Php the difference between include and require. Which is more correct to use - require or include? Get Blog Updates !!! Subscribe

Often you have to store all sorts of everywhere-used data / functions in separate files, and then include using include [_once] / require [_once]. But these files are usually not parsed by the server, that is, they can be viewed through a browser, which is what we want to avoid. It is not very correct to give such files the PHP extension, since they can be called through the browser, and, although we will not see the content, we will most likely start to get out some errors, since the code inside the files is usually designed to be executed in a certain environment (the presence of a connection to the database reading files / certain values \u200b\u200bof constants / variables). There are 2 outputs that are essentially similar:

  1. put all INC files outside of DOCUMENT_ROOT Apache
  2. write (.htaccess) to deny access to all files with certain extensions

Example

# prohibit downloading files with the specified extensions order deny, allow # deny access from everywhere deny from all # allow access from your ip (if you have it, of course, static) allow from<ваш ip>

require

Loads and inserts the code into a PHP script. If such a file, the code is not available, the further work of the entire PHP script stops. If the same instruction is called in the same script, then there will be either an error or ignoring the file loading - that is, a void will be stupidly returned.

PHP functions and developed libraries.

Call options:

require "file"; // I like this better, you can see it more clearly require ("file");

include

Loads and inserts the code into a PHP script. If such a file, the code is not available, then the main PHP script proceeds to the execution of the code after the include statement. If the file has already been downloaded earlier, it will be downloaded again. You cannot use to load the same modules with functions, there will be an error.

Used primarily for loading HTML inserts into pages.

Call options:

include "file"; // I like this better, you can see it more clearly include ("file");

There are also more functions require_once and include_once, the once prefix means loading data into a PHP script only once. If such a function is encountered twice in one script, then the code will be executed only at the first stage, all the others will be ignored, thereby increasing the speed of script execution.

What to use for in PHP files of Include or Require statement?
It is very convenient to split one large program or web page into several files. And it happens that you just need to connect your file to the script of another developer.

I will tell you one incident from my life. When I started learning HTML, I created my first website. At that time, I did not yet know that there was a programming language PHP. The site consisted of 100 pages. When I added an article, I had to specify the name and path of the new page on each page separately in the menu. It was horrible, because, as you know, this lesson took a lot of time until I learned about the Include statement with the ability to include third-party files to my page. As soon as I made a change in one third-party file, for example, in the menu, the replacement took place on all 100 pages. Convenient, fast and fashionable.

Let's try to connect a third-party file to our web page using a simple example.

Create a file named "index.php" with this code:

A bunch of text ……….

You can like this:

Include and Require statements on the site A bunch of text ……….

Now create a file "cop.php" with this code:


Result:

So what have we done?
In the file "index.php" we have connected to the third-party file "cop.php".

If you change the text in the "cop.php" file, then in the "index.php" file you will see the replacement.

Include statement template:

Require statement template:

Another example for pinning the topic.
We have a web page like this:

Include and Require statements on the site Home Author Contacts A bunch of text ……….
All rights reserved © 2012-2014..ru

Let's now split this web page into two blocks using the Include or Require statement, as in the diagram:

It will look like this:

Include and Require statements on the site A bunch of text ……….

Save it under the names "index.php", "avtor.php" and "kontakty.php"
That is, there will be three pages “index.php”, “avtor.php” and “kontakty.php”.

Now create a "menu.php" file for the menu:

Home Author Contacts


All rights reserved © 2012-2014..ru

Result:

If you change something in the "cop.php" or "menu.php" file, then the replacement will automatically occur in the three files "index.php", "avtor.php" and "kontakty.php". Try it yourself.

That's all! Subscribe to the blog update so as not to miss new ones pHP lessons... Good luck!

Did you like the post? Help others to learn about this article, click on the social media button ↓↓↓

Get Blog Updates !!! Subscribe:

Latest news categories:

One of the most fun and useful features of php is connecting another file. For example, a site has a top menu, a bottom menu, and between them the content of the page itself. And, for example, 10 pages of the site use the bottom menu. At some point, changes were required to it. In html, you would manually make changes in each separate file, but php allows you to significantly simplify the work with the site! The bottom menu code 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 must now be made only to the file with the menu, and on 10 others it will be displayed with the changes.

The meaning of connecting in php in simple Russian:

1.php file
Top Menu

2.php file
Lower menu

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

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

The path to the file

The file is connected according to the path specified to the file. There are two options for the path: relative and absolute. Relative is an indication of the path to the included file relative to the file with the connection instruction. 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 in the same directory as the file with the connection

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

include and include_once

include () - a construction designed to include files in PHP script code during PHP script execution. When processing the code, the instruction is replaced with the contents of the attached file. Let's consider an example right away.

Let's consider the work of include using two files as an example: index.php and text.php... For simplicity, let's say they are 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 "The text contained in the include file";

?>
The index.php file will display:

Plain text contained in the main file
The text contained in the include file
Isn't it convenient? Now, by changing the content in the text.php file, there will be a completely different result of index.php work!

Now let's talk about another design - include_once... It works exactly the same as include, only it was 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 can connect the file 2 or more times, which will affect the incorrect operation of the page and receive the corresponding error message.

PHP Code

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

// reconnection below will not be counted and displayed
// and because of it, no error message will be displayed
include_once "text.php"; // nothing will happen

require and require_once

The require and require_once statements work identically to include and include_once except for one peculiarity - if the included file is not found, the script execution will be stopped (the script will not be read any further), 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 are, check everything from the very beginning

1. Check if your server and php are working, if any php code on the site works 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 php file to be included is actually located at the address at which you specified
5. Try to specify not a relative path, but an absolute (full path to the file).

Example PHP Code

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

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

6. If your file is not connected 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, insert the following line

Error_reporting (E_ALL);
Both settings will force display errors

Thanks for your attention!

The require include construct

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

require filename;

At startup (exactly at startup, not at execution!) Of the program, the interpreter will simply replace the instruction with the contents of the file filename (this file may also contain a PHP script framed, as usual, with tags and ?> ). Moreover, he will do this immediately before starting the program (as opposed to the one discussed below). This can be quite convenient for including various template pages with HTML code in the script output. Let's give 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 build PHP scripts from several separate files, which can be like html-pages and php-scripts.

Design require supports including 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 \u003d 1 & bar \u003d 2";
// The following example works
require;
?>

! Design require allows to include remote files, if enabled in the PHP config file. Detailed information .

Includes remote files

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

If "URL fopen wrappers" are included in PHP (as in the default configuration), you can specify the file to be included using a URL (over 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 inheriting the variable scope of the parent file; after all, the script runs on a remote server, and the result is then connected to the local script.

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

note: PHP versions 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 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 as file.txt is not being processed by www.example.com as PHP
include "http://www.example.com/file.txt?foo\u003d1&bar\u003d2";

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

// The following example works:
include "http://www.example.com/file.php?foo\u003d1&bar\u003d2";

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

?>

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 reaction to the absence of an include file. Function include ("Enable") if the specified file does not exist, it will generate an error message of the E_WARNING type, but the program will continue to run. Unlike her, require ("Require") in the absence of a include file, it issues a fatal error (E_ERROR), which leads to the immediate termination of the script being executed.

Thus, based on the 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 does not generally 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... 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 include file was deleted by a virus or lost during the development process) it will simply terminate the script. In one of the future articles, I will show you how to track absolutely all non-standard situations in the code and keep abreast of what is happening inside the site.

Now let's consider the constructions include_once and require_once... From simple include and require they are distinguished by the "_once" ending, which prevents the same files from being reinserted.

For example, if your include file contains descriptions of classes or functions, then such a file cannot be re-included, since it will be re-executed and PHP will generate a fatal error when trying to define classes or functions with already existing names. There is no doubt that you can design your code in such a way that reconnection never happens, but this is 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 that contain one or more classes and do not contain code that can be executed "directly". I always connect such files using require_once... The second kind is templates or template chunks containing HTML and some PHP code. I connect such files using requirebecause sometimes the same piece of template can be used several times on the page.

I never use include and include_oncebecause I consider the absence of a file, which should be, a critical situation requiring an immediate solution without any compromises. And if I need to include a file, the existence of which is in doubt, then I just first check its existence using is_file ().

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 \u003d include ‘file.php’;

That's all for today, program correctly!