Reputation: 2760
I have a file that is called header (the header of my site).. I use that file in all my site. The problem is that it has this include in it:
include_once("../untitled/sanitize_string.php");
which means that a mistake may be thrown, depending on who calls the header file.
I have directories, subdirectories and subdirectories to the subdirectories.. is there a simple way to prevent this from happening.. Instead of taking the satize string include and placing it on every page and not in the header file
Warning: require_once(/untitled/sanitize_string.php) [function.require-once]: failed to open stream: No such file or directory in C:\xampp\htdocs\PoliticalForum\StoredProcedure\User\headerSite.php on line 7
Fatal error: require_once() [function.require]: Failed opening required '/untitled/sanitize_string.php' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\PoliticalForum\StoredProcedure\User\headerSite.php on line 7
Upvotes: 0
Views: 1626
Reputation: 3163
For php 5.3 you can do:
include_once(__DIR__ . '/../untitled/sanitize_string.php');
where __DIR__
is the directory for the current file
For older versions you can use
include_once(dirname(__FILE__) . '/../untitled/sanitize_string.php');
where __FILE__
is the path for the current file
Lets say you have the following structure:
/app/path/public/header.php
/app/path/public/user/profile.php
/app/path/untitled/sanitize_string.php
If your header.php
includes santitize_script.php
with a relative path like so:
include_once("../untitled/sanitize_string.php");
the php interpreter will try to include that file RELATIVELY to the current working dir so if you will do a request like http://localhost/header.php
it will try to include it from /app/path/public/../untitled/sanitize_string.php
and it will work.
But if you will try to do a request like http://localhost/user/profile.php
and profile.php includes header.php, than header.php will try to include the file from /app/path/public/user/../untitled/sanitize_string.php
and this will not work anymore. (/app/path/public/user
beeing the current working dir now)
That's why is a good practice to use absolute paths when including files. When used in header.php
, the __DIR__
and __FILE__
constants will always have the same values: /app/path/public
and /app/path/public/header.php
respectively no matter where header.php
will be used thereafter
Upvotes: 4
Reputation: 104
You're going to have to use absolute paths here, as opposed to relative. I often set up some constants to represent important directories, using the old Server vars. Like so:
define('MY_DIR',$_SERVER['DOCUMENT_ROOT'].'/path/to/yer/dir');
Then, modify your include statement:
include_once(MY_DIR.'/your_file.php');
Upvotes: 1
Reputation: 3848
You may consider setting a global include path while using include.
Upvotes: 5
Reputation: 50976
Use absolute path as yes123 said.
include_once(dirname(__FILE__)."/../untitled/sanitize_string.php");
Upvotes: 1