Thursday, November 10, 2011

Include another PHP files


You can insert the content of one PHP file into another PHP file before the server executes it, with the include() or require() function.
The two functions are identical in every way, except how they handle errors:
  • include() generates a warning, but the script will continue execution
  • require() generates a fatal error, and the script will stop
These two functions are used to create functions, headers, footers, or elements that will be reused on multiple pages.

Include 
<?php include("header.php"); ?>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>

<div class="leftmenu">
<?php include("menu.php"); ?>
</div>

<h1>Welcome to my home page.</h1>
<p>Some text.</p>

Require
<?php
require("wrongFile.php");
echo "Hello World!";
?>

Include Vs. Require
In include : Notice that the echo statement is executed! This is because a Warning does not stop the script execution
-------------------------------------
Warning: include(wrongFile.php) [function.include]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5

Warning: include() [function.include]:
Failed opening 'wrongFile.php' for inclusion
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5

Hello World!
-------------------------------------
In Require : The echo statement is not executed, because the script execution stopped after the fatal error.
-------------------------------------
Warning: require(wrongFile.php) [function.require]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5

Fatal error: require() [function.require]:
Failed opening required 'wrongFile.php'
(include_path='.;C:\php5\pear')
in C:\home\website\test.php on line 5
-------------------------------------

No comments:

Post a Comment