include, require and relative paths - php

I'm not sure why I always have some many problems with this. Anyways this is the path to the file I want to require
/var/www/vhosts/mysite.com/htdocs/Classes/DBConnection.php
This is the path to the file that has the require statement
/var/www/vhosts/mysite.com/htdocs/Classes/Forecast/MyFile.php
and this is the require statement in MyFile.php
require_once '../DBConnection.php';
I keep getting the "failed to open stream" error. It works fine if I put in an absolute path. Does anyone see the problem here?

If /Classes/Forecast/MyFile.php is included from /index.php the relative path will be from the index file. To solve this, use __DIR__. The require will then be relative from that file.
require_once __DIR__.'/../DBConnection.php';

I have a detailed answer on this in another question:
finding a file in php that is 4 directories up
It explains the caveats of relative file paths in PHP. Use the magic constants and server variables mentioned there to overcome relative path issues.

Yep. The path is relative to the file your including your class file MyFe.php from and not the class file itself. I am assuming MyFile.php is not really the page being served, but an included or autoloaded class.

Make your path relative to the initially requested file. So if you're hitting /var/www/vhosts/mysite.com/htdocs/index.php, which includes MyFile.php, your path would be "Classes/DBConnection.php"

Related

Php 5.4 Include / require -- cannot get file path right

Suppose i have this file:
/Home/user/docs/somewhere/inHere.php
And in this php, i want to require this:
/Home/user/other/well/buried/place.php
I know the difference between an absolute and relative path, but cannot seem to figure out how php wants this to look, i keep getting 'file not found or does not exist'
I am on a hostgator shared web server, if that has any bearing on anything.
Include it using absolute paths.
Either:
include '/Home/user/other/well/buried/place.php';
or do it relative from where you are, but still absolute:
include __DIR__ . '/../../other/well/buried/place.php';
The magic constant __DIR__ contains the absolute path to the file it was written in.
If you just do a relative path include '../../and-so-on', the starting point will change if you're including that file in some other file that resides in some other location.
Firstly you can get the current folder using getcwd().
Next, you can use $path = '../../etc'; $realPath = realpath($path). It will return false if the path is wrong, and the concrete path without relative ../'s if it is indeed an actual path.
If you still can't get it, var_dump($path); and then copy the path and try to cd into it, you should diascover what you are doing wrong at that point.
From the file location (somewhere) you have to go upwards (to docs) and another time (to user), and then go inside "other", like this:
include ("../../other/well/buried/place.php");
There you go.

PHP include file by relative path

This absolute path successfully includes my file httpapi.inc.php:
require_once '/home/devel/wwwroot/nm/dev/http-api/http-api/src/httpapi.inc.php';
The calling file is:
Caller relative:
/devel/phi/dev/appcenter-head/appcenter/application/nm/index.php
Caller location:
/home/devel/wwwroot/phi/dev/appcenter-head/appcenter/application/nm
Now, how can I include that same file based on a relative path like:
/devel/nm/dev/http-api/http-api/index.php
I must use this path "as is", since it is a config option passed by the user.
require() and include() should operate relative to the configured include paths and the currently executing script. So, this should work:
require_once('src/httpapi.inc.php');
To be perfectly precise, though, the current script's working directly is actually designated as one of the include paths in the default configuration. It won't work if you've mucked with it.
Using a . in the include path allows for relative includes as it means
the current directory.
Regarding your latest edit, your paths are different enough that it's simpler to just use the full path or add /home/devel/wwwroot/nm/dev/http-api/http-api/ to your config and use require_once('src/httpapi.inc.php').
You might use the document root from the $_SERVER variable:
http://www.php.net/manual/en/reserved.variables.server.php
require_once $_SERVER['DOCUMENT_ROOT'] . '/nm/dev/http-api/http-api/src/httpapi.inc.php';
include "src/httpapi.inc.php";

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.

$_SERVER['DOCUMENT_ROOT'] path not working

I am using document root to provide absolute path which is not working. if i echo this path it turns out to be C:wamp/www/proman/header.php. I i give relative path it works fine what is the problem here?
$path = $_SERVER['DOCUMENT_ROOT']."proman/header.php";
I elaborate my problem here: I have 2 php files data_object.php and user.class.php. user.class.php has an include statement for data_object.php which is relative to user.class.php.These two files are under different directory hierarchy.
Now I have to include this user.class.php in various files (like projects.php, links.php) under different hierarchy when I want to create a User() object. The problem is the relative path for file inclusion of data_object.php does work for say projects.php but if I open links.php the error message says it could not open file data_object.php in user.class.php.
What I think is for relative inclusion of data_object.php it is considering the path of the file in which user.class.php is included.
I am facing such problems in more than one scenarios I have to keep my directory structure the way it is but have to find a way to work with nested includes. I am currently running on a WAMP server but after completion I have to host the solution on a domain. Pls help
Since that's a server variable, you may or may not see it, depending on which web server you're running under (especially IIS), or if something's configured weird.
One way to deal with this problem is to set the variable.
$_SERVER['DOCUMENT_ROOT'] = "C:/some/absolute/path";
// or, if you put this code in a file that's in your document root:
$_SERVER['DOCUMENT_ROOT'] = dirname(__FILE__);
Then, you can either require() this file when you need to verify the document root, or use the auto_prepend_file php.ini option to include the file automatically.
If you are actually trying to make a URL, then you just specify an absolute URL - /proman/header.php, or a relative URL - ../proman/header.php.
In my experience, $_SERVER['DOCUMENT_ROOT'] doesn't including a trailing slash. Try:
$path = $_SERVER['DOCUMENT_ROOT'].'/proman/header.php';

Categories