To create a promising, expandable and effective site of any complexity, you should start with a simple one. This process is not easy, it requires certain basic knowledge of PHP and MySQL, but if you look at it point by point, you can draw up a kind of “work plan” that will come in handy when creating new sites. Let's prepare the "core" and the base for the project. At first, it will be a regular business card site, but then, by adding functionality, it can be turned into anything. So let's get started.
1. Database preparation. Create the first table in the MySQL database
Create a new database, for example "mysite". Personally, I'm used to working with UTF-8 encoding, so I'll make a reservation right away: make sure that all text files of the site, the database itself, tables and table fields are in the same encoding.
Create a table in a new database. Let's call it "pages". This table will store the static pages of the future site and information about them. The table must contain the following fields:
- page_id - page ID (SMALLINT, primary key, auto_increment);
- page_alias - page alias for the CNC address string (VARCHAR, 255);
- page_title - title of the page in the browser window (VARCHAR, 255);
- page_meta_d - page meta description for meta tag description(varchar, 255);
- page_meta_k - meta keywords for the meta keywords tag (VARCHAR, 255);
- page_h1 - page title (VARCHAR, 255);
- page_s_desc - short description material, for example, if the site materials will be in the form of a blog (TEXT);
- page_content - the main text of the page, which will be displayed in the central column of the site (TEXT);
- page_publish - contains "Y" if the page is published, or "N" if it is hidden (CHAR, default is "Y").
Immediately after creating the table, insert the values for home page site. In the "page_alias" field for the main page, I suggest inserting the value "home". Meta tags - according to the theme of the entire site. In the same way, you can create other pages, for example, "About the company" with the "about" alias and its own meta tags, or "Contacts" with the "contacts" alias, etc.
2. Create a site configuration file
In the root folder of the site, which should be empty at this stage, we create a “cfg” folder, in it, using .htaccess, we close access with the “deny from all” directive. Create a core.php file with the following content:
// MySQL
class MyDB
{
var $dblogin = "root"; // YOUR DATABASE LOGIN
var $dbpass = ""; // YOUR DATABASE PASSWORD
var $db = "mysite"; // NAME OF THE BASE FOR THE SITE
var $dbhost="localhost";
var$link;
var$query;
var $err;
var $result;
var$data;
var $fetch;
Function connect() (
$this->link = mysql_connect($this->dbhost, $this->dblogin, $this->dbpass);
mysql_select_db($this->db);
mysql_query("SET NAMES utf8");
}
function close() (
mysql_close($this->link);
}
Function run($query) (
$this->query = $query;
$this->result = mysql_query($this->query, $this->link);
$this->err = mysql_error();
}
function row() (
$this->data = mysql_fetch_assoc($this->result);
}
fetch() (
while ($this->data = mysql_fetch_assoc($this->result)) (
$this->fetch = $this->data;
return $this->fetch;
}
}
function stop() (
unset($this->data);
unset($this->result);
unset($this->fetch);
unset($this->err);
unset($this->query);
}
}
This file contains only a simple database connection class for now, but in the future you can add various useful functions to it that will be available from anywhere in the site code. Don't forget to change your username and password for your database.
If you are working on a Windows environment, I can recommend using the . This editor has line numbering, and it easily translates text from one encoding to another. ATTENTION! If you work in UTF-8 encoding - convert files to UTF-8 without BOM - this will help to avoid problems in the future.
3. Create index.php - the main site controller
The configuration file has been created. Now we create index.php in the root folder of the site - this will be the main script of the site, a kind of "main controller". Contents of the index.php file:
define("INDEX", ""); // SET MAIN CONTROLLER CONSTANT
Require_once($_SERVER."/cfg/core.php"); // CONNECT THE CORE
// CONNECT TO DB
$db = new MyDB();
$db->connect();
// MAIN CONTROLLER
switch ($_GET) (
case "page":
include($_SERVER."/com/page.php");
break;
default:
include($_SERVER."/com/home.php");
break;
}
Include($_SERVER."/template.php");
$db->close();
The $_GET variable will tell the main controller which site component to load on request. Now our site has only two components: “page” and “main page” (in principle, you can get by with one component for displaying a regular page, but often the look of the main page of the site differs from the usual pages of menu items). The logic of the main controller is as follows: the name of the required component (the value of the $option variable) is extracted from the URL string, depending on its value, the file of the component itself is included (contained in the /com folder). The component file does all the necessary work, retrieves data from the database and writes it to variables to be passed to the design template. At the very end, the site design file is connected, into which all the variables and data extracted in the components are transferred. This sounds a lot more complicated than it works.
4. Create a normal page output component
In the root of the site, create a folder "com" - it will store the component files. A site component, in my understanding, is a file in which data is processed for different sections of the site. For example, the component of a regular page retrieves the title, description, and text of the material from the database and writes them to the variables $title, $meta_d, $meta_k, $content, etc. This data is then transferred to the design template (you can create your own design template for each component ) and displayed to the user as an HTML page. For example, a catalog component that can be created in the future would do almost the same thing, but with data about products - and there are specifics, other fields in the table, and so on. Therefore, for each functional section of the site, it is worth creating a separate component. In the MVC (Model-View-Controller) scheme, the component plays the role of a model.
Create a file "page.php" in the "com" folder. The contents of the file are as follows:
/* PAGE COMPONENT */
$alias = $_GET;
$query = "SELECT * FROM pages WHERE page_alias="".$alias."" AND page_publish="Y" LIMIT 1";
$db->run($query);
$db->row();
// COMPONENT VARIABLES
$id = $db->data;
$alias = $db->data;
$title = $db->data;
$h1 = $db->data;
$meta_d = $db->data;
$meta_k = $db->data;
$s_desc = $db->data;
$component = $db->data;
// IF THE PAGE DOES NOT EXIST
if (!$id) (
header("HTTP/1.1 404 Not Found");
$component = "ERROR 404! This page does not exist";
}
$db->stop();
5. Create the Home Page Display Component
The main page in our database is stored under the pseudonym "home", and so far it does not differ in its structure from the usual pages of the site - it's just an article. Nevertheless, we will create a separate component for it - for the future, so to speak.
The content of the "home.php" component in the "com" folder is almost the same as the content of the normal page component, except for the query string to the database and the name of the component. The query string now looks like this:
$query = "SELECT * FROM wx_pages WHERE page_alias="home" LIMIT 1";
6. Create a design template for the entire site
Create a template.php file in the root of the site. In fact, this is a normal web design layout in HTML + CSS format, only with PHP variables in the right places. Insert between title tags=$title?>, in the central column of the site insert=$component?>and so throughout the template we place the necessary variables that are declared in the components.
The root folder should also have "css" and "images" folders for design elements. In the file /css/style.css - you can customize the styles to your liking.
7. Clean links and .htaccess file
To create clean links, I use mod_rewrite with direct instructions for the rules for each component separately, since parsing the address bar using the controller itself is considered unnecessary functionality. The content of .htaccess at this stage is:
Rewrite Engine On
RewriteBase /
RewriteCond %(REQUEST_FILENAME) !-d
RewriteCond %(REQUEST_FILENAME) !-f
# FORBIDDEN FILES
RewriteRule .htaccess - [F]
RewriteRule template.php - [F]
# mod_rewrite RULES
RewriteRule page/(+)([\/](0,1))\.htm$ index.php?option=page&alias=$1 [L]
In the future, we will add rules for the search components, catalog, articles blog, etc. There is only one point: to convert links like "mysite.com/index.php?option=pages&alias=about" into a link like "mysite.com/pages/about.htm" - looks pretty nice. In development, try to avoid the $_GET array for safety reasons and don't rely on it. It is advisable to store only parameters for the main controller (the $option variable) and for the component (the $alias variable) in it.
Also, in each folder of the site, “just in case”, create an empty index.html file - this is necessary so that nothing is displayed when accessing the directory through the address bar.
Tags: php, mysql, site engine, controller, site creation, mvc
We only talked about static pages, that is, those that, no matter how the user interacts with them, always remain unchanged, and in order for their content or design to change, the page owner needs to edit the code manually.
Dynamic pages and what they need
In addition to static, there are also dynamic pages. Most of them are on the Internet now. The information is loaded from external sources, such as a database or other files. The content and formatting of such pages may change depending on the user's actions. To edit dynamic sites, it is not necessary to interfere with their code - it is enough to change the content in a specially designed file or database, which, by the way, is also a file, only structured in a certain way.
To create dynamic websites, just HTML and CSS is not enough. It also uses programming languages, as well as databases and query languages for them. Most often, modern dynamic sites are used in their HTML work, CSS, PHP, JavaScript, SQL. The first two abbreviations are already familiar to you firsthand, SQL is used to access databases, JavaScript is a client-side language whose commands are processed by the browser and are often used to show you all sorts of beauty like curtains or smoothly opening photos, but PHP is a server-side programming language , which works, among other things, with the content of the site and makes it dynamic, we will come into contact with it today.
An example of using the include command
In the previous article, I talked about the block layout of the site and cited as an example the simplest page(document index.html and the file associated with it style.css).
Now we will split the document index.html into several files, each of which will contain its own part of the page, which will help to further separate the code, improve the structure of the template and, in fact, make the page dynamic. For this purpose, we will use the PHP language, or rather, only one of its directives - the function include(), which includes one file within another.
1. Change the permission of the file created in the article about block layout index with .html on the .php to name the document index.php. File type .PHP indicates to the server that the document was written or uses inserts in the programming language of the same name.
2. In the folder with the page, create a directory blocks.
3. All supporting information (top, bottom, navigation and sidebar site) we will take out into separate files, which we will place in the folder blocks.
So, create four files in the blocks directory: header.php, navigation.php, sidebar.php and footer.php. Fill in the files with code.
header (site header)
4. Check the template folder structure. The files must be in the root index.php, style.css and directory blocks.
Folder structure blocks should be like this.
5. In file index.php delete the existing code and write a new one:
Main page content
In the browser, the index.php file looks exactly the same as before, but the structure of the template has completely changed. We will talk about what happened later, and now we will answer the question about the mysterious commands of the form .
Like HTML code, PHP code also has its own start and end designation. So, you need to start a PHP insert with the command , and end with the line ?> . Between these commands, the main code is written. In our case, this is just one command - include.
Function include() inserts code from another file into the file, making it possible to store different parts of the page in different documents, thereby reliably separating them from each other.
As a result of the actions performed, we got a dynamic page index.php, parts of which are loaded from different files. Thanks to this, you can create other pages by loading auxiliary elements from the folder files in the same way. blocks.
This approach is good because if you want to change, say, the name of a menu item on a site of 20-30 pages, then in a template with a newly created structure, you will need to make changes to only one file - blocks/navigation.php, and the menu will change immediately on all pages in which it is included. If the site were static, then to change the name of one menu item, you would have to make changes to every from 20-30 pages. The difference is obvious.
Last update: 1.11.2015
Now we will create a small site, which is designed to give an initial understanding of working with PHP.
To create programs in PHP, we need a text editor. The most popular program today is Notepad++.
Let's move on to the previously created directory C:\localhost , which will store all the site's documents. Let's create text file and let's call it index.html. Let's open it in text editor and add the following code to it:
Enter your details:
The html code contains a form with two text fields. When the button is clicked, the form data is sent to the display.php script, as it is specified in the action attribute.
Now let's create this script that will process the data. Add to folder c:\localhost new text file. Let's rename it to display.php. By default, php program files have the extension .php. So let's add the following code to the display.php file:
Here already in the html markup there are blotches of PHP code. Tags are used to add PHP expressions to a page, between which there are instructions for PHP language. AT php code we receive the form data and display it on the page.
Each individual PHP expression must end with a semicolon. AT this case we have three expressions. Two of them receive the submitted form data, for example $name = $_POST["firstname"]; .
$name is a variable that will hold some value. All variables in PHP are preceded by a $ sign. And since the form on the index.html page uses the POST method to submit, we can use the $_POST["firstname"] expression to get the value that was entered in the text field with the attribute name="firstname" . And this value gets into the $name variable.
With the echo statement, you can display any value or text that comes after the statement on the page. In this case (echo "Your name: ".$name . " " . $surname . ""), using a dot, the quoted text is concatenated with the values of the $name and $surname variables and displayed on the page.
Now let's turn to the input form by going to the address http://localhost:8080:
Enter some data and click on the submit button:
So, the script worked for us display.php, which received and displayed the submitted data on the page.
Precautions must be taken. Because the resource can turn out to be extremely dynamic. That and look, bite!
PHP and HTML
Now these two disciplines are almost connected together. Their tandem is the basis on which the "life" of most of the Internet is built. Of course, other server-side languages (Perl, ASP.NET) are also used in conjunction with html. But their prevalence on the World Wide Web, compared to PHP, is purely episodic.
According to statistics, the architecture of most resources on the Internet is built on the basis of php and html.
For many beginners, the relationship between these technologies seems incomprehensible. On the one hand, static html , which is interpreted by browsers on the client side. On the other hand, it is a programming language that is processed on the server. Therefore, before writing a site in php from scratch, we will give a simple example of the interaction of these two technologies:
- Let's create a new file with php extension;
- Let's put the following code there:
- Save the file to local server and open it in a browser. Then click on the right mouse button and context menu choose the item " View html pages ».
As you can see in the screenshot, the lineis not displayed in the html code of the page. Both in the browser and in the code, only the returned date and time are visible. This means that the script was processed on the server side. Therefore, creating a site in php is fundamentally different from writing simple html pages.
Dynamic site
There are two main types of websites today:
- Static - created only on html based. Such sites do not change their content in response to user actions. Of course, a static resource can respond to events and user actions. But the client-side implementation of page dynamism has a narrow scope, limited by the capabilities of Java Script.
The Java Script code runs in the browser on the client side.
- Dynamic - capable of changing their state and content - html pages of dynamic sites are formed on the fly at the time of code execution in response to a user request sent by him from the browser to the server. Most often, page generation on the server side occurs using code written in php .
A dynamic php site consists of the following files:
- index.php is the main project file;
- Templates - include the structure of a particular part of the page ( caps, basement, main body);
- CSS files - store all the style descriptions of the resource.
In addition, the site project may consist of files that store the code of php functions and methods. And also include a database.
In most CMS, the content source for filling pages dynamically generated on the server side is the database. The most commonly used database is MySQL.
How to write a website in PHP
To understand how a site is created in php, consider practical example. Of course, much of it is simplified, but the entire mechanism of work and the stages of creation are preserved.
I have an html site with the following structure and design:
His code: