I want to refer to my website root, or more exactly, to the directory above my script's one.
Let's say my website is example.com/test. I made a installation site which writes a config file. But it shouldn't write it to example.com/test/install/config.php, but to example.com/test/config.php. And the biggest pain in the ** is that I run on Windows (my development PC).
How do I do it?
If you want to get the web-site document root, you can use:
$_SERVER['DOCUMENT_ROOT']
That should work regardless of the operating system and gives you a path on the local file system (so no www.etcetc.).
If you want to get the fully-qualified path of your site root, from that file it is:
$root = realpath(dirname(__FILE__) . '/../../..');
The double-dots work their way up the directory structure, then realpath() is used to turn it into a proper path. So if you want to traverse one less folder up, use two sets of dots rather than three.
Related
I have a little problem: I began a project as a subdirectory in a larger web project. Thus the web file path is something like /../myProject. But things have progressed and I've realized that this should be its own project. However, I'd like to be able to keep it where it (as a sub-directory) also make it a sub-domain wherein myProject becomes the root. (There is also the possibility that my project will be mirrored at a library site, where it will once be in a sub-directory).
The problem I having with all this is that in some cases I have html_partial files, (for instance for the header or footer). But the relative path of these partials differs depending on where you are in the file tree. I originally solved this by always going back to the root.
But now, you see, depending on where my project lives, the root will be different. What I'd like to do is declare myProject as the "application root" and then be able to use relative paths based on this application root rather the than the web root'. This way, all of the relative paths within 'myProject' will work no matter wheremyProject` lives in the web path.
Does PHP have a way to declare something like an Application Root if so, can you explain it me or direct me to its documentation. Thanks!
You could simply have a PHP file in your application root directory which would define the directory it is in as the application root. The file could be as simple as this:
<?php
define('APPLICATION_ROOT', __DIR__);
?>
You could then include this file as needed and base all of your file paths off of APPLICATION_ROOT. Note that APPLICATION_ROOT would not have a trailing slash as defined here (unless your file happened to be on in the machines root directory, which is unlikely).
I usually do something lile this in the front controller:
define('APPLICATION_PATH', realpath(__DIR__));
Then you can do things like:
set_include_path(APPLICATION_PATH . '/include');
Or:
$fp = fopen(APPLICATION_PATH . '/path/to/some/file', 'r');
If your app doesn't make use of a front controller, you could define an environment variable in your vhost config or .htaccess:
SetEnv APPLICATION_PATH /full/path/to/my/app
And then use:
getenv('APPLICATION_PATH')
Why the paths are hardcoded ? For example:
require_once 'Zend/Gdata/Extension.php';
The thing is that Zend folder is not in root - it's in library/packages
So do I have to change the path of every file?
To be like :
define('ROOT_PACKAGES', dirname(__FILE__) . "/library/packages/");
ROOT_PACKAGE.'Zend/Gdata/Extension.php';
Let me explain by asking you a question. When you use 'Zend/Gdata/Extension.php' - what directory is it looking in for the sub-directory Zend? You will answer "/library/packages/" and that leads to the key question. Why?
Update: My question is not why use that directory, it's why would the O/S have that directory as the default directory.
At any point in time there is a default directory. And relative paths will then be evaluated using that default directory. But the value of that is not locked to a specific directory. And it is dependent on how an app is running. I assume you have a web app and basically any code in your app, or the web server, can change the directory.
So yes, use ROOT_PACKAGES. You should always use fully qualified directories.
I have wamp setup on my windows box. Generally, when I bring a site down from the web, I create a folder inside my www folder for the site name. ex: c:\wamp\www\mysite. Once I have the folder, I copy down all the live files. The issue is that all the paths are then broken because my local folder isn't rooted.
What is the best way to setup paths so that if the site moves to a folder that isn't rooted, it will work easily?
I use a file (usually called something like config.php) to keep track of the root folder. My definitions (constants) look like this:
define('BASE_DIR','/wherever/whenever/');
define('LIB_DIR', BASE_DIR . 'lib/');
And then when you need to include a file
include LIB_DIR . 'aFile.php';
This would be something you do on a new site or if you have time to refactor your current site.
Create an include file, that has constants setup based upon whatever the root directory is... then in your code, use the constants you created to include files.
Also note, that when you are using directory "slashes", always use the build in constant DIRECTORY_SEPARATOR instead of hard coding it, this will allow you to go from WIndows to Linux seamlessly.
We use $_SERVER['DOCUMENT_ROOT'] to determine where we are in the filesystem and then simply append the folder name of our project to that. This works perfectly for us. You should always use a configuration.php where you define basic paths and URL's that may change when moving the project from one server/folder to another.
Option 1. Use <base href=""/> tag
Option 2. Use a config file, like #MattCan suggests
Option 3. Use a server environment variable, like #Bjorn suggests
Option 4. Create a virtual host on your apache, than you can create a domain who appoint exactly where are your app folder. Apache Doc here
I wrote a CMS in PHP. It works fine on most servers but I encountered a strange problem on my latest hosting account. This is either a path problem or a coding problem. The latter seems to be OK as this script works fine on all my other accounts, which is why I'm asking for help.
When I first install my CMS tool I run a script called "inventory.php" in which I attempt to get and display all the directories on the server from the location of my script, which is 2 or 3 directories down from the root, depending on the server. I try to use a global path that goes up to the root and from it to return all the directories it can find. If this file works then the entire CMS works; if not... well that's why I'm here.
Here's the code that scans the directories:
$main_root = realpath('../../');
echo '<b style="color:orange;">All The dirs on this server:</b><hr><br>';
$whats_on_the_server = array_filter(glob($main_root.'/*'), 'is_dir');
foreach($whats_on_the_server as $on_server) {
$on_server = trim($on_server);
if(stristr($on_server,'.')){
$arr1 = preg_split('^/^',$on_server);
echo $arr1[4].'<br>';
}
}
The root is: chroot/home/account/ under which all my folders are located. I can't run a script from that directory, so I must access it from elsewhere. This works fine on other servers but on the one I currently use, it doesn't return anything if the path is set as above. It gets the directory contents if I set the path to a subfolder on the specific server, such as:
$main_root = realpath('../../SomeDir');
I must however get the name of all the directories located on the root.
So probably you don't have the privileges to access the root but do have privilegs to access the given subdirectories?
By the way, you can go to root by simply doing
$main_root = realpath('/');
which is always your most upper path!
You should use:
$main_root = dirname(__FILE__).'../../';
where __FILE__ is a PHP constant for the current file.
In HTML, I can find a file starting from the web server's root folder by beginning the filepath with "/". Like:
/images/some_image.jpg
I can put that path in any file in any subdirectory, and it will point to the right image.
With PHP, I tried something similar:
include("/includes/header.php");
...but that doesn't work.
I think that that this page is saying that I can set include_path once and after that, it will be assumed. But I don't quite get the syntax. Both examples start with a period, and it says:
Using a . in the include path allows for relative includes as it means the current directory.
Relative includes are exactly what I don't want.
How do I make sure that all my includes point to the root/includes folder? (Bonus: what if I want to place that folder outside the public directory?)
Clarification
My development files are currently being served by XAMPP/Apache. Does that affect the absolute path? (I'm not sure yet what the production server will be.)
Update
I don't know what my problem was here. The include_path thing I referenced above was exactly what I was looking for, and the syntax isn't really confusing. I just tried it and it works great.
One thing that occurs to me is that some people may have thought that "/some/path" was an "absolute path" because they assumed the OS was Linux. This server is Windows, so an absolute path would have to start with the drive name.
Anyway, problem solved! :)
What I do is put a config.php file in my root directory. This file is included by all PHP files in my project. In that config.php file, I then do the following;
define( 'ROOT_DIR', dirname(__FILE__) );
Then in all files, I know what the root of my project is and can do stuff like this
require_once( ROOT_DIR.'/include/functions.php' );
Sorry, no bonus points for getting outside of the public directory ;) This also has the unfortunate side affect that you still need a relative path for finding config.php, but it makes the rest of your includes much easier.
One strategy
I don't know if this is the best way, but it has worked for me.
$root = $_SERVER['DOCUMENT_ROOT'];
include($root."/path/to/file.php");
The include_path setting works like $PATH in unix (there is a similar setting in Windows too).It contains multiple directory names, seperated by colons (:). When you include or require a file, these directories are searched in order, until a match is found or all directories are searched.
So, to make sure that your application always includes from your path if the file exists there, simply put your include dir first in the list of directories.
ini_set("include_path", "/your_include_path:".ini_get("include_path"));
This way, your include directory is searched first, and then the original search path (by default the current directory, and then PEAR). If you have no problem modifying include_path, then this is the solution for you.
There is nothing in include/require that prohibits you from using absolute an path.
so your example
include('/includes/header.php');
should work just fine. Assuming the path and file are corect and have the correct permissions set.
(and thereby allow you to include whatever file you like, in- or outside your document root)
This behaviour is however considered to be a possible security risk. Therefore, the system administrator can set the open_basedir directive.
This directive configures where you can include/require your files from and it might just be your problem.
Some control panels (plesk for example) set this directive to be the same as the document root by default.
as for the '.' syntax:
/home/username/public_html <- absolute path
public_html <- relative path
./public_html <- same as the path above
../username/public_html <- another relative path
However, I usually use a slightly different option:
require_once(__DIR__ . '/Factories/ViewFactory.php');
With this edition, you specify an absolute path, relative to the file that contains the require_once() statement.
Another option is to create a file in the $_SERVER['DOCUMENT_ROOT'] directory with the definition of your absolute path.
For example, if your $_SERVER['DOCUMENT_ROOT'] directory is
C:\wamp\www\
create a file (i.e. my_paths.php) containing this
<?php if(!defined('MY_ABS_PATH')) define('MY_ABS_PATH',$_SERVER['DOCUMENT_ROOT'].'MyProyect/')
Now you only need to include in every file inside your MyProyect folder this file (my_paths.php), so you can user MY_ABS_PATH as an absolute path for MyProject.
Not directly answering your question but something to remember:
When using includes with allow_url_include on in your ini beware that, when accessing sessions from included files, if from a script you include one file using an absolute file reference and then include a second file from on your local server using a url file reference that they have different variable scope and the same session will not be seen from both included files. The original session won't be seen from the url included file.
from: http://us2.php.net/manual/en/function.include.php#84052
hey all...i had a similar problem with my cms system.
i needed a hard path for some security aspects.
think the best way is like rob wrote. for quick an dirty coding
think this works also..:-)
<?php
$path = getcwd();
$myfile = "/test.inc.php";
/*
getcwd () points to:
/usr/srv/apache/htdocs/myworkingdir (as example)
echo ($path.$myfile);
would return...
/usr/srv/apache/htdocs/myworkingdir/test.inc.php
access outside your working directory is not allowed.
*/
includ_once ($path.$myfile);
//some code
?>
nice day
strtok
I follow Wordpress's example on this one. I go and define a root path, normally the document root, and then go define a bunch of other path's along with that (one for each of my class dirs. IE: database, users, html, etc). Often I will define the root path manually instead of relying on a server variable.
Example
if($_SERVER['SERVERNAME'] == "localhost")
{
define("ABS_PATH", "/path/to/upper/most/directory"); // Manual
}
else
{
define("ABS_PATH, dirname(__FILE__));
// This defines the path as the directory of the containing file, normally a config.php
}
// define other paths...
include(ABS_PATH."/mystuff.php");
Thanks - this is one of 2 links that com up if you google for php apache windows absolute path.
As a newbie to intermed PHP developer I didnt understand why absolute paths on apache windopws systems would be c:\xampp\htdocs (apache document root - XAMPP default) instead of /
thus if in http//localhost/myapp/subfolder1/subfolder2/myfile.php I wanted to include a file from http//localhost/myapp
I would need to specify it as:
include("c:\xampp\htdocs\myapp\includeme.php")
or
include("../../includeme.php")
AND NOT
include("/myapp/includeme.php")
I've come up with a single line of code to set at top of my every php script as to compensate:
<?php if(!$root) for($i=count(explode("/",$_SERVER["PHP_SELF"]));$i>2;$i--) $root .= "../"; ?>
By this building $root to bee "../" steps up in hierarchy from wherever the file is placed.
Whenever I want to include with an absolut path the line will be:
<?php include($root."some/include/directory/file.php"); ?>
I don't really like it, seems as an awkward way to solve it, but it seem to work whatever system php runs on and wherever the file is placed, making it system independent.
To reach files outside the web directory add some more ../ after $root, e.g. $root."../external/file.txt".