PHP Include and Require Functions

Bookmark and Share

Speed up your developing by using PHP include() and require() functions. Learn how to include multiple files into one PHP file and learn why this is useful in this short lesson.

Introduction:

With PHP, there are two ways to include a file. There is the include() statement and the require() statement. Both constructs are very similar except on how they handle failures. Include() produces a Warning while require() results in a Fatal Error.

I prefer to not to use the require() statement, because if there’s an error, the rest of the page will not be displayed. Include() does not behave this way, the script will continue regardless and all of the other code will be executed.

When a file is included, any variables available at that line in the calling file will be available within the called file, from that point forward. For example, you may want to store all of your php functions or database username and passwords into a file called “inc_funct.php” and have all the other pages include it. This will save you the headache of having to retype the code over and over again.

Source PHP Code:

<?
// include a file.
include(‘inc_info.php’);
// display the value of the included file.
echo $password;
?>

Source PHP Code of Included File (inc_info.php):

<?
$password = “1234″;
?>

Conclusion:

Just be sure to properly type the path to your file. Note, if you’re including files that are in higher directories (parent directories), it’s best to type out the full path name starting from the home directory (ex: home/user/public/file.php).

Please rate this post by clicking a star:

(No Ratings Yet)

Leave a Reply





Tags: , , , , ,