Computer lessons

Php require once description. PHP functions: require(), require_once(), include(), include_once()

Page Layouts

13.22. require() operator

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

require("path/filename.html");

If the fopen_wrapper_SB PHP URL parameters are set to enabled (they are typically default), then you can also define the file in the 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 operator a function:

Require() is not subordinate to any control structures;

Require() does not return any value, which is what a function does.

An attempt to call any value from a require() statement will result in an error and interrupt further program execution.

Unlike include, require always reads the file's address line, even when it is not being executed. If you need to conditionally include a file, use the include() statement. Simply 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 that address will be executed. This is logical, since the file is accessed in this case through the require() operator.

Loop execution structures do not affect the behavior of the require() statement, although the code contained in the resulting 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 the require() statement with all the instructions attached to it in a loop statement block and expect different executions of this statement at each iteration while the loop is running. To take advantage of this, we suggest you use the include() operator.

When a file is run with a require() statement, the contained cbd inherits the variable capabilities 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 a calling file, then all code contained in the called file will behave as if it were defined within that

If the require() statement is working on a file that is called over HTTP and uses fopen wrappers, and if the station address interprets the resulting file as PHP code, then variables can be passed to the require() statement using the URL -request, like the HTTP Get method. It's not the same. that calling the require statement file since the script practically continues the execution of the script on the 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");

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

targets 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 clearly understand how to use the require() operator, as well as avoid making mistakes when creating programs. Next, we'll look at the include() statement, which is similar to the require() statement, and how it works.

One of the most fun and useful features of PHP is including another file. For example, a website has a top menu, a bottom menu, and between them the page content itself. And, for example, on 10 pages of the site the bottom menu is used. At some point, changes needed to be made to it. In html you would manually make changes in each individual file, but php allows you to significantly simplify working with the site! The code for the bottom menu can be contained in a separate file, and on each of the 10 pages you can simply include this separate file! That is, all changes now need to be made only to the file with the menu, and on 10 others it will be displayed with changes.

The meaning of connection in php in simple Russian language:

File 1.php
Top Menu

File 2.php
Lower menu

Example.php file
Connect File 1.php
Page content
Connect File 2.php

As a result of processing the example.php file, it will be displayed
Top Menu
Page content
Lower menu
Accordingly, in order to change anything in the bottom menu, you need to make changes only in the 2.php file

The path to the file

The file is connected according to the path specified for the file. There are two path options: relative and absolute. Relative - this is an indication of the path to the connected file relative to the file with the connection instructions. Absolute - specifying the full path to the included file.

PHP code

// example of a relative path
include "include/your_file.php"; // the file is in the include folder, which is located in the same directory as the connection file

// example of an absolute path
include $_SERVER["DOCUMENT_ROOT"]."/include/your_file.php"; // $_SERVER["DOCUMENT_ROOT"] - indicates the root directory of the site

include and include_once

include()- a construct designed to include files in PHP script code during execution of the PHP script. When processing the code, the instruction is replaced with the contents of the attached file. I suggest looking at an example right away.

Let's look at how include works using two files as an example: index.php And text.php. For simplicity of work, let's assume that they are located in the same directory.

PHP code(file index.php)

Echo "Plain text contained in the main file";
include "text.php"; // include the contents of the text.php file

?>
PHP code(file text.php)

Echo "Text contained in the included file";

?>
The result of running the index.php file will be:

Plain text contained in the main file
Text contained in the included file
Is it really convenient? Now, by changing the contents in the text.php file, the result of index.php will be completely different!

Now let's talk about another design - include_once. It works exactly the same as include, only created later and for those cases when the file cannot be re-included. For example, you are afraid that as a result of an error you may connect a file 2 or more times, which will affect the page not working correctly and receiving a corresponding error message.

PHP code

Include_once "text.php"; // the text.php file will be included only once

// reconnections below will not be taken into account and displayed
// and it will not cause an error message to be displayed
include_once "text.php"; // nothing will happen

require and require_once

The require and require_once instructions work identically to include and include_once with the exception of only one feature - if the included file is not found, script execution will be stopped (the script will no longer be read), while include and include_once simply display a warning and continue further execution of the script.

If include or require doesn't work

To understand the reasons why include does not work, I suggest checking everything step by step. No matter how clear and superficial the points below may be, check everything from the very beginning

1. Check if your server and php are working, and if any php code on the site is working at all
2. Check if the include file exists
3. Check if the file name and extension are entered correctly in the connection
4. Make sure that the included php file is actually located at the address you specified
5. Try specifying an absolute path (the full path to the file) rather than a relative path.

Example PHP code

Include "http://www.example.com/include/your_file.php";

// DOCUMENT_ROOT - denotes the root directory of the resource
include $_SERVER["DOCUMENT_ROOT"]."/include/your_file.php";

6. If your file does not connect and no error is displayed, then in the directory with the file you are connecting, create a file .htaccess with the following content

Php_flag display_errors On
or in php file, before connecting, paste the following line

Error_reporting(E_ALL);
Both settings will force errors to be displayed

PHP Operators: require(), require_once(), include_once()

Date: 2012-10-15

PHP functions: require(), require_once(), include(), include_once()

In the last lesson we discussed the work in detail. Let me remind you that the operator include() in PHP, substitutes the content of one web page into another web page. But PHP has other functions that allow you to implement a similar task. In particular these are the functions:

include_once()
require()
require_once()

To insert the content of a specific web page, it is enough to specify the path to the desired file as an argument (in parentheses) to these functions. For example, like this:

include("file.php") or require("file.php")

The task of all these functions is the same: insert the desired code or text from one file into another file. But, nevertheless, these functions differ from each other. Let's figure it out.

Suffix " _once" allows you to connect the code of a file for substitution into another file only once, no matter how many calls are made. For clarity, let's look at a simple example. In the last lesson, we figured out that using the operator include(), you can put the site header in a separate file header.php, for simplicity, we will assume that we are placing the graphic logo of the site in this file. In the right place on the web page (in this case, in the place of the site header) we write the code Listing 1.

Listing 1.

Then, accordingly, the site logo will also be displayed twice, approximately like this:

Agree, it doesn’t look very nice, right? It turns out that the operator include() pulls it out of the folder twice blocks file header.php and substitutes it twice in place of the site header.

In general, the included file may contain functions that, when added to the source file, may generate errors and your web page may not load at all.

On large sites it is very easy to get confused about where and what file you included and whether you can include it again, and this can lead to an error. That's why they came up with the prefix " _once" to functions include And require, which embeds the contents of a file into another web page only once.

How does include() differ from require()

Now let's talk about the function include() different from function require(). There are no differences between them in their work. Both functions incorporate the contents of one file into another. But they have a difference and it lies in the way they react to a situation when the file we are connecting is not in place.

Let's go back to the previous example code Listing 1. We have the following code:

Include("blocks/header.php");

Let's try to delete the file header.php, which we actually connect, for example, the file is damaged or was accidentally deleted from the north.

We update the test file and see this error:

As you can see, a message appears stating that in the directory (folder) blocks file not found header.php, but the program is still executed and the rest of the site’s web page is displayed normally.

What if we write code ( Listing 3) using the function require():

Listing 3.

Require("blocks/header.php");

That's what we have only one error message will be displayed, and the program will no longer be executed, and you will only see this message.

As you know, PHP has 4 functions for including other files. This 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 reaction to the absence of an included file. Function include(“enable”), if the specified file is missing, will generate an error message like E_WARNING, but program execution will continue. Unlike her, require(“require”), if there is no included file, generates a fatal error (E_ERROR), which leads to the immediate stop of the running script.

Thus, based on your knowledge of how your code is executed, you can use one or another operator. For example, if this is just a piece of HTML that generally does not affect the flow 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. In other cases, 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 the development process) the script will simply end. 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 let's look at the structures include_once And require_once. From simple include And require they are distinguished by the ending "_once", which prevents the same files from being included again.

For example, if your included file contains descriptions of classes or functions, then such a file cannot be included again, since it will be executed again and PHP will throw a fatal error when trying to define classes or functions with already existing names. There is no doubt that it is possible to design the code in such a way that reconnection never occurs, but this is unnecessary restrictions and unnecessary work. Therefore, functions with the suffix “_once” are useful and necessary.

In my practice, I use two types of files. The first type are files that contain one or more classes and do not contain code that is executed “directly”. I always connect such files using require_once. The second type is templates or pieces of templates containing HTML and some PHP code. I connect such files using require, because 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 compromises. And if I need to include a file whose presence is in doubt, then I simply first check its presence using is_file().

There is one more trick when using include. Despite the fact that this is not actually a function, but a language construct, the operator inside the included file works 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!

The construct of require inclusions

Design require allows you to include files in a PHP script to run a PHP script. General syntax require such:

require filename;

When starting (precisely at startup, not during execution!) of the program, the interpreter will simply replace the instruction with the contents of the file file_name (this file may also contain a PHP script, framed, as usual, with tags And ?> ). Moreover, it will do this immediately before starting the program (unlike include, which is discussed below). This can be quite convenient for including various template pages with HTML code in the script output. Here's an example:

Header.html file:

It is a title

Footer.html file:
Home Company, 2005.

Script.php file
require "header.htm";
// The script displays the body of the document itself
require "footer.htm";
?>

So the design require allows you to assemble PHP scripts from several separate files, which can be like html-pages and php-scripts.

Design require supports inclusion of remote files (since PHP 4.3.0). For example:

// The following example doesn't work because it tries to include a local file
require "file.php?foo=1&bar=2" ;
// The following example works
require ;
?>

! Design require allows you to include remote files if this feature is enabled in the PHP configuration file.

Including remote files

PHP allows you to work with URL objects like regular files. Packers, available by default, are used to work with remote files using the ftp or http protocol.

If "fopen wrapper URLs" are included in PHP (as in the default configuration), you can specify a file to be included using a URL (via HTTP) instead of a local path. If the target server interprets the target file as PHP code, variables can be passed to the include file using a URL query string, as in HTTP GET. Strictly speaking, this is not the same as including a file and having it inherit the scope of the parent file's variables; after all, the script runs on a remote server, and the result is then included in the local script.

In order for remote inclusion of files to be available, you need to set in the configuration file (php.ini) allow_url_fopen=1.

note: PHP versions for Windows prior to PHP 4.3.0 do not support the ability to use remote files by this feature, even if the allow_url_fopen option is enabled.


/* This assumes that www.example.com is configured to parse.php
* files, not .txt files. Also "Works" here means that the variables
* $foo and $bar are available in the included file. */

//Won't work because file.txt is not processed by www.example.com like PHP
require "http://www.example.com/file.txt?foo=1&bar=2";

// Will not work because it is looking for the file "file.php?foo=1&bar=2" in the local
// file system.
require "file.php?foo=1&bar=2" ;

// The following example works:
require "http://www.example.com/file.php?foo=1&bar=2";

$foo = 1 ;
$bar = 2;
require "file.txt" ; // Works
require "file.php" ; // Works

?>