php include, all paths get messed up - php

When i use php include to include a page in my website all the paths in the file i include get messed up. The included page acts like it is in the same folder as the page im including from.
Is there way to avoid/fix this problem?

One way I try to get around this problem is by always including from where the file that is including the other file is based:
$here = dirname(__FILE__);
include($here."/../include.php");
// will include a file *allways* one level up from where *this* file is located
// and not the file that started the execution of the script.
I sometimes have files that are accessed from several different places and so the includes file path can become a bit hard to manage. So I usually try to include a configuration file at a known point then define paths to common include points.
// from a common config file
define("PATH_TO_CLASS", dirname(__FILE__)."/../class");
define("PATH_TO_MEDIA", dirname(__FILE__)."/../assets/media");
Then you can use in the file you've included the config file like:
include dirname(__FILE__)."/../config.php";
include PATH_TO_CLASS."/snassy.class.php";

What is your include path set to? If included.php is not the same directory as page.html, you can append to you existing include path.
<?php
$path = '/path/to/includes';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
?>
Try the PHP manual

You might need to set the include path correctly, for example via:
set_include_path(get_include_path() . PATH_SEPARATOR . 'YourPath');
Then you just need to include as if it were is the same directory:
include 'FileName.php';

No, that is the default behaviour of the php include function: It basically copies the contents of the included file into the including file. That way the instructions in the included file behave as if they were in the including file (because they are in a way).
You either have to refactor the instructions in you included file so they can operate from the folder of the including file, or add the folder of the included file to the include path.

You could use absolute paths? 'http://www.site.com/the/full/url/image.jpg'
Or even
$path = 'http://www.site.com';
and $path.'images/image.jpg' or whatever it is

Another answer for you. If things are unchangeable for some reason I've used chdir() to some success.
For example I had mobile users come from and use a different directory than the main site, but wanted to use all of the functions and classes of the main site, so I would chdir(/to/the/main/site/folder); right before calling the common code, which required different include paths. I would use sparingly though... as things can get confusing.

Related

including files from different directories

So I set up my include files, such as header.php, nav.php, and footer.php in a /inc folder.
Then I include the files in my pages. But if I have another folder, for example wiki where i'd like to include those files onto the pages of wiki, the file paths for the includes break.
Example: I have included this in a page from the wiki directory.
<?php include_once('../inc/header.php'); ?>
I have two other includes in the header.php file, but since I'm including them in a different directory, both includes break, unless I go and append a ../ in the include path.
I'm wondering what is the best way to include files within different directories and not having to go back and fix the path?
Create constants using realpath in the initial file and then reference them using easy to read and manage but now absolute paths.
You can see an example here:
How can I get the "application root" of my URL from PHP?
I'd also suggest testing for the constant definition before defining.
The simplest solution? Use absolute paths.
If the files are in directories of the same level, the relative pathes (with ../) will be the same. If you have one within another, you will need to have the ../ on the beginning of the one in the sub-directory. The only way around changing the paths is to create a link as a sub-directory representing the main directory, although this can have dangerous consequences relating to recursive processes.
btw, include_once means that this operation is "optional", meaning the program will continue to execute. If you require the files included, use require_once, and the program will break if it's not there.
Include them like this
require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'inc'.DIRECTORY_SEPARATOR.'header.php');
This could work!
I like using this method:
define('ROOT_DIR', dirname(__FILE__) . '/'); // Defined on the index or in the bootstrap
include(ROOT_DIR . 'subfolder/fileName.php');
If you use PHP's native set_include_path to add an include folder you can then include files just by their name.
<?php
/**
* The path to your /inc/ folder.
*/
$path = '/absolute/path/to/inc/';
/**
* get_include_path retrieve's the current include path.
* It's a bad idea to over write the entire include path
* The PATH_SEPARATOR constant is set per operating system
*/
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
/**
* You can now include any files in /inc/ from any directory with no path
*/
include_once('header.php');
?>
$_SERVER['DOCUMENT_ROOT'] gives you the DocumentRoot of your webserver, e.g. Apache. Then you can take that as a stable datum and map from there as that won't vary.
include_once($_SERVER['DOCUMENT_ROOT'].'/inc/header.php');
I found that I had to do str_replace("\\","/",$_SERVER['DOCUMENT_ROOT']) when running on IIS if that helps.

PHP: require doesn't work as it should

I have a directory root:
index.php
includes/
template.php
testfile.php
phpFiles/
processInput.php
testfile.php
index.php:
require_once("includes/template.php");
template.php:
require_once("includes/phpFiles/processInput.php")
processInput.php:
require_once("testfile.php")
require_once("../testfile.php")
This code will work when you run index.php, of course it will not work when you run template.php.
As you can see, index.php includes template.php like normal. But in template.php, you have to include like if you are in the directory that index.php is in. But then, in processInput.php, you include as if you are in the directory that processInput.php is in.
Why is this happening, and how can I fix it so that the include path is always the directory of the file that the require is done in? The second included file have the same include path as the requested file, but the next one does not.
Thanks for your help!
EDIT: The strange thing is that I've included classes in a class folder. And it included other files as it is supposed to, even though the paths are relative. WHY does this happen, and how can I fix it?
VERY IMPORTANT EDIT: I just realized that all this is because in my example, the inclusion in includes/phpFiles/processInput.php includes a file in the same directory: require_once("file in same dir.php"); This is the reason. If you are including a file with out specifying anything more than the filename, the include_path is actually the dir where the file the require is written in is in. Can anyone confirm this?
Use an absolute path.
require_once($_SERVER['DOCUMENT_ROOT']."/includes/phpFiles/processInput.php");
Use a similar form for all your required files and they will work no matter where you are.
You can do this in a few ways, amongst others:
Use set_include_path to control the directories from where to perform require() calls.
Define a common absolute base path in a constant that you define in index.php and use that in every require() statement (e.g. require(BASEPATH . '/includes/template.php')).
Use relative paths everywhere and leverage dirname(__FILE__) or __DIR__ to turn them into absolute paths. For instance: require(__DIR__ . '/phpFiles/processInput.php');
By default, the current working directory is used in the include path; you can verify this by inspecting the output of get_include_path(). However, this is not relative to where the include() is made from; it's relative to the main executing script.
You're using relative paths. You need to use absolute paths: $_SERVER['DOCUMENT_ROOT'].
When you include/require, you are basically temporarily moving all code from one file, to another.
so if file1.php (which is located in root) contains:
require("folder/file.php");
and you include file1.php in file2.php (which is in a different location (say folder directory for example):
file2.php:
require("../file1.php");
Now all of file1.php code is in file2.php. So file2.php will look like this:
require("../file1.php");
require("folder/file.php");//but because file2.php is already in the `folder` directory, this path does not exist...
index.php:
require_once("includes/template.php");
template.php:
require_once("includes/phpFiles/processInput.php")
Your directory structure is off. The file inclusion is being seen from the file you're using it from. So, "template.php" is looking for an "includes/" folder in its current folder (/includes/).
As others are saying, use absolute paths, which will make sure you're always going at it from the file system root, or use:
require_once("phpFiles/processInput.php")
In your template.php file (which is far more likely to break if you ever move things around, which is why others all recommend using absolute paths from the file system root).
BTW, if you're using "index.php" as some kind of framework system, you can consider defining a variable that stores the address of common files such as:
define('APPLICATION_PATH', realpath(dirname(__FILE__));
define('PHPFILES_PATH', APPLICAITON_PATH . '/includes/phpFiles/');

Why would I use dirname(__FILE__) in an include or include_once statement?

I have seen this:
<?php
include( dirname(__FILE__) . DIRECTORY_SEPARATOR . 'my_file.php');
?>
Why would I ever need to do this? Why would I go to the trouble of getting the dirname and then concatenating that with a directory separator, and a new filename?
Is the code above not equivalent to this:
<?php
include( 'my_file.php' );
?>
??
The PHP doc says,
Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include() will finally check in the calling script's own directory and the current working directory before failing. The include() construct will emit a warning if it cannot find a file; this is different behavior from require(), which will emit a fatal error.
Let's say I have a (fake) directory structure like:
.../root/
/app
bootstrap.php
/scripts
something/
somescript.php
/public
index.php
Now assume that bootstrap.php has some code included for setting up database connections or some other kind of boostrapping stuff.
Assume you want to include a file in boostrap.php's folder called init.php. Now, to avoid scanning the entire include path with include 'init.php', you could use include './init.php'.
There's a problem though. That ./ will be relative to the script that included bootstrap.php, not bootstrap.php. (Technically speaking, it will be relative to the working directory.)
dirname(__FILE__) allows you to get an absolute path (and thus avoid an include path search) without relying on the working directory being the directory in which bootstrap.php resides.
(Note: since PHP 5.3, you can use __DIR__ in place of dirname(__FILE__).)
Now, why not just use include 'init.php';?
As odd as it is at first though, . is not guaranteed to be in the include path. Sometimes to avoid useless stat()'s people remove it from the include path when they are rarely include files in the same directory (why search the current directory when you know includes are never going to be there?).
Note: About half of this answer is address in a rather old post: What's better of require(dirname(__FILE__).'/'.'myParent.php') than just require('myParent.php')?
I might have even a simpler explanation to this question compared to the accepted answer so I'm going to give it a go: Assume this is the structure of the files and directories of a project:
Project root directory:
file1.php
file3.php
dir1/
file2.php
(dir1 is a directory and file2.php is inside it)
And this is the content of each of the three files above:
//file1.php:
<?php include "dir1/file2.php"
//file2.php:
<?php include "../file3.php"
//file3.php:
<?php echo "Hello, Test!";
Now run file1.php and try to guess what should happen. You might expect to see "Hello, Test!", however, it won't be shown! What you'll get instead will be an error indicating that the file you have requested(file3.php) does not exist!
The reason is that, inside file1.php when you include file2.php, the content of it is getting copied and then pasted back directly into file1.php which is inside the root directory, thus this part "../file3.php" runs from the root directory and thus goes one directory up the root! (and obviously it won't find the file3.php).
Now, what should we do ?!
Relative paths of course have the problem above, so we have to use absolute paths. However, absolute paths have also one problem. If you (for example) copy the root folder (containing your whole project) and paste it in anywhere else on your computer, the paths will be invalid from that point on! And that'll be a REAL MESS!
So we kind of need paths that are both absolute and dynamic(Each file dynamically finds the absolute path of itself wherever we place it)!
The way we do that is by getting help from PHP, and dirname() is the function to go for, which gives the absolute path to the directory in which a file exists in. And each file name could also be easily accessed using the __FILE__ constant. So dirname(__FILE__) would easily give you the absolute (while dynamic!) path to the file we're typing in the above code. Now move your whole project to a new place, or even a new system, and tada! it works!
So now if we turn the project above to this:
//file1.php:
<?php include(dirname(__FILE__)."/dir1/file2.php");
//file2.php:
<?php include(dirname(__FILE__)."/../file3.php");
//file3.php:
<?php echo "Hello, Test!";
if you run it, you'll see the almighty Hello, Test!! (hopefully, if you've not done anything else wrong).
It's also worth mentioning that from PHP5, a nicer way(with regards to readability and preventing eye boilage!) has been provided by PHP as well which is the constant __DIR__ which does exactly the same thing as dirname(__FILE__)!
Hope that helps.
I used this below if this is what you are thinking. It it worked well for me.
<?php
include $_SERVER['DOCUMENT_ROOT']."/head_lib.php";
?>
What I was trying to do was pulla file called /head_lib.php from the root folder. It would not pull anything to build the webpage. The header, footer and other key features in sub directories would never show up. Until I did above it worked like a champ.
If you want code is running on multiple servers with different environments,then we have need
to use dirname(FILE) in an include or include_once statement.
reason is follows.
1. Do not give absolute path to include files on your server.
2. Dynamically calculate the full path like absolute path.
Use a combination of dirname(FILE) and subsequent calls to itself until you reach to the home of your '/myfile.php'.
Then attach this variable that contains the path to your included files.

PHP absolute path in requireonce

I'm using a simple pre-made authorisation tool to secure my site. The tool requires this line of code to be applied to the top of every .php page. Auth.php lives on the root level.
<?php ${(require_once('Auth.php'))}->protectme(); ?>
I need to be able to add this line of code to every file, including files in sub-folders. But I'm unsure of how to apply the method as shown in require_once in php to ensure it always is linked absolutely, alongside the protectme(); function.
Any enlightenment is appreciated.
Cheers.
Set a variable to the absolute path. $_SERVER['DOCUMENT_ROOT'] is a PHP global variable that stores the servers, root path. You just need to insert the rest of the path information to the script. For instance if your website exists on /var/www/ and your script exists at /var/www/scripts you would do the following.
$path = $_SERVER['DOCUMENT_ROOT'] . '/scripts/Auth.php';
require_once($path);
You can use a relative path to get to it.
One level up: ../Auth.php
Two levels up: ../../Auth.php
etc.
You should alter your php.ini to change the include path to the the path to that (all all your other) included files. Then you can include them without a path on every page regardless of their own location.
More Details
Add the root level directory to your include_path - PHP will do the rest for you. No complicated variables, constants or whatever.
In addition to everything that has been said already, I suggest centralizing all common functionality. Create a file, like common.php with all includes that you need for you application and then include that from all your scripts.
Also, a nice way to do relative includes is by using dirname() function in combination with __FILE__ magic constant. For example:
require_once dirname(__FILE__) . '/../lib/common.php';
If you do not have access to php.ini, I've used something like this before
include $_SERVER['DOCUMENT_ROOT']."/"."include_me.php";
The easiest way since it's a site wide change is to add its directory first in the include path in php.ini.
If you can't change php.ini, there are a few other options for adding it to the include path.

How to include file from another directory

In the root (www) I have two folders.
In the first folder, "folder1", I put a file called register.php.
In the next folder, "folder2", I put files called header.php and footer.php.
I need to include the header and footer files from folder2 in the register.php file.
How can i do this? I tried to use this include ../folder2/header.php
..but it does not work
On some configurations, adding ./ (current dir) does the trick like this:
include './../folder2/header.php';
Alternatively, you can specify in terms of document root:
include $_SERVER['DOCUMENT_ROOT'] . 'folder2/header.php';
<?php include( $_SERVER['DOCUMENT_ROOT'] . 'folder2/header.php' ); ?>
include $_SERVER['DOCUMENT_ROOT'] . '/folder2/header.php';
would work from any directory of the site
it is called absolute path and it's the only reliable way to address a file
However, in real it should be something like
include $_SERVER['DOCUMENT_ROOT'] . '/cfg.php';
// some code
include $TPL_HEADER;
using a variable, previously defined in cfg.php
However, it may fail too. Because you can be just wrong about these paths
And here goes your main problem:
but it does not work
There is no such thing as "it does not work"
There is always a comprehensive error message that tells you what exactly doesn't work and what it does instead. You didn't read it yourself, and you didn't post it here to let us show you a correct path out of these error messages.
include files should generally be kept outside of the server root.
lets say your setup is;
www/website1
and
www/includes
Then you php.ini file, or .htaccess file should stipulate that
include_path=www/includes
then from any of your files, in any directory, no matter how far down the trees they go you simply do:
include 'myfile.php';
where myfile.php is at www/includes/myfile.php
Then you can stop worrying about these issues
include dirname(__FILE__).'/../folder2/header.php';
Try This it is work in my case
<?php require_once __DIR__."/../filename.php";?>
As the PHP manual states here $_SERVER['DOCUMENT_ROOT'] is "The document root directory under which the current script is executing, as defined in the server's configuration file." For this example, $_SERVER['DOCUMENT_ROOT'] will work just fine but. . . By using the new "magic constants" provided in >= PHP 5.3, we can make this code a little safer.
Put your includes in a subfolder, and use the magic constant DIR to make a reference to the included files. DIR returns the directory of the currently executing php file. By using this, you can move your folder containing all your includes anywhere you like in your directory structure, and not need to worry if your includes will still work.

Categories