PHP file Include Once script and exampleBy using PHP include() function and file can be used (included ) to any script or file. This is required where we have a common set of code to be used or any declarations or say the database connection is required for the script. All the files in the script can call the file storing database information by using include command and the set of code having all the information about database connection inside the included file gets attached to the main file.
It is important to note that when a file is included by using include functions then its is parsed as html mode unless the included file has php start and end tags inside it. Here is a simple example of PHP include.
This will include the file name config.php of the include directory. Please note that here we have used relative path in respect to the script running. "include/config.php" is the file name config.php inside the directory name include.
If the file is one step above ( or towards root ) the present directory then we can call the file like this
If we are keeping any PHP code inside the config.php file then we must use PHP start and end tags in those area (<?Php And ?> ). Without this all are taken as html code only.
If we are including the file and if there is a chance that we may declare some functions or variables again then we can use the function include_once() which will take care of this.
PHP function include() can work for internal files only. This way we can't include external files( say in another server ) to our script.
To read an external URL it is better to use fopen() .
include_once()If we want to include a file once only and further calling of the file will be ignored then we have to use the PHP function include_once(). This will prevent problems with function redefinitions, variable value reassignments, etc. Here is one example to explain this.
Let us create one PHP file and name it as data.php . Here is the content of this file
Now let us create one more file and from that we will be including the above data.php file . The name of the file will be inc.php and the code is given below.
So here in the above code the echo command displaying Hello will be displayed three times and not five times. The include_once() command will not include the data.php file again.
Be the first to post comment on this article :