Posts

PHP Quick Start

Listings of this chapter can be found in the start subdirectory.

Despite the fact that PHP is a universal programming language and can be used to develop almost any software, its main specialization is Web development. The current chapter will show the most typical techniques for working with PHP. Some structures (if, include) will be illuminated superficially. In subsequent chapters, we will focus on them in more detail.

Scripts

The PHP programming language is considered a scripting language, so programs written in it are called scripts. The main difference between traditional programs and scripts is that the scripts work only in a specific environment and use the resources of this environment.

For example, the scripting JavaScript programming language works primarily in Web browsers, Visual Basic for Applications only in the Microsoft Office environment. Using these programming languages, it is impossible to create a program that works without an appropriate environment.

In the case of PHP, the Web environment (Web server, database server, mail server, etc.) acts as such an environment. It is PHP that receives requests from the client, ensures their parallel execution and sending data. The PHP script receives all the information about the request and executes the request, and then sends the data back to the server.

Comment! However, the PHP programming language allows the creation of programs that operate independently of the Web server, but in this form it has not received any widespread use.

One of the main features of the PHP programming language is the fact that its code can be interspersed with the HTML code. In order for the PHP interpreter to distinguish between HTML and PHP codes, the latter consists of special tags, between which are constructions and operators of the PHP programming language.

Listing 3.1 provides a classic example that displays the phrase “Hello, world” to the browser window using the echo construct. The contents of Listing 3.1 should be placed in a file with the .php extension, for example, in the index.php file.

Listing 3.1. The simplest PHP screen. Lndex.php file

<!DOCTYPE html>
<html lang="en">
<head>
<title>The simplest PHP script</title>
<meta charset='utf-8'>
</head>
<body>
<?php
echo "Hello, world!";
?>
</body>
</html>

The echo construct prints one or more lines to standard output. As a result of the script, the phrase “Hello, world!” Will be displayed in the browser window. When working with server-side programming languages, such as PHP, it should be remembered that the scripts located between the tags are executed on the server.

The client receives only the result of the PHP code, which can be easily seen by viewing the source code of the HTML page.

<!DOCTYPE html>
<html lang="en">
<head>
<title>The simplest PHP script</title>
<meta charset='utf-8'>
</head>
<bоdу>
Hello, world!
</body>
</html>

Start and End Tags

As mentioned in the previous section, the PHP script must be placed between the start tag in order for the interpreter to share the HTML and PHP codes. Even if the HTML code is not used, the indication of PHP tags is mandatory, otherwise the PHP code will be displayed in the browser window as is, without interpretation. In addition to tags, PHP supports a special type of tags for outputting the result of a single PHP statement. For example, the script in Listing 3.1 could be rewritten as shown in Listing 3.2.

Listing 3.2. Alternative tags. File shortags.php

<!DOCTYPE html>
<html lang="en">
<head>
<title>Alternative tags</title>
<meta charset='utf-8'>
</head>
<body>
<?= "Hello, world!"; ?>
</body>
</html>

As can be seen from the example above, to output the string "Hello, world!" the echo construction is not required, the <?= tag automatically outputs the result to the standard stream.

It should be noted that an HTML page may contain more than one php-insert. Listing 3.3 shows an example that contains two inserts: one sets the name of the page (in the HTML <title> tag), and the second defines the content of the page (in the HTML-tag <body>).

Listing 3.3. Multiple PHP inserts are allowed in the HTML code. Few.php file

<html>
<head>
<title><?php echo "Display current date" ?></title>
</head>
<body>
<?php
echo "Current date:<Ьr />";
echo date(DATE_RSS);
?>
</body>
</html>

If there is no output after the final tag ?>, you can omit it (Listing 3.4).

Listing 3.4. The final tag ?> Can be omitted. Missing.php file

<?php
echo "Hello world!";

Moreover, the PSR-2 coding standard, which defines the formatting of the PHP code for the distributed components, requires that you do not specify the final tag ?> in all cases where this is possible.

Upon encountering a character, for example, a space, the PHP interpreter believes that the HTTP output of the document begins and the formation of the HTTP preceding header is completed. Therefore, later attempts to send the HTTP headers will fail. If the trailing tag is not used, such errors are excluded as a class.

PSR standards define the rules for developing PHP components, their purpose is to unify the frameworks and components distributed through the Composer Manager (see Chapter 26) so that the components of one framework can be used in another.

At the time of this writing, 8 standards were adopted and 9 were in preparation. You can follow the adoption of standards at http://www.php-fig.org/psr/. The PSR-1 and PSR-2 standards define the formatting and style of the PHP code. We will adhere to these standards and report formatting rules as you learn a language.

Use a semicolon

The set of programming language constructions ending with a semicolon will be called an expression.

As you can see from Listing 3.3, the semicolon is not indicated after the line “Displaying the current date”. The expression is one, and there is no need to separate it from other expressions. However, as can be seen in the second inset, there is a semicolon at the end of each echo construct. If you forget to specify this delimiter, the PHP programming language interpreter will consider the expression on a new line a continuation of the previous one and will not be able to correctly parse the script.

As a result, the error message will be generated:

"Parse error: syntax error, unexpected 'echo' (T _ ECHO), expecting ',' or ';"

The last expression before the final tag ?> Can be omitted from the semicolon. For example, in Listing 3.3, after the echo date(DATE_RSS) expression, the semicolon can be omitted. However, it is strongly recommended not to use this feature and to put semicolons after each expression, since the addition of new operators may lead to the appearance of intractable errors.

String translations do not affect the interpretation of the script, the expression can be split into several lines – the PHP interpreter will assume that the expression is completed only after it detects a semicolon or the ending tag ?>. In listings 3.5 and 3.6, there are two scripts that are similar in functionality.

Listing 3.5. Use a semicolon. Semicolumn.php file

<?php
echo 5 + 5;
echo 5 - 2;
echo "Hello, world";

Listing 3.6. Alternative script entry from listing 3.5. File mech.php

<?php
echo 5
+
5; echo 5 -
2; echo "Hello, world!" 
;

Constructions like the one shown in listing 3.6 should be avoided. The more clearly and expectedly the code is written, the easier and faster it is to debug.

Compound expressions. Braces.

Braces allow you to combine several expressions into a group, which is usually called a compound expression (Listing 3.7).

Listing 3.7. Compound expression. Curly.php file

<?php
{
    echo 5 + 5;
    echo 5 - 2;
    echo "Hello, world!";
}

As you can see from the example above, the expressions inside the curly braces are indented. This indent is not required, but it increases the readability of the program. The PSR-2 coding standard requires 4 spaces to indent. If you are used to using the tab character, you should configure your editor to replace the tab character with spaces.

In itself, a compound expression is almost never used; its main purpose is to work together with conditional operators, cycle operators, etc., which we will consider in subsequent chapters.

A compound expression can be located in several PHP inserts. Listing 3.8 shows an example of two compound expressions that are broken up into several PHP inserts. The task of the script is reduced to a random conclusion in the browser window of either the green word “Truth” or the red word “False”. Without the use of curly braces, the if statement would only extend its action to one expression, the use of a compound expression allows its action to be extended to several simple expressions.

COMMENT
The conditional if statement is discussed in Chapter 8.

Listing 3.8. Composite expression in several PHP inserts. Fews.php file

<?php
    if(mt _rand(0, 1)) {
    ?>
    <div style="color: green"><?= "True"; ?></div>
    <?php
} else {
    ?>
    <div style="colo r:red"><?= "False" ?></div>
<?php
}

As you can see in Listing 3.8, a compound expression can be interrupted by tags <?php and ?> at any time and then continued. However, there are exceptions, for example, a compound expression used to form a class cannot be divided by tags <?php and ?>.

Comments

The code of modern programming languages ​​is quite convenient for human perception compared to machine codes, assembler, or the first high-level programming languages. Nevertheless, the constructions of the language are dictated by the architecture of the computer, and, creating programs, the developer, willy-nilly, uses computer logic, not human logic. This often leads to tahe creation of quite complex constructions that need explanation in ordinary language. Comments are used to insert such explanations into the code.

PHP provides several ways to insert comments, variants of which are presented in Table 3.1.

Table 3.1. PHP Comments

Comment Description
// ... C ++ style comment, starting with a double slash // character and ending with a line break
# ... Commentary in the style of UNIX scripting languages, starting with the octothorpe/hash symbol # and ending with a line break
/*
...
*/
If the two previous comments are limited to only one line, then a comment in the style of the C-language /* … */ is multi-line

Listing 3.9 demonstrates the use of all three types of comments from Table 3.1.

Listing 3.9. Comments. File comments.php.

<?php
/*
Demonstration of different types of comments 
in PHP programming language
*/
echo 'Hello'; // this is a comment
echo 'Hello'; # and this is a comment

Naturally, PHP comments act only inside limit tags <?php ... ?>. That is, if the comment characters are outside the delimiter tags, they, like any text, will be displayed by the browser (Listing 3.10).

Listing 3.10. Comments are valid only inside <?php and ?>. File into.php

<?php
echo "Hello<br />"; // РНР comment
?>
// this text will be displayed by the browser
----------------
<!-- This text will not be displayed by the browser 
because it is enclosed between characters that are HTML comments. 
However, it can be viewed in the source code of the HTML page. -->

Comments can be inserted not only after the semicolon, but also in the middle of the expression (Listing 3.11).

Listing 3.11. The comment in the function argument list. File position.php

<?php
echo strstr( // we will look at this function later
"Hello, world", "H");

Enabling the PHP file

Up to this point, we have dealt with only one PHP script. However, PHP scripts can be connected to other PHP scripts using two constructs: include and require. Both take a single argument – the path to the included file, and the result of their action is the substitution of the contents of the file in the place of their call in the source script. If the PHP script is used as the included script, then it is first substituted into the original script, and then the resulting script is interpreted (Listing 3.12).

Listing 3.12. Use include instructions. Include.php file

<?php
echo 'Main script<br />';
include 'included.php';
echo 'Main script<br />';

Let the file included.php contain the code shown in listing 3.13.

Listing 3.13. File included.php

<?php
echo 'Include file<br />';
?>
<h3>The text does not have to be displayed by the echo operator.</h3>

As a result of running the script from Listing 3.12, the following lines will be displayed in the browser:

Main script
Include file
The text does not have to be displayed by the echo operator.
Main script

The difference between include and require lies in their reaction to the absence of an include file. In the case of include, a warning is displayed, all subsequent code continues to be executed; in the case of require, if the file cannot be found, the script stops working.

Tasks

1. Find the date() function in the documentation on http://php.net, which is engaged in date formatting, learn how to work with the function.

2. Find in the documentation the functions for working with date and time time() and mktime(), familiarize yourself with the possibilities that these functions provide. Using calendar functions, output the current date and time in the following format: '10 .07.2018 14:10'.

3. Find in the documentation the function of generating random numbers mt_rand(), familiarize yourself with its capabilities. Create a script that would generate a random number from 0 to 1000.

/ October, 15 at 19:21

I create web projects, develop, optimize and promote websites. If you have any ideas or want to suggest something, then write to me and my team.

Top ↑

Leave a Reply