Include and Require in PHP

PHP website or project is divided across multiple files. Each file performs a specific functionality. Often times, we need to use the contents of one file into the other. For instance, you have created a PHP header which you want to use across multiple pages, you will need a mechanism to do so. Include and Require provides such facility.

The include statement is used to copy the contents of the file which is being included to the file where include statement is being used. Require statement also performs the same task but if file is not found, PHP script throws exception and dies at that point. Include, however let the script execute even if the file is not found. Have a look at the following example to see how include works.

First create a PHP file named “filetoinclude.php” and add the following piece of code in it.


This is the header in some other file';
?>

Now create another PHP file and add the following code to it.





    

In the above code, the contents of the file “filetoinclude.php” are being added via include function. The include function is simple to use. You just have to call include followed by the name of the file to include within the single quotation marks.

It is pertinent to mention here that if we remove the file “filetoinclude.php” and then execute the above code, the code shall execute without any error only the contents of the filetoinclude.php will not displayed. However, if require function is used instead of include and then he file “filetoinclude.php” is deleted, the script shall die at require statement.

Download the code
Run the code

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .