PHP include relative path
You could always include it using __DIR__
:
include(dirname(__DIR__).'/config.php');
__DIR__
is a 'magical constant' and returns the directory of the current file without the trailing slash. It's actually an absolute path, you just have to concatenate the file name to __DIR__
. In this case, as we need to ascend a directory we use PHP's dirname
which ascends the file tree, and from here we can access config.php
.
You could set the root path in this method too:
define('ROOT_PATH', dirname(__DIR__) . '/');
in test.php would set your root to be at the /root/
level.
include(ROOT_PATH.'config.php');
Should then work to include the config file from where you want.
php includes is there any way to include a file relative only to that document?
This may help: (from http://php.net/manual/en/function.include.php)
Files for including are first looked
for in each include_path entry
relative to the current working
directory, and then in the directory
of current script. E.g. if your
include_path is libraries, current
working directory is /www/, you
included include/a.php and there is
include "b.php" in that file, b.php
is first looked in /www/libraries/
and then in /www/include/. If filename
begins with ./ or ../, it is looked
for only in the current working
directory or parent of the current
working directory, respectively
Your question states:
If I want to include another file
inside footer.php, I must do it
relative to the index.php file (the
one that is including it).
This is true only if the filepath you are trying to include()
starts with ./
or ../
. If you need to include a file above the current file using a relative path, you can (as you suggested) use:
include( dirname(__FILE__) . '/../file.php')
If you define an absolute path, you can also add this to the current include_path:
set_include_path(get_include_path() . PATH_SEPARATOR . '/absolute/path');
You can then do all your includes relative to '/absolute/path/'.
Impossible to use include function when resource paths are relative
The simplest way to achieve this is with a root-relative path. If you begin every link with a "/" it is read as relative to the root directory. Therefore on mywebsite.com, a link to "/folder/file.php" will always go to "mywebsite.com/folder/file.php" regardless of how many folders deep the current page is.
This works great for live sites on a server. The problem I'm struggling to work out is it fails in my local XAMPP setup (my testing server) and on a shared hosting setup where the domain name has not gone live yet because in both cases the server maps the root directory to the wrong place but on a live site, it solves your problem perfectly.
Relative paths and nested includes
I had a similar challenge and created a single file that defines constants for all the relevant paths that I want to be able to call as-needed. I include this file in all my pages (I define the $urlRoot so that this will work in all environments and is moveable do different domains, etc):
File: pathData.php (added MENUDIR for your example):
$baseDir = dirname(__DIR__) . '/';
$rootUrl = (!empty($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';
define('ROOTURL', $rootUrl);
define('BASEDIR', $baseDir);
define('INCLUDES', $baseDir . 'includes/');
define('INCLUDESURL', ROOTURL . 'includes/');
define('JQUERYURL', ROOTURL . 'includes/jquery/');
define('MENUDIR', ROOTURL . 'views/general/');
Then in each file, I include that file with an include that includes the relative directory path. For example:
include("pathData.php");
or
include("../pathData.php");
or
include("../../pathData.php);
etc.
So in your case you could (depending on where your pathData file is):
include("../pathData.php");
include(MENUDIR . "navbar.php");
etc...
PHP - include() or require() with relative paths won't work on windows, even when appending __DIR__
You need to add the \
after the directory name:
include(__DIR__ . "\\..\\another_folder\\file_2.php");
This will make the path be
C:\xampp\htdocs\main_folder\..\another_folder\file_2.php
instead of
C:\xampp\htdocs\main_folder..\another_folder\file_2.php
Also, for portability, it is advisable to use /
instead of \
, which works on all platforms, including Windows:
include(__DIR__ . "/../another_folder/file_2.php");
Are PHP include paths relative to the file or the calling code?
It's relative to the main script, in this case A.php. Remember that include()
just inserts code into the currently running script.
That is, does it matter which file the include is called from
No.
If you want to make it matter, and do an include relative to B.php, use the __FILE__
constant (or __DIR__
since PHP 5.2 IIRC) which will always point to the literal current file that the line of code is located in.
include(dirname(__FILE__)."/C.PHP");
PHP include html file containing relative path
The problem here is the discrepency between absolute and relative paths. By including it into some other path, effectively changing the path of chart.html
, but NOT changing the relative path of the dependent files, you break the code.
There is the base tag https://developer.mozilla.org/en/docs/Web/HTML/Element/base that you could put in the head. However, that may make matters worse, since the other content your index.php
might include will not work anymore, unless those use absolute paths. If you don't do this anyway, this might be a good solution.
The second solution would probably be to (programmatically) search for relative paths in your html and replace those paths with corrected paths on the fly. there are some weird cases where javascript is used in html and there may be some "anti-copy" protection js code, that will probably choke on this.
The third solution (depending on your use case of course) would be, to not include the html but instead put an iframe
in your output, where you point to the correct path. Since it's loaded from the right path, relative paths should work again. (I'd prefer that one, especially if it's some kind of "preview" functionality you're after).
Another solution could be to put another index.php
into the chart folder, that - by including (and making the original index.php
s code flexible enough) - will do the same work as the original index.php, but as it is requested from a different path, everything is fine.
A different approach would be URL rewrites, where you could make it appear as if the index.php was in the chart directory (a redirect from the original call might be necessary). URL rewrites can be difficult, depending on your overall setup.
Those are my proposals, however, depending on what you actually want to do with your project, there might be more suitable solutions.
update to the extra index.php
solution:
Note that this will only work for showing one project at a time, and not multiple simultaneously. Also this highly depends on what your index.php
does or how it works. Let me assume it looks like this:
<?php
$project = !empty($_POST['project']) ? $_POST['project'] : '';
$projects = array('chart', 'otherproject');
if(in_array($project, $projects)) {
include $project.'/'.$project.'.html';
}
foreach($projects as $p) {
echo '<a href="?project='.$p.'">'.$p.'</a>';
}
Now, the new chart/index.php
would do something like:
<?php $project='chart'; include '../index.php';
and you'd need to change your original /index.php
to:
<?php
$project = !empty($project) ? $project : ''; // <-- changed
$projects = array('chart', 'otherproject');
if(in_array($project, $projects)) {
include $project.'/'.$project.'.html';
}
foreach($projects as $p) {
echo '<a href="/URL/TO/ROOT/'.$p.'/index.php">'.$p.'</a>'; // <-- changed
}
making relative path for include files
I always included a config.php
in the first line of each php:
require_once($_SERVER['DOCUMENT_ROOT']."/".(explode ('/', $_SERVER['PHP_SELF'])[1])."/config.php");
This code should always find the root directory, and then include the config.php
file.
Note that you can put this file anywhere you want - it will always find it's location on its own. If you move the file to another directory subsequently, you don't have to change anything.
This config file then defines the paths to all subdirectories and other important files, relative to the root directory:
$paths = array(
"root" => "",
"controller" => "controller",
"stylesheets" => "css",
"images" => array(
"icons" => "img/icons",
"controls" => "img/controls"
),
"javascript" => array(...),
...
);
This array means, that the root folder (your public_html
) contains the directories "controller", "stylesheets", images" and so on. Images are either placed within "img/icons" or "img/controls".
All other files are included so:
require_once($paths['helper']['html']."/form.php");
This can be very useful, because it allows you to restructure your complete directory layout, and you only need to update your config.php.
And, last but not least, the config also contains a function like this:
$projectName = "YourProjectFolderName";
function fInc($filePath){
global $projectName;
return '//'.$_SERVER['HTTP_HOST'].'/'.$projectName.'/'.$filePath;
}
It can be used to convert paths which will be inserted into the HTML document.
Edit:
Note, that defining an array with all paths is just a suggestion. It helped me in my projects, as I often restructure my project layout. If you don't do that in your project, you can just define a
$rootDir = $_SERVER['DOCUMENT_ROOT']."/".(explode ('/', $_SERVER['PHP_SELF'])[1]);
and then include files with
require_once($rootDir . "/home/index.php");
This way, you won't need the config.php
anymore.
Related Topics
Method="Post" Enctype="Text/Plain" Are Not Compatible
How to Call a PHP Function on the Click of a Button
Sending Email Via PHP Mail Function Goes to Spam
Forcing a Simplexml Object to a String, Regardless of Context
PHP Echo VS PHP Short Echo Tags
How to Get Protected Property of Object in PHP
Using PHP 5.5'S Password_Hash and Password_Verify Function
Correct Way to Use Like '%{$Var}%' With Prepared Statements
"Invalid Parameter Number: Parameter Was Not Defined" Inserting Data
MySQLi_Real_Escape_String() Expects Exactly 2 Parameters, 1 Given
Selecting a CSS Class With Xpath
PHP Sort Array by Subarray Value
Why Is the Hash Part of the Url Not Available on the Server Side