Creation of pages with php articles. PHP

2017-01-10


We create a dynamic website with using php

Hello dear visitor!

Today from home page using the tongue PHP programming let's create dynamic page, which will subsequently be generated on the server with each user request.

Thus, by changing the structure of the site and filling it with similar changing pages, we will get a dynamic site, which will greatly simplify it in the future technical support and development compared to the static option.

  • Why do you need a dynamic website?
  • How to convert a static site to a dynamic one
  • We form blocks of a dynamic site
  • Converting a web page from static to dynamic
  • Site source files

Why do you need a dynamic website?

Why a dynamic website is needed was discussed at the very beginning step by step instructions See the article Installing a local Denwer web server, where the need to install a local web server was explained. Therefore, we can go back and refresh this question.

Also, if you want to further consider the pros and cons of static and dynamic sites, we can advise you to read the pages of the online directory "Puzzleweb.ru" with the section Types of sites, where quite succinctly, but at the same time clearly given explanations for different site options.

screenshot 12

We can only add to this that in order to get a truly full-fledged Internet resource, it is impossible to skip this step and remain with the static site option.

Therefore, we will no longer delve into theoretical discussions of the need to create a dynamic site, but will move on to consider the question of how we will do this.

How to convert a static site to a dynamic one

As you know, the fundamental difference between a dynamic and a static site is that in a static site, ready-made web pages lie on the server and wait their turn to be sent to the user’s browser. Moreover, if the pages have even minor differences, say the difference is only in one phrase or even in one word, then these will still be separate pages.

In the dynamic version, pages are generated on the server with each user request, depending on the requested information.

Simply put, this can be compared to a construction set, where a large number of different shapes can be made from a limited number of elements. Moreover, if you make any change to one of the elements, it will be reflected in the entire structure that includes this element.

Based on this, we will make from our created main page something like a constructor, consisting of certain elements (in our case, these will be files), from which web pages will subsequently be assembled according to user requests.

To explain the actions that we will perform for this, we will use the HTML code of the main page frame obtained at one of the stages of creating a site in the article.

  1. "utf-8" >

    <span><b>Page title</b> </span>

    "Description" content = "Brief description of page content" >

  2. "wrapper" >

    A cap

    Rotator

    Main content

    Sidebar

    Basement

As you can see from the HTML code, the container , designed to accommodate the visible part of the web page, contains the following main blocks:

  • A cap;
  • Rotator;
  • Main content;
  • Sidebar;
  • Basement.

However, you need to pay attention to the fact that four of the five blocks are common, and only one “Main content” block will be different for each page.

To obtain elements of a dynamic site, we will separate the content from these blocks into separate files, which we will later include when assembling various web pages based on user requests.

Now, at this stage there will be only five of these files. But in the future, when pages or additional functionality are added to the site, new files will be connected, and so on, as needed.

This construction of the site structure will allow you in the future not to have to deal with the routine work of changing the HTML code of all pages in the event of replacing or adding any fragment common to them. In such cases, it will be enough to make changes only to a specific file, and the entire replacement procedure will be completed. As you can see, there is an advantage.

But in order to do this, we will need the PHP language, with which web pages will be able to access these selected blocks and transfer their contents to themselves.

If anyone has never had to deal with the PHP language, then it is advisable to get to know it better, since PHP is one of the most important tools for website development. This can be done by using various kinds of reference literature, which can be found in large quantities on the Russian Internet.

As an option, the already mentioned reference book “Puzzleweb.ru”, in which one of its parts is devoted to the topic of PHP. For a more in-depth study of PHP, you can also use a specialized reference book tailored specifically for this language, posted on the website "php.ru". Using the link "https://php.ru/manual/control-structures.intro.html" you can get to its "Introduction" page, from where you can easily select any section of the directory you are interested in.

But in order to now make a dynamic website and provide the ability to connect files to HTML pages, it is enough to use only one language instruction (in PHP, any script consists of a sequence of instructions). This can be one of four possible instructions for connecting files:

  • include;
  • require;
  • include_once;
  • require_once.

There is no point in describing their features here, since this is explained in detail in reference books, for example, using the link “http://www.puzzleweb.ru/php/26_inc_files.php” you can understand this well.

When creating a site, we will use the “require_once” instruction; I usually use this option, for me it is the most convenient.

Well, now that we have figured out what we will do, let’s move on to practical actions.

We form blocks of a dynamic site

In order to form blocks that will then participate in the assembly of web pages, you first need to create them. This is done in the Notepad++ text editor in the same way as we created the first site file “index.html” in the article Create a web page and host it on a local web server. Only in this case the extension should be specified not “html”, but “php”. In this case, you must definitely pay attention to the encoding in order to avoid the appearance of various kinds of incomprehensible characters on the pages in the future.

We will create the files in a separate, newly created “blocks” folder. For files that are common to all pages, we will assign names taking into account the names of the corresponding blocks. And for the “main” block we will indicate a specific name for each page of the site.

Thus, for the main page we will connect a file called “block_glavnaya” to the “main” block. For the rest: "header", "section", "aside" and "footer".

When creating files, you can also take into account that to simplify this procedure, you can copy them using the "File" menu, specifying the new file name when saving "Save As".

In general, creating files is a standard procedure, so there shouldn’t be any difficulties. In the end it should look like this.


Then we copy the contents of each block and transfer it to the appropriate file. Using "header.php" as an example, let's look at this in more detail.

1. Open the file “index.html” in the Notepad++ editor, select the desired area of ​​the “header” block and alternately click the right and left mouse buttons and copy it to the clipboard.

It should be noted that here we are copying all the contents of the block with the exception of the menu. This is because to reflect the active menu button in the tag attributes

  • it is necessary to assign a value to the class class for each page "activ". The same applies to a similar fragment in the "footer" block.

    In the future, we will also move these menu fragments in the “header” and “footer” blocks into separate files, but for now we will not complicate things and leave them in the same place.

    How to select and copy a fragment of the "header" block to the clipboard is shown in the screenshot below.



    3. And finally, in order to move the contents of a file in Notepad++ to the left, you need to press “Tab” several times while holding down the “Shift” button. As a result, we will get the generated “header.php” file in the following form.


    We will do the same for other files. Below, the screenshots show how their contents will look after all the necessary steps are completed.


    Fig.6 File "section.php"


    Fig.7 File "block_glavnaya.php"


    Fig.8 File "aside.php"


    Fig.9 File "footer.php"

    Thus, we have received all the files to create a dynamic page, and we can now go directly to its HTML code.

    Converting a web page from static to dynamic

    In order to ensure that our main page loads the files that were created in the previous section, we must first change the extension of the "index" file from "html" to "php", and then open it again in the Notepad++ editor and make the following changes:

    • Delete the contents of blocks that were previously transferred to newly created files.
    • In the free space, write the instructions “require_once” in PHP, indicating the path to the corresponding files.
    • In menu tags
    • , which indicate the path to the pages, for the main page replace the extension from “html” to “php”, and for others indicate the names of the newly created pages.
    • Indicate "Home" in the title.

    After completing these operations, our main page should look like this.


    From the above screenshot you can see that all PHP instructions are highlighted with an opening tag. This designation is used to indicate when to start and stop processing code written in PHP. Therefore, in the future, all PHP codes will be highlighted with this designation.

    You can also note that the names of the new pages are made taking into account their purpose, so the structure and code of the site is better perceived.

    This is where all our transformations ended. And now, if we open the main page in the browser again, we should not see any changes with the previous version of the site, it should open the same as before. But, if the result turns out to be something wrong, then you need to look for the mistake in the above operations.

    Let's update the browser now and try to open the main page.


    As you can see, in our case the main page opened without any problems. But, unlike the previous work of the site, the page acquired this appearance as a result of its formation on the server when processing the request.

    Thus, our site now has its first dynamic page. And after adding other similar pages to it, this site can rightfully be called dynamic with all the ensuing consequences, i.e. it will have all the advantages inherent in dynamic sites. And we will be able to verify this when we fill it with various kinds of functionality in the future.

    With this we will complete this important stage of website development and in the next article we will create new dynamic pages for it. The source codes for the latest version of the site can be downloaded, as usual, from the link at the end of the article.

    Site source files

    The source files of the site with the updates that were made in this article can be downloaded from the attached additional materials.

    Hello! Now we will try to implement the simplest registration on the site using PHP + MySQL. To do this, Apache must be installed on your computer. The working principle of our script is shown below.

    1. Let's start by creating the users table in the database. It will contain user data (login and password). Let's go to phpmyadmin (if you are creating a database on your PC http://localhost/phpmyadmin/). Create a table users, it will have 3 fields.

    I create it in the mysql database, you can create it in another database. Next, set the values ​​as in the figure:

    2. A connection to this table is required. Let's create a file bd.php. Its content:

    $db = mysql_connect("your MySQL server","login for this server","password for this server");
    mysql_select_db ("name of the database we are connecting to", $db);
    ?>

    In my case it looks like this:

    $db = mysql_connect("localhost","user","1234");
    mysql_select_db("mysql",$db);
    ?>

    Save bd.php.
    Great! We have a table in the database and a connection to it. Now you can start creating a page on which users will leave their data.

    3. Create a reg.php file with the contents (all comments inside):



    Registration


    Registration


















    4. Create a file, which will enter data into the database and save the user. save_user.php(comments inside):



    {
    }
    //if the login and password are entered, then we process them so that tags and scripts do not work, you never know what people might enter


    //remove extra spaces
    $login = trim($login);
    $password = trim($password);
    // connect to the database
    // check for the existence of a user with the same login
    $result = mysql_query("SELECT id FROM users WHERE login="$login"",$db);
    if (!empty($myrow["id"])) (
    exit("Sorry, the login you entered is already registered. Please enter another login.");
    }
    // if this is not the case, then save the data
    $result2 = mysql_query("INSERT INTO users (login,password) VALUES("$login","$password")");
    // Check if there are errors
    if ($result2=="TRUE")
    {
    echo "You have successfully registered! Now you can enter the site. Home page";
    }
    else(
    echo "Error! You are not registered.";
    }
    ?>

    5. Now our users can register! Next, you need to create a “door” for already registered users to enter the site. index.php(comments inside) :

    // the whole procedure works in sessions. It is where the user's data is stored while he is on the site. It is very important to launch them at the very beginning of the page!!!
    session_start();
    ?>


    Home page


    Home page











    Register



    // Check if the login and user id variables are empty
    if (empty($_SESSION["login"]) or empty($_SESSION["id"]))
    {
    // If empty, then we do not display the link
    echo "You are logged in as a guest
    This link is only available to registered users";
    }
    else
    {

    In file index.php We will display a link that will be open only to registered users. This is the whole point of the script - to limit access to any data.

    6. There remains a file with verification of the entered login and password. testreg.php (comments inside):

    session_start();// the whole procedure works on sessions. It is where the user's data is stored while he is on the site. It is very important to launch them at the very beginning of the page!!!
    if (isset($_POST["login"])) ( $login = $_POST["login"]; if ($login == "") ( unset($login);) ) //enter the login entered by the user into $login variable, if it is empty, then destroy the variable
    if (isset($_POST["password"])) ( $password=$_POST["password"]; if ($password =="") ( unset($password);) )
    //put the user-entered password into the $password variable, if it is empty, then destroy the variable
    if (empty($login) or empty($password)) //if the user did not enter a login or password, then we issue an error and stop the script
    {
    exit("You have not entered all the information, go back and fill out all the fields!");
    }
    //if the login and password are entered, then we process them so that tags and scripts do not work, you never know what people might enter
    $login = stripslashes($login);
    $login = htmlspecialchars($login);
    $password = stripslashes($password);
    $password = htmlspecialchars($password);
    //remove extra spaces
    $login = trim($login);
    $password = trim($password);
    // connect to the database
    include("bd.php");// the bd.php file must be in the same folder as all the others, if it is not then just change the path

    $result = mysql_query("SELECT * FROM users WHERE login="$login"",$db); //retrieve from the database all data about the user with the entered login
    $myrow = mysql_fetch_array($result);
    if (empty($myrow["password"]))
    {
    //if the user with the entered login does not exist
    }
    else(
    //if exists, then check the passwords
    if ($myrow["password"]==$password) (
    //if the passwords match, then we launch a session for the user! You can congratulate him, he got in!
    $_SESSION["login"]=$myrow["login"];
    $_SESSION["id"]=$myrow["id"];//this data is used very often, so the logged in user will “carry it with him”
    echo "You have successfully entered the site! Home page";
    }
    else(
    //if the passwords do not match

    Exit ("Sorry, the login or password you entered is incorrect.");
    }
    }
    ?>

    OK it's all over Now! The lesson may be boring, but very useful. Only the idea of ​​registration is shown here, then you can improve it: add protection, design, data fields, loading avatars, logging out of the account (to do this, simply destroy the variables from the session with the function unset) and so on. Good luck!

    I checked everything, it works properly!

    Many readers in any book about computers skim over everything that is not of immediate interest and move on to what they really need. want know. Personally, that's what I do. However, there is nothing wrong with that - there are rarely technical books that need to be read from cover to cover. Or maybe that's what you did - skipped the initial eight chapters and picked up this chapter because it had the most interesting title? And who wants to waste time on details when another project is on fire at work?

    Fortunately, such haste will not prevent you from properly mastering the material in the second part of the book, which is devoted to using PHP to build sites and interact with the Web. In this chapter, you will learn how to easily modify the content of web pages and navigate the Web using links and various standard functions. The next chapter will complement the material presented - it examines in detail the means of interaction with the user in HTML forms. Chapter 11 describes the organization of the interface with databases. The remaining chapters of the second part discuss non-trivial aspects of web programming in PHP.

    However, it should be remembered that the material in Part 1 absolutely necessary for normal knowledge of PHP. It is assumed that you have already read Part 1, so the examples will use many of the concepts described earlier. So, if you skim through part of the book, you will have to go back to previous chapters from time to time and catch up.

    Simple links

    <а href = "date.php">

    $link = "date.php";

    print "<а href = \"$link\">View today's date
    \n"

    You are probably wondering why there is a backslash (\) before the quotes (") in the link code? The fact is that quotes in PHP are special characters and are used as line delimiters. Therefore, quotes are literals in strings must be shielded.

    If having to escape quotes annoys you, simply enable the magic_quotes_gpc mode in your php.ini file. The result is all apostrophes, quotes, backslashes and null characters. are automatically escaped in the text!

    Let's develop the given example. To quickly display a list of links in the browser, you can use an array:

    // Create an array of sections

    $contents - array("tutorials", "articles", "scripts", "contact");

    // Iterate through and sequentially display each element of the array

    for ($i = 0; $i< sizeof($contents; $i++)

    print " ".$contents[$i]."
    \n";

    // - special designation for marker point endfor;

    File components (templates)

    We've come to one of my favorite PHP features. A template (in relation to web programming) is a part of a web document that you are going to use in several pages. Templates, like PHP functions, save you from unnecessary copying/pasting of page content and program code. As the scale of the site increases, the importance of templates increases, since they allow easy and quick modifications at the level of the entire site. This section will describe some of the possibilities that open up when using simple templates.

    Typically, common pieces of content/code (i.e. templates) are saved in separate files. When building a web document, you simply “include” these files in the appropriate places on the page. In PHP there are two functions for this: include() and require().

    include() and require()

    One of the most outstanding aspects of PHP is the ability to build templates and programming libraries and then insert them into new scripts. Using libraries saves time and effort in using common functionality across different websites. Readers with

    experience programming in other languages ​​(such as C, C++ or Java), and are familiar with the concept of function libraries and their use in programs to extend functionality.

    Including one or more files in a script is done using the standard PHP functions require() and include(). As will be shown in the next section, each of these functions applies in a specific situation.

    Functions

    There are four functions in PHP for including files in PHP scripts:

    • include();
    • include_once();
    • require();
    • require_once().

    Despite the similarity of names, these functions solve different problems.

    The include() function includes the contents of a file into the script. The include() function syntax is:

    include(file file]

    The include() function has one interesting feature - it can be executed conditionally. For example, if a function call is included in an if command block. then the file is included in the program only if the condition i f is true. If the includeO function is used in a conditional command, then it must be enclosed in curly braces or alternative delimiters. Compare the differences in syntax between Listings 9.1 and 9.2.

    Listing 9.1. Incorrect use of include()

    if (some_conditional)

    include("text91a.txt"); else

    include("text91b.txt");

    Listing 9.2. Correct use of include()

    if (some_conditional) :

    include("text91a.txt");

    include("text91b.txt");

    All PHP code in the include file Necessarily lies in PHP tags. Don't assume that simply saving a PHP command to a file will ensure it is processed correctly:

    Instead, you need to wrap the command in appropriate tags, as the following example shows:

    print "this is an invalid include file";

    The include_once() function does the same thing as include(), with one exception: before including a file in the program, it checks to see if it has already been included. If the file has already been included, the include_once() call is ignored, and if not, the standard file inclusion occurs. In all other respects, include_once() is no different from include(). The include_once() function syntax is:

    include_once(file file)

    In general, the require() function is similar to include() - it also includes the template in the file in which the require() call is located. The require() function syntax is:

    require (file file)

    However, there is one important difference between the require() and include() functions. The file specified by require() is included in the script regardless of the location of require() in the script. For example, if you call requi re() in an if block, if the condition is false, the file will still be included in the script!

    In many situations, it is convenient to create a file with variables and other information that is used throughout the site, and then include it as needed. Although the name of this file is arbitrary, I usually call it init.tpl (short for "initializaion.template"). Listing 9.3 shows what a very simple init.tpl file looks like. In Listing 9.4, the contents of init.tpl are included in the script with require().

    Listing 9.3. Example of an initialization file

    $site_title = "PHP Recipes";!}

    $contact_email = " [email protected]";

    $contact_name = "WJ Gilmore";

    Listing 9.4. Using the init.tpl file

    <? print $site_title; ?>

    \"mai1 to:$contact_email\">$contact_name."; ?>

    Passing a URL when calling require() is only allowed if the “URL fopen wrappers” mode is enabled (this mode is enabled by default).

    As the size of the site increases, it may turn out that some files are included in the script several times. Sometimes this doesn't cause a problem, but in some cases, including the file again causes the values ​​of the changed variables to be reset. If the include file defines functions, naming conflicts may occur. With that said, we come to the next function - require_once().

    The require_once() function ensures that the file is included in the script only once. Once requi re_once() is called, all further attempts to include the same file are ignored. The syntax of the require_once() function is:

    You'll likely start using file inclusion features more often as your web applications begin to grow in size. These functions appear frequently in examples in this book to reduce code redundancy. The first examples are discussed in the next section on the principles of constructing basic templates.

    Building Components

    When defining the structure of a typical web page, I usually break it down into three parts: header, body, and footer. As a rule, most properly organized websites have a header that remains virtually unchanged; the main part displays the requested content of the site, so it changes frequently; Finally, the footer contains copyright information and navigation links. The footer, like the header, usually remains unchanged. Don't get me wrong - I'm not trying to suppress your creative aspirations. I've seen many great websites that don't follow these principles. I'm just trying to come up with a general structure that can serve as a starting point for further work.

    Heading

    A header file (like the one in Listing 9.5) appears in almost every one of my PHP-enabled websites. This file contains

    site-wide information, such as the title, contact information, and some HTML page code components.

    Listing 9.5. Example header file

    // File: header.tpl

    // Purpose: header file for the PhpRecipes website.

    $site_name = "PHPRecipes";

    $site_email= " [email protected]";

    $site_path = "http://localhost/phprecipes";

    <? print $site_name; ?>

    // Print current date and time

    print date("F d, h:i a");

    Quite often, access to included files by visitors is restricted, especially if these files contain sensitive information (for example, passwords). In Apache, you can prevent certain files from being viewed by editing the http.conf or htaccess files. The following example shows how to prevent viewing of all files with a .tpl extension:

    Order allow,deny

    Allow from 127.0.0.1

    PHP and website security issues are covered in detail in Chapter 16.

    Running title

    The footer is usually the information located at the bottom of the pages of a site - contact information, links and copyright information. This information can be placed in a separate file and included as a template in the same way as a header. Let's say that with the onset of the new year you need to change the copyright information and bring it to the form “Copyright © 2000-2001”. There are two options: Spend Christmas Eve frantically editing hundreds of static pages. or use a template like the one shown in Listing 9.6. One simple change and you can get back to your holiday routine.

    Listing 9.6. Example footer file (footer.tpl)

    contact |

    your privacy

    Note the use of the $site_email global variable in the footer file. The value of this variable is page-wide, and we assume that the header.tpl and footer.tpl files will be included in one final page. Also notice the presence of $site_path in the Privacy link. I always include the full path to all links in my templates - if the link URL were just privacy.php, the footer file would be hardcoded to a specific directory.

    Main part

    The main part of the page includes the contents of the header and footer. In essence, it is the main part that contains the information that interests site visitors. The header looks impressive, the footer contains useful information, but it is for the main part of the page that users return to the site again and again. Although I can't provide any advice on specific page structure, templates like the one in Listing 9.7 greatly simplify page administration.

    Listing 9.7. Example of the main part of the page (index_body.tpl)

    /tutorials.php">tutorials

    articles

    scripts

    contact

    Welcome to PHPRecipes. the starting place for PHP scripts, tutorials,

    and information about gourmet cooking!

    All together: header, footer and body

    Perhaps my mood is best summed up by a line from Colonel “Hannibal” Smith (George Peppard) from the famous TV series “The A-Team”: “I love it when things fall into place.” I'm experiencing something similar where disparate templates come together to form a complete web document. By combining three document sections: header.tpl, index_body.tpl, and footer.tpl, you can quickly build a simple page like the one shown in Listing 9.8.

    Listing 9.8. Building an index.php page by including several files

    // File: index.php

    // Destination: PHPRecipes home page

    // Print title

    include("header.tpl");

    // Output the main part

    include("index_body.tpl");

    // Display the footer

    include("footer.tpl");

    So how? Three simple commands and you have a finished page. The text of the final page is shown in Listing 9.9.

    Listing 9.9. HTML page built in Listing 9.8 (index.php)

    PHPRecipes

    August 23, 03:17 pm

    tutorials

    articles

    scripts

    contact

    Welcome to PHPRecipes, the starting place for PHP scripts, tutorials,

    and gourmet cooking tips and recipes!

    3. Create a file footer.php.

    Copyright 2000 PHPRecipes. All rights reserved.

    contact |

    your privacy

    In Fig. Figure 9.1 shows how the resulting page looks in a browser. Although I don't usually use table borders, this time I drew them out to make the three parts of the page stand out more clearly in the illustration.

    Rice. 9.1. Appearance of the page built in Listing 9.8

    Template optimization

    In the second (in my opinion, more preferable) option, the templates are designed as functions located in a separate file. This provides additional structure to your templates. I call this file the initialization file and store other useful information in it. Since we've already looked at relatively long header and footer examples, Listings 9.10 and 9.11 have been slightly shortened to illustrate the new idea.

    Listing 9.10. Optimized site template (site_init.tpl)

    // File: site_init.tpl

    // Purpose: PhpRecipes initialization file

    $site_name = "PHPRecipes";

    $site_email = " [email protected]";

    $site_path = "http://localhost/phprecipes/";

    function show_header($site_name) (

    <? print $site_name: ?>

    This is the header

    function show footer()

    This Is the footer

    Listing 9.11. Using an initialization file

    // Include initialization file

    include("site_init.tpl");

    // Print title

    show header($site_name);

    // Body content This is some body information

    // Display the footer Show_footer();

    Project: page generator

    Although most of the websites I've created have generated the main page content based on information read from a database, there are always a few pages that remain virtually unchanged. In particular, they can display information about the development team, contact information, advertising, etc. I usually store this “static” information in a separate folder and use a PHP script to load it when a request comes in. Of course, you have a question - if this is static information, what is the PHP script for? Why not load regular HTML pages? The benefit of PHP is that you can use templates and insert static snippets as needed.

    <а href = "/static.php?content=$content">Static Page Name

    Let's start by creating static pages. For simplicity, I'll limit myself to three pages containing site information (Listing 9.12), advertising (Listing 9.13), and contact information (Listing 9.14).

    Listing 9.12. Information about the site (about.html)

    About PHPRecipes

    What programmer doesn't mix all night programming with gourmet cookies. Here at PHPRecipes. hardly a night goes by without one of our coders mixing a little bit of HTML with a tasty plate of Portobello Mushrooms or even Fondue. So we decided to bring you the best of what we love most: PHP and food!

    That's right, readers. Tutorials, scripts, souffles and more. 0nly at PHPRecipes.

    Advertising Information

    Regardless of whether they come to learn the latest PHP techniques or for brushing up on how

    to bake chicken, you can bet our readers are decision makers. They are the Industry

    professionals who make decisions about what their company purchases.

    For advertising information, contact

    ">[email protected].

    Listing 9.14. Contact details (contact.html)

    Contact Us

    Have a coding tip?

    Know the perfect topping for candied yams?

    Let us know! Contact the team at [email protected].

    Let's move on to building the static.php page, which displays the requested static information. This file (see Listing 9.15) includes the page components of our site and the initialization file site_init.tpl.

    Listing 9.15. General output of static pages (static.php)

    // File: static.php

    // Purpose: displaying requested static pages.

    // WARNING: this assumes that the file is "site_init.tpl" and that's it

    // static files are in the same directory.

    // Load functions and variables include("site_init.tpl"):

    // Display the header show_header($site_name);

    // Output the requested content include("$content.html"):

    // Display the footer show footer();

    Now everything is ready to build the main scenario. Just include it in the page

    <а href = "static.php?content=about">Static Page Name

    Advertising Information

    Contact Us

    If you click on any of these links, your browser will load the corresponding static page embedded in static.php!

    Results

    In this chapter, you became acquainted with the primary task for which PHP was created - dynamically building web pages. The following issues were considered:

    • URL processing;
    • building dynamic content;
    • inclusion and construction of basic templates.

    The chapter ends with a page generator, a program that loads static pages into a template and makes it easy to support large numbers of static HTML pages.

    The next chapter focuses on using PHP in combination with HTML forms to greatly enhance the interactivity of your site. And then - interaction with databases! You have a lot of interesting things to learn.

    There are a huge number of websites on the Internet. All these sites can be divided into two types: static and dynamic. Today we will talk about creating dynamic pages, but first I would like to tell you what a static and dynamic site (page) is.

    Static sites

    Static sites consist of static web pages. This means that no matter what the user does, the page always looks the same. Such pages are stored on the server as HTML documents. Static pages are typed manually. If you need to change the content of a page, you have to edit the HTML code for each page.

    Advantages:

    • Simplicity and low cost of creation, low requirements for hardware resources;

    Flaws:

    • Large amounts of time spent editing content;
    • Inappropriate for use in large projects.

    Dynamic sites

    Dynamic sites consist of dynamic web pages that can respond to user actions and change. Such pages are formed by a web server from several files (templates). All information is stored in a database. When a user requests a page, the relevant information is retrieved from the database, inserted into a template to form a web page, and sent by the web server to the user's browser. Thus, when updating the site's content, you simply need to add text for the new page, which is then inserted into the database using a specific mechanism.

    Advantages:

    • Content management is done through special forms where you can easily add, edit and delete information;
    • Maximum efficiency when adding new content to the site;
    • When adding or editing content, no special knowledge in the field of web mastering (HTML, CSS) is required;
    • Ability to create large multifunctional projects;
    • Great opportunities for promotion.

    Flaws:

    • High cost of creation and maintenance;
    • You need to have the appropriate knowledge to maintain the functionality of the site.

    Now I think you understand that it is best to make a website using dynamic pages because... it is the best and convenient choice. Well, now let's talk about creating dynamic pages.

    Simple links

    Before learning the PHP language, I think you should already know HTML and, of course, creating hyperlinks. I would like to remind you:

    $link = "example.php"; print "<а href = \"$link\">An example of a dynamic hyperlink.
    \n"

    This is how easy it is to create a dynamic hyperlink using the PHP language.

    Dynamic page creation process

    The process of creating a dynamic page consists of several stages:

    Laying out the page frame. Let's call the page index.php - it will consist of parts: header, footer, left menu. In this example, I will show how a page is laid out based on tables, but you can also use block layout.

    1. Create a file header.php.

    Dynamic page in PHP.

    Site header


    2. Create a file leftmenu.php.

    • Link 1
    • Link 2
    • Link 3
    • Link 4
    • Link 5

    Site footer




    Create a folder called template, into which copy the received files. If you need to edit the header, left menu or footer of the site, you will know that the templates for these parts of the site are located in this folder.

    Let's connect the received files (templates) to the site using the include statement using the index.php page as an example.

    Hello!

    This is the first dynamic page in PHP.

    This is how the index.php page is a dynamic page, it will be formed from several files (templates). You can make any number of such templates. If you need to change any part of the site, just find the required template file and edit it.

    This completes the creation of dynamic pages. I think you understand the meaning and practicality of dynamic sites and based on my example you will be able to create a large project. And don’t forget to comment on your code - this is very important, friends! Good luck to you!

    P.S. Minor changes from 07/06/2019:

    Since programming is always evolving, it must therefore evolve at the speed of light. The tabular layout shown above is rarely used in practice these days and is only necessary for learning by novice programmers.

    If you want to create new and effective websites, then we recommend using block layout rather than table layout. Let's take a closer look.

    Tables were invented specifically for displaying tabular data, and not for marking up page elements. What is in the table:

    text

    can be presented in the form of a block (div) layout:

    text

    it takes up much less disk space.

    Let's consider the advantages of block layout compared to tabular layout:

    1. A significant reduction in page size, usually by 2–3 times, which significantly reduces the loading time of a website. At the same time, the size of the -file will increase slightly, but due to the fact that it is cached once by the user’s browser and when accessing other pages it is read from his computer, as a result the site loads much faster than a tabular one.
    2. It is much more convenient to change the design of website pages, put into a CSS file. In this case, there is practically no need to edit the code.
    3. Thanks to the capabilities of block layout, you can ensure that the main content of the page comes first in the code, and only then the header, left and/or right columns. However, the appearance of the page will not change at all.
    4. The transparency of the block page code is visually pleasing - there are no clutter of tags, everything is very beautiful and compact.


    So, friends, if you have reached this lesson, then you have managed to either install a local server or buy hosting on which you can work with PHP. Congratulations - this is a big step!

    I’ll say briefly about PHP - this programming language is used all over the world and you can use it to create websites of all levels of complexity, from business card websites to large portals. I think it’s no secret to many that the largest social networks facebook.com(from scratch in php) and vk.com(php engine) were written in PHP. So let’s draw conclusions and get to work!)

    How the code works

    PHP code processed on the server side. That is, there is no finished page. For example, the code gives a command to collect data on how many users are currently registered on the site. A site visitor clicks on a link All users. He wants to get dynamic data, that is, those that are constantly changing. After the counting on the server is completed, data will be sent from the server in the form of a generated HTML code for a page with the number of users. As a result, after clicking a request on the link, the user receives a page. If you view the code of the resulting page, you will only see HTML, and the PHP code will not be viewable. Roughly speaking, PHP is instructions to the server on how and from which blocks to make a page.

    What does PHP code look like and where to insert it?

    PHP code can be embedded directly into HTML. PHP code is embedded in HTML pages using angle brackets and a question mark , however, you can limit yourself to brackets with question marks . You will only need to change the file extension, for example from .html on .php

    PHP code(file index.php)



    PHP usage example


    echo "Hello, world!";
    ?>





    Demonstration Download sources
    The result of the code will be plain text output Hello World!. You may ask why write PHP code to display plain text? echo operator, which we’ll talk about a little later, is needed not just for displaying text. More often echo is used to display the result of some function that performed calculations or took data from the database (What is a Database?). That is for display dynamic data.

    echo statement in PHP

    As you already understood, the operator echo needed for data output. We take the content (in our case only text for now) into quotes, and put a semicolon at the end ; this marks the end of the operator's work.

    In programming, when creating the first page, it is customary to use the phrase Hello, World!- that is Hello World! This is exactly what we use. In the example we will not use html, since this is not necessary.

    PHP code

    echo "Hello World!";
    ?>
    The program will print Hello World!.
    In the very first example, we inserted a small PHP code into the html. Now, on the contrary, let’s introduce html elements into the php code.

    PHP code

    echo " ";
    echo " ";
    echo " My first PHP script";
    echo "";
    echo " ";
    echo "

    Hello World!

    ";
    echo "";
    ?>
    As a result, we get a blank page with a title Hello World!

    The print statement in PHP

    Unlike the echo operator, print outputs data taking into account spaces and text breaks. It has some limitations - you can only use one argument, echo several. Takes longer to complete than echo. In the future, we will resort to this operator when writing functions.

    print "Hello World!
    Second line of text"; // the result will be printed in two lines
    ?>
    The text will be displayed the same way it was written.

    Output operator - heredoc PHP syntax

    As you have already noticed, displaying a page by constantly using the echo operator is ugly and unreadable. Therefore, to output large parts of html code there is another output operator using heredoc syntax. It also displays the data in the same form as it was (spaces and hyphens).

    echo<<

    Example


    An example of outputting a large amount of text using html


    The second paragraph of the same voluminous text.


    HERE;
    ?>

    Lesson reminder

    PHP code can:

    1. do not contain any html elements. The page and text will still be displayed. html is needed for beautiful content markup.

    2. be both included in the html code and contain it inside its output statements (echo, print, etc.). The main thing is not to forget the design

    3. pages with php code must have the appropriate extension: .php .phtml

    In the next lessons we will look at the basics of creating websites in PHP, in which you will see all the advantages of using this language!

    Thank you for your attention!