codescracker


php

PHP File Inclusion



« Previous Tutorial Next Tutorial »


You are free to include any PHP file into another PHP file before the server executes it. There are two functions available in PHP helps in including the content of one PHP file into another PHP file:

PHP include() Function

Let's suppose we have a file contains common menu for all pages. The name of this file is menu.php, containing the following contents:

<pre><a href="http://codescracker.com">Home</a> - 
<a href="http://codescracker.com/html">HTML</a> - 
<a href="http://codescracker.com/java">Java</a> - 
<a href="http://codescracker.com/sql">SQL</a> <br />

Now, here is another file, and we are going to include the content of the above PHP file inside this file:

<html>
<body>
<?php include("menu.php"); ?>
<p>This is an example to know how to include a PHP file!</p>
</body>
</html>

Here is the output of the above PHP file:

Home - HTML - Java - SQL

This is an example to know how to include a PHP file!

As you can see from the above example, the content of the menu.php file is displayed by the above PHP file. Now let's discuss about the require() function in PHP

PHP require() Function

Basically, there is no difference the PHP require() and PHP include() function, except that, they handle error conditions. It is recommended to use the PHP require() function instead of PHP include() function, because the scripts shouldn't continue executing if the files are missing or misnamed. Here is an example, uses require() function in including the PHP file in another PHP file:

<html>
<body>
<?php include("xmenu.php"); ?>
<p>This is an example to show how to include a wrong PHP file!</p>
</body>
</html>

It will produce following result :

This is an example to show how to include a wrong PHP file!

Now let's try same example with require() function :

<html>
<body>
<?php require("xmenu.php"); ?>
<p>This is an example to show how to include a wrong PHP file!</p>
</body>
</html>

This time file execution halts and nothing is displayed


« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test