How To Include A File In Php

Table of contents:

How To Include A File In Php
How To Include A File In Php

Video: How To Include A File In Php

Video: How To Include A File In Php
Video: 23: How to Include Documents in PHP | PHP Tutorial | Learn PHP Programming | PHP for Beginners 2024, November
Anonim

To connect an additional file to a PHP script, use the special function include. After connecting an external document, the programmer has the opportunity to use the written code or other content in the current application.

How to include a file in php
How to include a file in php

Include function

Include has the following syntax:

include “file name”;

The name is a relative or absolute path with the extension of the included document. If no location is specified, PHP will automatically check the contents of the configuration php.ini, which specifies include_path - a directory where additional libraries can be placed. If the directive is empty or the required file is not found at the path specified in it, the include expression will be ignored.

Once enabled, you can use the content you want in the script, assign variables, use declared constructs, etc. For example, there are 2 files 1.php and 2.php. The content of 1.php looks like this:

<? php

$ firstly = “variable from the first file”;

$ secondly = “imported value”;

?>

To include the variables mentioned above in 2.php, you can perform the following operation:

<? php

Include “1.php”;

echo $ firstly;

$ emerge = “$ secondly”;

echo $ emerge; ?>

In this script of the second file, the include command includes the contents of the first document, after which the variables declared in 1.php are used to display the necessary values on the screen.

Include can be used both at the very beginning of the file and inside the declared function in any part of the document. It is undesirable to use the function to connect files located on a remote server. If you want to implement this feature, you will need to enable the allow_url_fopen option in the php.ini file on your local or remote server.

Require

The require function is similar to include. The commands do not differ in syntax and execution technology. The only difference is that if the specified file is missing, require terminates the script, while include will continue executing the script and display the corresponding E_WARNING warning, which can be suppressed using the @ special character. For example:

<? php

require “1q.php”;

echo “Script stops working”; ?>

In this example, the path to the non-existent document 1q.php is specified. If the file is missing, the script will not execute the echo command, and the user's screen will either have a blank sheet or an error message (depending on php.ini settings). If you enter similar code using include:

<? php

include “1q.php”;

echo “Script continues”; ?>

The echo command will be executed and the corresponding text will appear on the display.

Recommended: