PHP | better way to include a file

|
| By Webner

Have a look at this folder structure:

Test
Folder1
Abc.php
Folder2
Qwerty.php

Now in Abc.php file, try to include Qwerty.php using the following code:

Abc.php
include(‘../Folder2/Qwerty.php’)

It will give this error:

Fatal error: Failed opening required ‘../Folder2/Qwerty.php’
(include_path=’.:/usr/local/lib/php’)
in /Test/Folder1/Abc.php on line 2″

Code looks for:

‘../Folder2/Qwerty.php’ relative to ‘/’ not relative to ’Abc.php’

Use this code instead:

$ds = DIRECTORY_SEPARATOR;
//extract absolute path of Abc.php first and then go to its parent folder
$base_dir = realpath(dirname(__FILE__) . $ds . '..') . $ds;
include "{$base_dir}{$ds}Folder2{$ds}Qwerty.php";

__FILE__: The full path and filename of the current file with symlinks resolved. If used inside an include, the name of the included file is returned.

dirname: The dirname() function returns the directory name from a path.
For example,echo dirname(“c:/testweb/home.php”) . “”;
Output:

c:/testweb

realpath: The realpath() function returns the absolute pathname.
This function removes all symbolic links (like ‘/./’, ‘/../’ and extra ‘/’) and returns the absolute pathname.
This function returns FALSE on failure.

Leave a Reply

Your email address will not be published. Required fields are marked *