February 27, 2013

PHP navigating parent folders

Question by tPlummer

I can not find a good example/explanation on how to traverse directories in a PHP script.

I have to call a class from a directory that is a great-great-great…great-great grandparent of the current file.

Since the directory of the file I cam calling is closer to the root than the current php script, I just want to say “c:folderscript.php”.

when I use require_once (dirname('c:/folder/').'script.php'); I get config errors.

This is on IIS. Is the slash direction a factor?

Answer by Oldskool

Yes, the slash matters between Windows/Linux. That’s why the DIRECTORY_SEPARATOR constant was invented, they differ per build. You should be able to:

define('DS', DIRECTORY_SEPARATOR); // Alias to keep it short and readable
require_once('C:' . DS . 'folder' . DS . 'script.php');

Answer by Starx

It might be more suitable to transverse from the root directory.

Generally this is represented by a “/”

require_once("/some/script.php");

Or, define a base directory on the top of executing script and use this as the helper variable on your links. Below is an example:

define("BASEDIR", "../../../../"); // Point to the great great great grans parents just once and use them

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!