Inclusion constructs in PHP. require and require_once statements in PHP Require examples

As you know, PHP has 4 functions for including other files. it include, include_once, require and require_once. How do they differ and how to use them correctly?

First, let's look at the difference between include and require. These two functions differ only in their response to the absence of an include file. Function include("enable") if the specified file is missing, it will give an error message like E_WARNING, but the program will continue. Unlike her, require("require") in the absence of an included file gives a fatal error (E_ERROR), which leads to an immediate stop of the script being executed.

So, based on your knowledge of how your code is executed, you can use one or the other operator. For example, if this is just a piece of HTML that generally does not affect the course of the program, or these are some minor plug-ins without which the rest of the program can function normally, then feel free to use include. Otherwise, I recommend using require. This will prevent the possibility of incorrect code execution and in case of an error (for example, the included file was deleted by a virus or was lost during development), it will simply end the script. In one of the future articles, I will show you how to track absolutely all non-standard situations in the code and be aware of what is happening inside the site.

Now consider the structures include_once and require_once. From simple include and require they differ in the "_once" ending, which prevents the same files from being re-included.

For example, if your include file contains descriptions of classes or functions, then such a file cannot be re-included, because it will be re-executed and PHP will give a fatal error when trying to define classes or functions with already existing names. There is no doubt that it is possible to build the code in such a way that a reconnection never occurs, but these are unnecessary restrictions and extra work. Therefore, functions with the "_once" suffix are useful and necessary.

In my practice, I use two types of files. The first type is files containing one or more classes and not containing code that is executed "directly". I always connect such files with require_once. The second type is templates or template pieces containing HTML and some PHP code. I include these files with require, since sometimes the same piece of template can be used several times on a page.

I never use include and include_once, because I consider the absence of a file that should be a critical situation that requires an immediate solution without any compromise. And if I need to include a file, the existence of which is in doubt, then I simply check its presence with is_file () beforehand.

There is one more trick when using include. Despite the fact that in fact this is not a function, but a language construct, the operator works inside the included file return. And, therefore, include returns this value to the called code. It looks like this

$ret = include 'file.php';

That's all for today, program correctly!

If functions are placed in separate file, then two require and include statements allow you to connect it. Operators have the following format:
require(<Имя файла>);
require<Имя файла>;
include(<Имя файла>);
include<Имя файла>;
Let's move the f_Sum() function to a separate file ( listing 17) and include it with the require statement ( Listing 16).

Listing 16. Using the require statement

Listing 17. The contents of the script.inc file

You can create a script.inc file, for example, using Notepad++. Note that an include file can have any extension, although it is common to give include files the extension inc (for "include").
Let's try to open the script.inc file with a Web browser. As a result, the web browser window will display source:

For this reason, it is necessary to place the include files in a directory that is accessible only to the script but not accessible from the Internet. When installing and configuring PHP, we specified the location of the include files in the include_path directive of the php.ini file:

include_path = ".;C:\php5\includes"

Here, separated by a semicolon, there are two places to look for include files:
□ . (dot) - in the same folder as executable file;
C:\php5\includes - in the includes folder (c:\php5\includes).
In other words, if it doesn't find an include file in the same folder as the executable file, the interpreter will look in the includes folder (c:\php5\includes).
You can also save an include file with a php extension. In this case, the source code will not be displayed in the Web browser window.

If the included file contains executable code, then PHP descriptors must be specified. Otherwise, the PHP code will be output as plain text, and when calling the functions defined in it, an error message will be displayed:
function f_Sum($x, $y=2) ( return ($x + $y); )
Fatal error: Call to undefined function f_Sum() in
C:\Apache2\htdocs\index.php on line 9
In other words, the included file may or may not contain PHP code. For example, let's move the header and the f_Sum() function to the header.inc file ( listing 19), and the footer to footer.inc ( listing 20). Then we connect these files to the main script ( Listing 18).

Listing 18. Placing HTML code in an include file

Listing 19. Contents of header.inc file

Functions

Listing 20. The contents of the footer.inc file

AT Listing 21 the source HTML code after the execution of the previous program is given.

Listing 21. Source HTML

Functions 7

This way you can generate templates for multiple pages. The interpreter, upon encountering a require statement, will make the contents of the included file part of the page. If the file cannot be loaded, then the statement generates fatal error and the script stops running.
You can use the include statement instead of the require statement. If the include file is not found, the operator will display an error message, but the script will continue to run. If this file contains functions, then each function call from this file will also generate an error.

The include statement returns true if the file is loaded and false on error. You can suppress the error message with the @ operator ( listing 22).

Listing 22. Error message suppression

To make the code more readable, you can, for example, place function and/or class definitions in a separate file. The ability to include files in PHP is provided by four language instructions:

  • include
  • require
  • include_once
  • require_once

All four instructions can take a local file name as a parameter. The include and require statements are very similar in action and differ only in their response to the impossibility of obtaining the requested resource. For example, if a resource is not available, include and include_once issue a warning and try to continue executing the program. require and require_once stop processing the given page if the requested resource is not available.

include

The include statement allows you to include and attach other scripts to your PHP script. When you run the program, the interpreter will simply replace the instruction with the contents of the included file. Let's see how it works, create a file called add.php and write inside:

Now let's create another file and name it test.php for example, in which we include the add.php file:

\$var2 = $var2" ?>

As you can see from the example, the include statement attaches the contents of the included file, thanks to which your program gets access to other variables, functions, classes, etc.

Note: you can give your include files any name, but always add the .php extension, because if you use a different extension, attackers can request your file, and the web server will return its text. This is a security risk because passwords or how your program works can be exposed, giving attackers a backdoor. To prevent this from happening, include files must be processed by the PHP interpreter.

Connecting inside a function

If a file is included inside a function, then all the code contained in the included file will behave as if it were defined inside that function, i.e. the code will have local scope. Let's rewrite the previous example a bit:

Now let's add a function to test.php:

In global scope: $var1"; ?>

Since we declared the $var1 global variable inside the function, it also becomes available in the global scope.

The path to the file

Files are included based on the specified path to the file, if the path is not specified, the path specified in the include_path directive will be used (in configuration file php.ini). If the file is not found at the specified include_path , the include statement will attempt to check the current working directory where the include file script resides, if include construct cannot find the file, a warning will be issued.

If a path is specified - no matter if it is absolute or relative (relative to the current directory where the include script is located) - the include_path directive will be ignored.

include_once

The include_once behavior is identical to the include statement, with the only difference being that if the code from the file has already been included once, it will not be included and will be re-executed. This helps avoid the problem of redefining functions, variables, etc. To better understand how this works, here is an example:

In test.php we will try to execute following code:

This will result in an error message, because functions cannot be overridden. To avoid this kind of error, you should use the include_once statement. Let's rewrite the code in the test.php file:

require and require_once

The require and require_once statements work identically to include and include_once except for one difference. If the include file is not found, script execution will stop while include and include_once issue a warning and continue script execution.

Tip : try not to use include and require at all, use their counterparts with the _once suffix. This will make it easier to break down a large and complex program into relatively independent modules.

Page layouts

13.22. require() statement

The require() operator works in a similar way to the #include() preprocessor directive in the C++ programming language. If you are familiar with this language, then it will not be difficult for you to master the following operators, however, even if you are not familiar, we will try to describe in more detail how these operators work. The require() statement replaces, calls the contents of the files whose path and name were specified in the statement block:

require("path/filename.html");

If the fopen_wrapper_SB PHP URL parameters are set to enabled (usually they are default), then you can also specify the file in a require() statement using a URL (Uniform Resource Locator) instead of use the local path to the required file in the require() statement, for example:

$url = http://my_new_adress/index.phtml;

The require() statement is not a function. Most likely it can be called a language construct. Why can't we consider this statement as a function:

Require() is not subordinate to any control structures;

Require() does not return any value, which the function does in turn.

Attempting to call any value from the require() statement will result in an error and abort further program execution.

Unlike include, require always reads the file's address line, even if it's not being executed. If you need to conditionally include a file, use the include() statement. It's just that conditional expressions are not considered effective when working with the require statement. However, if the line on which the requre statement is located is not executed, then not a single line of code in the file at this address will be executed. This is logical, since it is the access to the file in this case that is carried out through the require () operator.

The loop execution structures do not affect the behavior of the require() statement, although the code contained in the final file is still subject to the loop. From this we can conclude that the require statement is executed only once, unlike include ().

Therefore/you cannot place a require() statement with all of its accompanying instructions in a loop statement block and expect the same loop to execute the given statement differently on each iteration. To take advantage of this, we suggest you use the include() statement.

When a file is run with a require() statement, the contained cbd inherits the capability variables of the line on which requre() is executed. Any variables available on this line will be available within the called file. If a require statement is inside a function within calling file, then all the code contained in the called file will behave as if it were defined inside this

In the event that the require() operator is working on a file that is called via HTTP and uses fopen wrappers, and if the station address interprets the final file as PHP code, then variables can be passed to the require() operator using the URL -request as HTTP Get method. It's not the same. that the file call of the require statement since the script practically continues the execution of the script on remote server and the results will then be included in the local script:

/* will not work because it was not processed by the server */

require("http://my_domain_name/file.txt?varone=1&vartwo=2");

/* don't work because the filename is "file.php?varone=1&vartwo=2"

focused on local file system */

require("file.php?varone=1&vartwo=2");

/* will work without errors */

require("http://my_domain_name/test.php?varone=1Svartwo=2");

require("file.txt");

require("file.php");

These examples will help you visually understand how to use the require() operator, as well as avoid mistakes when creating programs. Next, we will look at the include() statement, similar to the require() statement, and the basic principles of how it works.

operator . Activation can be done in any of the following ways:

include "filename"; include $file_name; include("filename");

Example 3.9. Let us store a set of some parameters and functions in the params.inc file. Every time we need to use these parameters (functions), we will insert the include ("params.inc") command into the text of our main program.

params.incinclude.php"; // displays "Hi, Vasya!" echo "Today is $today"; // displays, for example, "Today is 07.07.05" ?> Example 3.9. Using the include statement

Note that using the operator include is equivalent to simply pasting the content of the params.inc file into the include.php program code. Maybe then it was possible to write a simple text in params.inc without any tags indicating that this is a php code? It is forbidden! The fact is that at the moment of inserting a file, a switch occurs from the mode PHP processing to HTML mode. Therefore, code within an include file that is to be processed as a PHP script must be enclosed in the appropriate tags.

The search for a file to insert occurs according to the following rules.

  1. First, the file is searched in include_path relative to the current working directory.
  2. If the file is not found, then the search is performed in include_path relative to the directory of the current script.
  3. Parameter include_path, defined in the PHP settings file, specifies the names of the directories in which to search include files.

For example, your include_path this is . (that is current directory), the current working directory is /www/ . In the main include.php file, you include the my_dir/a.php file, which in turn includes b.php . Then the parser first looks for the b.php file in the /www/ directory, and if there is none, then in the /www/my_dir/ directory.

If the file is included with include, then the code it contains inherits the scope string variables where it appeared include. Any variables in the called file will be available in the calling file from this line onwards. Accordingly, if include appears inside a function of the calling file, then the code contained in the called file will behave as if it were defined inside the function. So it will inherit the scope of that function. Although we have not yet become acquainted with the concept of a function, we nevertheless present this information here, counting on its intuitive understanding.

Example 3.10. Let the file to insert params.inc remain the same, and include.php be the following:

"; $str .= "The page was created by $user"; echo "$str"; ) Footer(); // call the Footer() function. We get: //Today: 08.07.05 //The page was created by Vasya echo "$user , $today"; // prints out a comma because // these variables are only visible // inside the function?> Example 3.10. Scope when using include

In addition to local files, with include you can also include external files by specifying their url-addresses. This feature is controlled by the url_fopen_wrappers directive in the PHP settings file and is usually enabled by default. But versions of PHP for Windows prior to PHP 4.3.0 do not support this feature at all, regardless of url_fopen_wrappers .

include() is a special language construct and must be enclosed in curly braces when used inside conditional blocks.

Example 3.11. Using include()

Using include Two types of errors are possible - an insert error (for example, the specified file cannot be found, the insert command itself is written incorrectly, etc.) or an execution error (if the error is contained in the inserted file). In any case, if there is an error in the command

A computer