PHP: Calling External Scripts (Include and Require)
Tutorials > PHP > Calling External Scripts
PHP: Calling External Scripts using Include and Require
Within PHP, there are two very useful functions that allow you to use external scripts and files within a PHP script. The main purposes of these functions are to allow programmers to keep codes for different tasks/purposes separate.
The code you will use is either 'include' or 'require'. Adding '_once' to either will tell the server not to include the file again if it has already been used within the script. This is useful if your script is using a process that should only be used once in a file, i.e. to define specific variables that you don't want changed. Note that the script within the external file will be executed at the point it is called.
include ( str path )
include_once ( str path )
include("main_page.php");
include_once("../../functions/send_email.php");
require ( str path )
require_once ( str path )
e.g. require("main_page.php");
require_once("../../functions/send_email.php");
The main difference between include and require is what happens when a file is not found. Include will continue with a script and include some error statements with the script output; with require though, the script will simply exit and an error will be shown.
Editors Notes:
The main benefits of using these methods are:
- Web Page Continuity: you can store web page layouts for dynamically generated pages in external files – allowing for easier and faster layout designing.
- Script separation: you can create separate files for each script you create, making them easier to manage.
- When it comes to OOP (Object Oriented Programming), this is almost always used.
Some people may think that this method will save time and processing power because the server does not have to compile code until it is needed. This is in fact a myth, unless your code is seriously inefficient. The truth is, in fact, the reverse. Using this method will generally cause scripts to take marginally longer to compile than if it was all within one script, but don't worry, it is usually no more than a few nanoseconds and is hardly ever noticeable. If you do notice a big difference, try looking at how your code is structured, both in the file itself and the external file; remember that there is almost always a more efficient way to write and structure a script.