PHP include file - The php require function


Home - Tutorials - Basics

In this tutorial I will show you how to divide your code into more files and how to include various files into your actual PHP code.

Tutorial info:


Name:PHP include file
Total steps:5
Category:Basics
Level:Beginner

Bookmark PHP include file



Bookmark and Share

Step 4 - The php require function


PHP include file


In a lot of cases it is very important to have the file really included in our code. For example if the include of a database management code fails and the script continue it's run then it will cause a lot of unwanted error in the later steps. To avoid this you can say if the include was not success then stop all the further activity. For this purpose was the function require() introduced.

The usage if php require function is quite similar to the include however if the file can not be found require will report a fatal error and the script will die.

Let's see an example:

Code:
  1. <?php
  2. echo "Try to include wrong file first with include.<br/>";
  3. include ('internalwrong.php');
  4. echo "Now try it with require.<br/>";
  5. require ('internalwrong.php');
  6. echo "Finish.";
  7. ?>
And the output will be:
Output:
Try to include wrong file first with include.
 
Warning: include(internalwrong.php) [function.include]: failed to open stream: No such file or directory in Z:WorkWebSitestestf1test.php on line 3
 
Warning: include() [function.include]: Failed opening 'internalwrong.php' for inclusion (include_path='D:Program FilesZendZendStudio-5.5.0binZendFrameworklibrary') in Z:WorkWebSitestestf1test.php on line 3
Now try it with require.
 
Warning: require(internalwrong.php) [function.require]: failed to open stream: No such file or directory in Z:WorkWebSitestestf1test.php on line 5
 
Fatal error: require() [function.require]: Failed opening required 'internalwrong.php' (include_path='D:Program FilesZendZendStudio-5.5.0binZendFrameworklibrary') in Z:WorkWebSitestestf1test.php on line 5
 
As you can see the include reports warnings but the executeion was continued and so you can see the output of the second echo function. However using the require to include the same file we got a fatal error and the script was stoped. You can't find the Finish message in the output.





Previous Step of PHP include fileNext Step of PHP include file


Tags: php incluude file, php include, include file, file include, php, include, file



Follow phpf1 on Twitter




F1 Site Family
AJAX F1
CSS F1
Database F1
Flash F1
HTML F1
Java F1
JavaScript F1
PhotoShop F1
PHP F1
Scripts F1
Tutorial F1
Windows F1

Total time: 0.0364