What is better to use - require or include? Include constructs in PHP include functions require in php.

29 responses

There is also require and include_once .

So your question should be...

  1. When should I use require and include ?
  2. When should I use require_once vs require

The require() function is identical to include(), except that it handles errors differently. If an error occurs, the include() function will generate a warning, but the script will continue executing. Require() throws a fatal error and the script stops.

The require_once() statement is identical to require(), except that PHP will check to see if the file has already been included and, if so, will not include (require) it again.

My suggestion is to just use require_once 99.9% of the time.

Using require or include instead implies that your code cannot be reused elsewhere, i.e. the scripts you are actually typing execute, instead of providing a class or some function libraries,

If you require/including code that runs in-place, this procedural code and you need learn a new paradigm. Similar to object oriented programming, functional programming or functional programming.

If you're already doing OO or functional programming, using include_once will basically linger when you find bugs/errors on the stack. You want to know that the do_cool_stuff() function is not available when you go to call it later, or the moment you expect it to be available, requiring a library? It's usually best to know right away if something you need and expect isn't available, so just use require_once .

Alternatively, in modern OOP, autoload your classes on use.

Difference between _once functions and _once functions: Without code, _once will be included again, whereas with _once functions, PHP keeps track of included files and will only include it once.

Difference between require and include: If the required file is not found, PHP will generate a fatal error, while include will only issue a warning.

include() will issue a warning if it cannot include the file, but the rest of the script will run.

require() will throw E_COMPILE_ERROR and stop the script if it can't include the file.

The include_once() and require_once() functions will not include the file a second time if it has already been included.

See the following documentation pages:

Whenever you use require_once() , you can use on file to include another file if you need the file you just specified in the current file. Here in the example I have test1.php.

and in another file i called test2.php

when you look at m requesting the file test1 twice, but the file will include test1 once and for the second time it will be ignored. And without stopping will display the output once.

Whenever you use "include_once() `, you can use in a file to include another file if you need the file to be called more than once in the current file. Here in the example, I have a file named test3.php.

And in another file which I called test4.php

since you are looking at m including the file test3 will include the file once but stop further execution.

The difference lies in the error that the commands generate. With require, it really needs the file you want to use, and thus generates an E_ERROR if it's not found.

require() is identical to include() except for the failure, it will also result in a fatal E_ERROR level error.

include throws an E_WARNING error if it fails, which is more or less silent.

So use it if the file is needed for the rest of the code to work and you want the script to fail, the file is not available.

For *_once() :

include_once() can be used in cases where the same file can be included and evaluated more than once during a particular script execution, so in that case it can help avoid issues like function redefinition, redefinition variable values, etc.

The same applies to require_once() , of course.

This question was asked seven years ago and none of the answers provide practical help for this question. In modern PHP programming, you basically use required_once only once to enable your autoloader (often composer's autoloader) and it will load all your classes and functions (feature files must be explicitly added to the composer.json file to be available in all other files). If for some reason your class is not loaded from the autoloader, you use require_once to load it.

These days, you only need to split a large chunk of a PHP file. This is basically the definition of a large array. In such cases, you only use require require_once .

"y"];

If the file you are going to use contains something executable or declares some variables that almost all the time you need to use require , because if you use require_once elsewhere your code will not be executed and/or your variables will not initialize silently, causing errors that are absolutely hard to spot.

The practice of include and include_once is practically not used.

You must store class and function definitions in files.

Use require_once() to load dependencies

Use require() to load template-like files.

Use include_once() to load optional dependencies(classes, functions, constants).

Use include() to load optional template-like files.

required will result in a fatal error (E_COMPILE_ERROR) and stop the script.

turn on will issue a warning (E_WARNING) and the script will continue.

Operator require_once can be used to include a PHP file in another when you may need to include the called file more than once.

If a.php is a PHP script that calls b.php with require_once() and does not find b.php, a.php will abort execution, causing a fatal error.

include()

It contains the specified file. It will issue a warning if it cannot find the file and execute the rest of the scripts

required()

It contains the specified file. This will result in a fatal error if it can't find the file and will stop executing

It contains the specified file. the file is already included, it will no longer be included. It issues a warning if it cannot find the file and execute the rest of the scripts.

It contains the specified file. the file is already included, it will no longer be included. This will result in a fatal error if it cannot find the file and will abort execution.

is identical to include/require, except PHP checks to see if the file has already been included, and if so, don't include it (required) again.

In the era of PSR-0/PSR-4 autoloaders, it might be completely unnecessary to use any statements if all you want is to make some functions/classes available to your code (of course you still need to use require_once in your file bootstrap and include templates if you are still using PHP as your template engine).

require() is identical to include() , except it fails, it will also result in a fatal E_COMPILE_ERROR level error. In other words, it will stop the script, whereas include() will only issue a warning (E_WARNING) that allows the script to continue.

The same is true for the _once() options.

I have used a function like below:

Function doSomething() ( require_once(xyz.php); .... )

Constant values ​​have been fixed in xyz.php.

I need to call this doSomething() function from another PHP script file.

But I observed the behavior when calling this function in a loop, for the first iteration doSomething() was getting constant values ​​inside xyz.php , but later each iteration of doSomething() could not get the constant values ​​declared in xyz.php .

I solved my problem by switching from require_once() to include() , the updated doSomething() code looks like this:

Function doSomething() ( include(xyz.php); .... )

Now each iterative call to doSomething() gets the constants defined in xyz.php .

When should you use require or include ?

The require and include functions perform the same task, i.e. include and evaluate the specified file, but the difference require will result in a fatal error if the specified file location is invalid or for any error, while include will generate a warning and continue executing the code.

So you can use the require function in case the file you are trying to include is the heart of the system and can have a huge impact on the rest of the code, and you can use the include function when the file you're trying to include is a simple file containing less important code.

And my personal recommendation (for less important code) is to use the require function everywhere in your code while it's in development so that you can debug the code and then replace all the require functions with include before you move it into production so that if you miss any errors it won't affect the end user and the rest of the code will execute correctly...

When should you use require_once or require ?

The main difference between require and require_once is require_once will check if the file is included or not, if it is already included then it will not include the file whereas the require function will include the file whether the file is included or not.

So, in cases where you want to add a piece of code again and again, use the require function, whereas if you want to include some code only once in your code, use require_once .

These are all ways to include files.

Require means that it is required. Require_once means it will be required, but only required once. Include means that it will include the file, but it is not needed to continue.

Require "filename" Require_once "filename" Include "filename"

There is also the include_once function, which includes a file once.

include_once "filename"

Do not use capital letters when I write from my phone.

Basically, if you need the wrong path, PHP throws a fatal error and the shutdown function is called, but when you include the wrong path, PHP will continue executing, but it will just show a warning that the file does not exist.

From the English word required, PHP says that the execution of a page or file depends on the required file.

In my experience, this is the norm, requiring important files such as configuration files, database classes, and other important utilities.

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 PHP configuration we have 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

The require construct

Design require allows you to include files in a PHP script executing a PHP script. General Syntax require such:

require filename;

When starting (namely, at startup, and not at execution!) 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, he will do this immediately before starting the program (unlike, which is discussed below). This can be quite handy for including various template pages in 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 outputs the body of the document itself
require "footer.htm";
?>

Thus, the construction require allows you to assemble PHP scripts from several separate files, which can be either html-pages, and php-scripts.

Design require supports inclusions deleted 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 such an option is enabled in the configuration PHP file. detailed information.

Remote File Inclusions

PHP allows you to work with URL objects, as with regular files. The default packers are used to work with remote files using ftp protocol or http.

If "fopen wrapper URLs" are enabled 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 included file using a URL query string, as in an HTTP GET. Strictly speaking, this is not the same as including a file and inheriting the parent file's variable scope; because the script works on remote server, and the result is then wired into a local script.

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

note: Versions of PHP for Windows prior to PHP 4.3.0 do not support the ability to use remote files with this function, 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. */

// Will not work because file.txt is not parsed by www.example.com like PHP
include "http://www.example.com/file.txt?foo=1&bar=2";

// Won't work because it looks for the file "file.php?foo=1&bar=2" in the local
// file system.
include "file.php?foo=1&bar=2" ;

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

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

?>

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

Date: 2012-10-15

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

In the last lesson, we analyzed the work in detail. Recall that the operator include() in PHP, substitutes the content of one web page into another web page. But there are other functions in PHP that allow you to accomplish 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 desired file. For example, like this:

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

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

Suffix " _once" allows you to connect the file code for substitution in 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 move the site header to a separate file header.php, for simplicity, we will assume that we put the graphic logo of the site into this file. AT right place web pages (in this case, in place of the site header), write the code Listing 1.

Listing 1.

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

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

In general, an include file may contain functions that, when added to original file, may give 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 it can be re-enabled, and this can lead to an error. Therefore, they came up with the prefix " _once" to functions include and require, which includes the contents of a file in another web page only once.

How does the include() function differ from require()

Now let's talk than a function include() different from function require(). There is no difference in their work. Both functions include the contents of one file in another. But they have a difference and it lies in the way they react to the situation when the file that we connect is not in place.

Let's go back to the previous code example Listing 1. We have 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 the following error:

As you can see, a message appeared stating that in the directory (folder) blocks file not found header.php, but the program still runs and the rest of the site's web page displays normally.

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

Listing 3.

Require("blocks/header.php");

Then we have only one error message will be displayed, and the program will no longer run., and you will see only this message.

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 path in include_path , the include statement will try to check the current working directory where the include file script is located, if the 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 the 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

require statements and require_once 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.

A computer