Dynamic pages in PHP. PHP. Dynamic page creation Create a regular page rendering component

In the last lesson, we figured out what blocks the trip template will consist of, so we can get to work. First, let's create two folders:

images - this folder will contain any graphic files used to design the template. Because We don’t have any design developments yet, then drop any one graphic file into this folder, otherwise Joomla will not install the template and will give an error if the folder is empty.

ATTENTION: The template images folder does not contain content graphics!

css - this folder will contain cascading style sheet files. First, let's place an empty template.css file in it, which will be used to assign different design styles to site elements.

Next, you can begin to create the main file index.php, which will determine the visual arrangement of site elements and tell the Joomla CMS in which block to place various components and modules. The file is a combination of PHP and HTML.

I always use only Macromedia Dreamweaver when writing code. An excellent program, I strongly recommend it to beginners, because... If you made a mistake while working on the code, the program will definitely highlight your mistake.

On the site you will find a tutorial for Macromedia Dreamweaver. If you are going to develop websites, then you should master this program, at least at the initial level, in order to edit template codes without errors.

The positioning of page elements (blocks) is done using HTML code; specifically, we will use DIV tags. But the way our site will work on the Joomla engine, i.e. It will be dynamic, then you will also have to use the PHP language. With its help, we will determine in which blocks the positions for outputting modules will be located, and what these positions will be called, whether the blocks will be collapsed or not. We will connect style sheets from external files, the content language, set how the site size will change, etc.

index.php

File header

The file header consists of several parts. The first part of the PHP header code is to ensure that the file is not accessed directly, for security reasons.

< ?php
defined ("_JEXEC" ) or die ;
JHtml::_("behavior.framework" , true ) ;
$app = JFactory::getApplication() ;
?>
< ?php echo "< ?" ; ?> xml version="1.0" encoding=" < ?php echo $this-> _charset ?> "?>

DOCTYPE is a very important parameter based on which the browser decides how to render this page and how to interpret the CSS.

< ! DOCTYPE html PUBLIC "- / / W3C/ / DTD XHTML 1.0 Strict/ / EN""http: // www.w3.org/ TR/ xhtml1/ DTD/ xhtml1- strict.dtd">

The following snippet retrieves the installed language from the global configuration.

< html xmlns= "http:// www.w3.org/ 1999/ xhtml" xml:lang= " < ?php echo $this-> language; ?> " lang= " < ?php echo $this-> language; ?> " dir = " < ?php echo $this-> direction; ?> " >

Next is a piece of code that includes additional header information that is set in the global configuration. You can see this information by looking at the source code of any web page. In particular, these are meta tags, which you already know about.

< head>
< jdoc:include type= "head" / >

The following header lines contain links to the main Joomla CSS styles.

< link rel= "stylesheet" href= "< ?php echo $this-> baseurl ?> / templates/ system / css/ system .css" type="text /css" / >
< link rel= "stylesheet" href= "< ?php echo $this-> baseurl ?> / templates/ system / css/ general.css" type="text /css" / >

To use template design styles, we link to a file containing cascading style sheets template.css, which is located in the CSS folder. It doesn’t matter that this file is empty for now, the main thing is to connect it, we’ll deal with the design later, when we install the template on Joomla. This will make it easier to observe the result.

< link rel= "stylesheet" href= "< ?php echo $this-> baseurl ?> /templates/< ?php echo $this-> template ?> /css/template.css" type="text /css" / >

The following code snippet allows us to collapse the left or right columns if there are no modules located at the left and right positions. If both columns are collapsed, the content takes up 100% of the page width. If only one column is included, then the content takes up 80%. With two columns enabled, content accounts for 60% of the page width.

< ?php
if ($ this-> countModules("left and right" ) = = 0) $contentwidth = "100" ;
if ($ this-> countModules("left or right" ) = = 1) $contentwidth = "80" ;
if ($ this-> countModules("left and right" ) = = 1) $contentwidth = "60" ;
?>

Header closes

< / head>

< body>

The “page” block contains the design of only the site page, which will be 950px wide.

< div id= "page" >

The "top" block is located at the very top of the page and contains two blocks "logo" and "user1".

< div id= "top" >

In the “logo” bokeh we will place a graphic file of the logo; this will be specified in the style sheets. But we write the automatic display of the site name in the index.php file, and place the name in the H1 tag, which is very important for search engine optimization.

< div id= "logo" >
< h1> < ?php echo $app - >getCfg("sitename" ) ; ?>< / h1>
< / div>

Let's define the position “user1” in the block of the same name to display the site search module.

< div id= "user1" >
< jdoc:include type= "modules" name= "user1" style= "xhtml" / >
< / div>
< / div> < ! - - конец блока top - - >

Output of the horizontal menu module in the “user2” block in the “user2” position. The block will collapse if there is no module at that position.

< ?php if ($this-> countModules("user2" ) ) : ?>
< div id= "user2 " >
< jdoc:include type= "modules" name= "user2" style= "xhtml" / >
< / div>
< ?php endif ; ?>

Next comes the site header block. In it we will define the “header” position for displaying modules. The block will collapse if there is no module at that position. I intentionally expanded the capabilities of this block to be able to place in it not only the header image, but also image rotators.

< ?php if ($this-> countModules(" header") ) : ?>
< div id= "header">
< jdoc:include type= "modules" name= "header" style="xhtml" / >
< / div>
< ?php endif ; ?>

In the “user3” block we define the position “user3” for outputting modules.

The block will collapse if there is no module output at this position "user3".

< ?php if ($this-> countModules("user3" ) ) : ?>
< div id= "user3" >
< jdoc:include type= "modules" name= "user3" style= "xhtml" / >
< / div>
< ?php endif ; ?>

A block of the left column opens, which will collapse if there are no modules in the “left” position.

< ?php if ($this-> countModules("left" ) ) : ?>
< div id= "left" >
< jdoc:include type= "modules" name= "left" style= "xhtml" / >
< / div>
< ?php endif ; ?>

The most important content block opens, which can occupy 100% of the page width, 80% and 60%, depending on the number of columns included.

< div id= "content< ?php echo $contentwidth ; ?> " >

Displaying messages in components

< jdoc:include type= "message" / >

Output content content.

< jdoc:include type= "component" style= "xhtml" / >
< / div> < ! - - конец блока контента- - >

A block of the right column opens, which will collapse if there are no modules in the “right” position.

< ?php if ($this-> countModules("right" ) ) : ?>
< div id= "rigth" >
< jdoc:include type= "modules" name= "right" style= "xhtml" / >
< / div>
< ?php endif ; ?>

Output of the “footer” block, designed to display the “HTML code” module with copyright information. You can also place a bottom horizontal menu or content presentation module here. The block will be collapsed if more than one module is displayed in this “footer” position

< ?php if ($this-> countModules("footer") ) : ?>
< div id= "footer" >
< jdoc:include type= "modules" name= "footer" style= "xhtml" / >
< / div>
< ?php endif ; ?>

The site page block “page”, body and all code are closed.

< / div> < ! - - конец блока page- - >
< / body> < ! - - конец блока body - - >
< / html> < ! - - конец кода- - >

We have created a complete index.php file. Now you know which commands are used and in what sequence the template blocks are displayed.

ATTENTION: In order for the template code to be read from the joomla admin panel, the index.php file must be opened in the AkelPad editor and saved in UTF-8 encoding, while unchecking the BOM checkbox. If you used the Macromedia Dreamweaver program to work with the file, then you need to select “Edit”> “Page Properties” in the top menu and select the document encoding Unicode (utf-8), and uncheck “enable Unicode signatures (BOM)”. However, I strongly advise you not to edit the code from the Joomla admin panel, if you mess something up - there is no turning back, unlike the Macromedia Dreamweaver program, where you can always undo the changes made.

The design of the blocks itself will be described in template.css. But we will configure style sheets after installing the template on Joomla 3 (joomla 2.5), and for this we need to create

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 in 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!

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.

From previous lessons we learned that using the GET method we can pass some parameters directly to the URL. However, there is nothing stopping us from doing this without forms, just listing them in the URL.

We can pass parameters via URL. And we can get these parameters directly in the script. So what's stopping us from showing different pages to the user depending on the parameters in the URL?

Creating a dynamic page

To show different pages to the user, you need to prepare content. Let it lie in a multidimensional array:

"Creating dynamic pages", "content" => "Text of the article about dynamic pages." ], [ "title" => "How to catch a kitten", "content" => "Text of the article about kittens." ] ]; ?>

The dynamic parameter in the URL will be called id, and we will catch it in $_GET["id"] . We could add an id field to each element of the array, but then we would have to iterate through all the elements and look for the subarray with the desired id. Therefore, it is much easier to use the keys of the main array as ids.

Simply put, we take the id and try to find an article with that key in the $articles array. It looks like this:

All that remains is to sketch out the menu output and check the id for correctness. It turns out to be a real PHP router!

"Home page", "content" => "Text of the article about our site" ], [ "title" => "Creating dynamic pages", "content" => "Text of the article about dynamic pages." ], [ "title" => "How to catch a kitten", "content" => "Text of the article about kittens." ] ]; # If the id is passed, write the article to $article or null if there is no article with that id if(isset($_GET["id"])) $current_article = $articles[$_GET["id"]] ?? null; # If id is not passed, then this is the main page, we can show the page with id = 0 else $current_article = $articles; ?> $article): ?> ">

Error 404: Page not found

Now you can create dynamic sites where the number of pages depends on the number of array elements, rather than PHP files. :) If the site should have different types of pages, for example, an article and a product, you can pass the page type as the second parameter: site.ru?type=article&id=5 .

Of course, this system is not perfect. After a while you will learn how to make a normal CNC (more convenient URLs, for example site.ru/articles/5/) and store articles in a file or database.

To create a promising, expandable and effective website of any complexity, you should start with something simple. This process is not easy, it requires certain basic knowledge of PHP and MySQL, but if you consider it point by point, you can create a kind of “work plan” that will be useful when creating new sites. Let's prepare the “core” and base for the project. At first it will be a regular business card website, but then, by adding functionality, it can be turned into anything. So let's get started.

1. Preparing the database. 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 on the site, the database itself, tables and table fields are in the same encoding.
We create a table in the new database. Let's call it “pages”. This table will store static pages of the future site and information about them. The table must contain the following fields:

  • page_id - page identifier (SMALLINT, primary key, auto_increment);
  • page_alias - page alias for the CNC address line (VARCHAR, 255);
  • page_title - title of the page in the browser window (VARCHAR, 255);
  • page_meta_d - meta description of the page for the meta description tag (VARCHAR, 255);
  • page_meta_k - meta keywords for the meta keywords tag (VARCHAR, 255);
  • page_h1 - page title (VARCHAR, 255);
  • page_s_desc - a brief description of the 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 “Y”).

Immediately after creating the table, we insert into it the values ​​for the main page of the site. I suggest inserting the value “home” into the “page_alias” field for the main page. Meta tags correspond to the theme of the entire site. In the same way, you can create other pages, for example, “About the company” with the alias “about” and your own meta tags, or “Contacts” with the alias “contacts”, 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, and 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 LOGIN TO THE DATABASE
var $dbpass = ""; // YOUR PASSWORD TO THE DATABASE
var $db = "mysite"; // NAME OF THE DATABASE 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);
}
function 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 currently contains only a simple database connection class, but in the future you can add various useful functions to it that will be accessible from anywhere in the site code. Don't forget to change the login and password for your database.

If you are working in a Windows environment, I can recommend using the . This editor has line numbering and easily converts text from one encoding to another. ATTENTION! If you work in UTF-8 encoding, convert files to UTF-8 without BOM - this will help avoid problems in the future.

3. Create index.php - the main site controller

The configuration file has been created. Now in the root folder of the site we create index.php - this will be the main script of the site, a kind of “main controller”. Contents of the index.php file:

define("INDEX", ""); // SETTING THE MAIN CONTROLLER CONSTANT

Require_once($_SERVER."/cfg/core.php"); // CONNECTING THE KERNEL

// 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 when requested. Currently, 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 appearance of the site’s main page differs from regular menu item pages). The logic of the main controller is as follows: the name of the required component is extracted from the URL string (the value of the $option variable), and 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, extracts data from the database and writes it into variables for transfer 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 regular page output component

In the root of the site, create a “com” folder - component files will be stored in it. A site component, in my understanding, is a file in which data is processed for different sections of the site. For example, a regular page component retrieves the title, description and text of the material from the database and writes them into 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 are displayed to the user as an HTML page. For example, a catalog component that could be created in the future would do almost the same thing, but with data about products - and it has its own specifics, other fields in the table, etc. Therefore, for each functional section of the site it is worth creating a separate component. In the MVC (Model-View-Controller) scheme, the component acts as 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 main page output component

The main page in our database is stored under the pseudonym “home”, and so far its structure does not differ from regular site pages - it’s just an article. Nevertheless, we will create a separate component for it - for the future, so to speak.


The contents of the “home.php” component in the “com” folder are almost identical to the contents of the regular page component, with the exception of the database query string and the component name. 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

In the root of the site we create a template.php file. In essence, this is a regular web design layout in HTML+CSS format, only with PHP variables in the right places. Insert between title tags, in the central column of the site there is an insertand 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 at your discretion.

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 I consider parsing the address bar using the controller itself to be unnecessary functionality. The contents of .htaccess at this stage are:


RewriteEngine On
RewriteBase /

RewriteCond %(REQUEST_FILENAME) !-d
RewriteCond %(REQUEST_FILENAME) !-f

# PROHIBITED FILES
RewriteRule .htaccess - [F]
RewriteRule template.php - [F]

# RULES mod_rewrite
RewriteRule page/(+)([\/](0,1))\.htm$ index.php?option=page&alias=$1 [L]

In the future, we will add rules for the search components, catalog, article blog, etc. There is only one point: convert links like “mysite.com/index.php?option=pages&alias=about” into a link like “mysite.com/pages/about.htm” - it looks pretty nice. Try to avoid the $_GET array in development for safety reasons and do not rely on it. It is advisable to store in it only the parameters for the main controller (the $option variable) and for the component (the $alias variable).

Also, in each site folder, “just in case,” create an empty index.html file - this is necessary so that when accessing the directory through the address bar, nothing is displayed.

Tags: php, mysql, site engine, controller, site creation, mvc

2017-01-10


Create a dynamic website using php

Hello dear visitor!

Today, from the main page, using the PHP programming language, we will create a 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 in the future will greatly simplify its technical support and development compared to the static version.

  • 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 of the step-by-step instructions in 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.