Hướng dẫn php include parent directory

In laymans terms, and practicality, I see this as an old DOS trick/thing. Whoa! What was that? DOS? Never heard of it!

".." backs you out of the current sub-directory one time to a higher folder/directory, and .. enter typed twice backs you out too 2 higher parent folders. Keep adding the ".. enter" back to back and you will soon find yourself at the top level of the directory.

As for Newbies to understand this better, consider this (in terms of the home PC or "C:\ drive" if you know what that means, rather than the web-servers/host "root directory" ). While your at it, Consider your website existing somewhere on your home PC's hard drive, buried in some folder under the C:\ drive. Lastly, you can think of it as ".." is back one directory and "/" is forward one directory/folder.

Now! If you are using the command prompt and are within the "myDocuments" folder of your PC you must back out of that folder to get closer to the higher directory "C:\" by typing the "../". If you wanted to access a file that is located in the widows directory while you are still in the myDocuments folder you would theoretically type ../windows; in reality of DOS command prompt you would simply type .., but I am setting you up for the web. The / redirects forward to another directory naturally.

Using "myDocuments" lets pretend that you created 2 folders within it called "PHP1" and "PHP2", in such we now have the folders:

  • C:\myDocuments\PHP1
  • C:\myDocuments\PHP2

In PHP1 you place a file called index.php. and in PHP2 folder you placed a file called Found.php. it now becomes:

  • C:\myDocuments\PHP1\index.php
  • C:\myDocuments\PHP2\found.php

Inside the C:\myDocuments\PHP1\index.php file you would need to edit and type something like:


The ../ is positional thus it considers your current file location "C:\myDocuments\PHP1\index.php" and is a directive telling it to back out of PHP1 directory and enter or move forward into PHP2 directory to look for the Found.php file. But does it read it? See my thoughts on trouble shooting below.

Now! suppose you have 1 folder PHP1 and a sub-folder PHP2:

  • C:\myDocuments\PHP1\PHP2

you would simply reference/code


as PHP2 exist as a sub-directory, below or within PHP1 directory.

If the above does not work it may have something to do with access/htaccess or permission to the directory or a typo. To enhance this...getting into trouble shooting...If the "found.php" file has errors/typo's within it, it will crash upon rendering at the error, such could be the reason (require/require_once) that you are experiencing the illusion that it is not changing directories or accessing the file. At last thought on the matter, you may need to instantiate your functions or references in order to use the included/require "whatever" by creating a new variable or object such as

$newObject = new nameobject("origianlThingy");

Remember, just because you are including/requiring something, sometimes means just that, it is included/required to run, but it might need to be recreated to make it active or access it. New will surely re-create an instance of it "if it is readable" and make it available within the current document while preserving the original. However you should reference the newly created variable $newObject in all instances....if its global.

To put this in perspective of some web host account; the web host is some whopping over sized hard-drive (like that on your PC) and your domain is nothing more than a folder they have assigned to you. Your folder is called the root. Inside that folder you can do anything you are allowed to do. your "one of many ways" to move between directories/folders is to use the ../ however many times to back out of your current in reference to folder position you want to find.

In my drunken state I realize that I know too much to be sane, and not enough to be insane!"

In PHP, what would be the cleanest way to get the parent directory of the current running script relative to the www root? Assume I have:

$_SERVER['SCRIPT_NAME'] == '/relative/path/to/script/index.php'

Or just:

$something_else == '/relative/path/to/script/'

And I need to get /relative/path/to/ with slashes properly inserted. What would you suggest? A one liner is preferred.

EDIT

I need to get a path relative to the www root, dirname(__FILE__) gives me an absolute path in the filesystem so that won't work. $_SERVER['SCRIPT_NAME'] on the other hand 'starts' at the www root.

asked Dec 10, 2009 at 16:08

Tatu UlmanenTatu Ulmanen

121k33 gold badges183 silver badges182 bronze badges

If your script is located in /var/www/dir/index.php then the following would return:

dirname(__FILE__); // /var/www/dir

or

dirname( dirname(__FILE__) ); // /var/www

Edit

This is a technique used in many frameworks to determine relative paths from the app_root.

File structure:

 /var/
      www/
          index.php
          subdir/
                 library.php

index.php is my dispatcher/boostrap file that all requests are routed to:

define(ROOT_PATH, dirname(__FILE__) ); // /var/www

library.php is some file located an extra directory down and I need to determine the path relative to the app root (/var/www/).

$path_current = dirname( __FILE__ ); // /var/www/subdir
$path_relative = str_replace(ROOT_PATH, '', $path_current); // /subdir

There's probably a better way to calculate the relative path then str_replace() but you get the idea.

answered Dec 10, 2009 at 16:09

Mike BMike B

31.6k13 gold badges85 silver badges111 bronze badges

5

As of PHP 5.3.0 you can use __DIR__ for this purpose.

The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__ FILE__).

See PHP Magic constants.

C:\www>php --version
PHP 5.5.6 (cli) (built: Nov 12 2013 11:33:44)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2013 Zend Technologies

C:\www>php -r "echo __DIR__;"
C:\www

answered Jan 29, 2014 at 9:08

To get the parentdir of the current script.

$parent_dir = dirname(__DIR__);

answered Apr 17, 2014 at 17:25

hanshans

1111 silver badge3 bronze badges

If I properly understood your question, supposing your running script is

/relative/path/to/script/index.php

This would give you the parent directory of your running script relative to the document www:

$parent_dir = dirname(dirname($_SERVER['SCRIPT_NAME'])) . '/';
//$parent_dir will be '/relative/path/to/'

If you want the parent directory of your running script relative to server root:

$parent_dir = dirname(dirname($_SERVER['SCRIPT_FILENAME'])) . '/';
//$parent_dir will be '/root/some/path/relative/path/to/'

answered May 9, 2011 at 19:19

Marco DemaioMarco Demaio

32.7k33 gold badges126 silver badges157 bronze badges

2

I Hope this will help you.

echo getcwd().'
'; // getcwd() will return current working directory echo dirname(getcwd(),1).'
'; echo dirname(getcwd(),2).'
'; echo dirname(getcwd(),3).'
';

Output :

C:\wamp64\www\public_html\step
C:\wamp64\www\public_html
C:\wamp64\www
C:\wamp64

answered Jun 2, 2017 at 10:38

Vignesh KMVignesh KM

1,7861 gold badge17 silver badges23 bronze badges

Fugly, but this will do it:

substr($_SERVER['SCRIPT_NAME'], 0, strpos($_SERVER['SCRIPT_NAME'],basename($_SERVER['SCRIPT_NAME'])))

Sliq

15k24 gold badges105 silver badges139 bronze badges

answered Aug 30, 2013 at 20:37

BradBrad

511 silver badge1 bronze badge

$dir = dirname($file) . DIRECTORY_SEPARATOR;

answered Dec 10, 2009 at 16:10

1

Here is what I use since I am not running > 5.2

function getCurrentOrParentDirectory($type='current')
{
    if ($type == 'current') {
        $path = dirname(__FILE__);  
    } else {
        $path = dirname(dirname(__FILE__));
    }
    $position = strrpos($path, '/') + 1;
    return substr($path, $position);
}

Double dirname with file as suggested by @mike b for the parent directory, and current directory is found by just using that syntax once.

Note this function only returns the NAME, slashes have to be added afterwards.

answered Jun 11, 2013 at 0:49

AlexAlex

9,0527 gold badges38 silver badges80 bronze badges

This is a function that I use. Created it once so I always have this functionality:

function getDir(){
    $directory = dirname(__FILE__);
    $directory = explode("/",$directory);
    $findTarget = 0;
    $targetPath = "";
    foreach($directory as $dir){
        if($findTarget == 1){
            $targetPath = "".$targetPath."/".$dir."";
        }
        if($dir == "public_html"){
            $findTarget = 1;
        }
    }
    return "http://www.".$_SERVER['SERVER_NAME']."".$targetPath."";
}

answered Feb 11, 2017 at 5:25

1

Try this. Works on both windows or linux server..

str_replace('\\','/',dirname(dirname(__FILE__)))

answered Jan 15, 2014 at 9:37

This is also a possible solution

$relative = '/relative/path/to/script/';
$absolute = __DIR__. '/../' .$relative;

answered Jun 3, 2015 at 11:12

I hope this will help

function get_directory(){
    $s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
    $protocol = substr(strtolower($_SERVER["SERVER_PROTOCOL"]), 0, strpos(strtolower($_SERVER["SERVER_PROTOCOL"]), "/")) . $s;
    $port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
return $protocol . "://" . $_SERVER['SERVER_NAME'] . dirname($_SERVER['PHP_SELF']);
}
define("ROOT_PATH", get_directory()."/" );
echo ROOT_PATH;

answered Mar 2, 2018 at 2:10

Got it myself, it's a bit kludgy but it works:

substr(dirname($_SERVER['SCRIPT_NAME']), 0, strrpos(dirname($_SERVER['SCRIPT_NAME']), '/') + 1)

So if I have /path/to/folder/index.php, this results in /path/to/.

answered Dec 10, 2009 at 17:55

Tatu UlmanenTatu Ulmanen

121k33 gold badges183 silver badges182 bronze badges

1