HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

PHP Include Files

The include (or require) statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement.



PHP include and require Statements


The include and require statements are identical, except upon failure:


require will produce a fatal error (E_COMPILE_ERROR) and stop the script
include will only produce a warning (E_WARNING) and the script will continue



Syntax


include 'filename';

or

require 'filename';



• PHP include Examples

Assume we have a standard footer file called "footer.php", that looks like this:


<?php echo "<p>Copyright © 1999-" . date("Y") . " codelines.in</p>"; ?>

To include the footer file in a page, use the include statement:


Example


<!DOCTYPE html>
<html>
<body>

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

<p>Some more text.

<?php include 'footer.php';?> </body> </html>

Output

Welcome to my home page! Some text. Some more text. Copyright © 1999-2024 codelines.in


• PHP include vs. require

The require statement is also used to include a file into the PHP code.


However, there is one big difference between include and require; when a file is included with the include statement and PHP cannot find it, the script will continue to execute:



Example


<!DOCTYPE html>
<html>
<body>

<h1>Welcome to my home page!</h1>
<?php include 'noFileExists.php';
echo "I have a $color $car.";
?>

</body>
</html>

Output

Welcome to my home page!

I have a .


If we do the same example using the require statement, the echo statement will not be executed because the script execution dies after the require statement returned a fatal error:



Example


<!DOCTYPE html>
<html>
<body>

<h1>Welcome to my home page!</h1>
v?php require 'noFileExists.php';
echo "I have a $color $car.";
?>

</body>
</html>

Output

Welcome to my home page!

Use require when the file is required by the application.

Use include when the file is not required and application should continue when file is not found.