[php] php how to go one level up on dirname(__FILE__)

I have a folder structure as follows:

mydomain.com
  ->Folder-A
  ->Folder-B

I have a string from Database that is '../Folder-B/image1.jpg', which points to an image in Folder-B.

Inside a script in Folder-A, I am using dirname(FILE) to fetch the filename and I get mydomain.com/Folder-A. Inside this script, I need to get a string that says 'mydomain.com/Folder-B/image1.jpg. I tried

$path=dirname(__FILE__).'/'.'../Folder-B/image1.jpg';

This shows up as mydomain.com%2FFolder-A%2F..%2FFolder-B%2Fimage1.jpg

This is for a facebook share button, and this fails to fetch the correct image. Anyone know how to get the path correctly?

Edit: I hope to get a url >>>mydomain.com%2FFolder-B%2Fimage1.jpg

This question is related to php dirname

The answer is


Try this

dirname(dirname( __ FILE__))

Edit: removed "./" because it isn't correct syntax. Without it, it works perfectly.


To Whom, deailing with share hosting environment and still chance to have Current PHP less than 7.0 Who does not have dirname( __FILE__, 2 ); it is possible to use following.

function dirname_safe($path, $level = 0){
    $dir = explode(DIRECTORY_SEPARATOR, $path);
    $level = $level * -1;
    if($level == 0) $level = count($dir);
    array_splice($dir, $level);
    return implode($dir, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
}

print_r(dirname_safe(__DIR__, 2));

If you happen to have php 7.0+ you could use levels.

dirname( __FILE__, 2 ) with the second parameter you can define the amount of levels you want to go back.

http://php.net/manual/en/function.dirname.php


You can use realpath to remove unnessesary part:

// One level up
echo str_replace(realpath(dirname(__FILE__) . '/..'), '', realpath(dirname(__FILE__)));

// Two levels etc.
echo str_replace(realpath(dirname(__FILE__) . '/../..'), '', realpath(dirname(__FILE__)));

On windows also replace \ with / if need that in URL.


dirname(__DIR__,level);
dirname(__DIR__,1);

level is how many times will you go back to the folder


One level up, I have used:

str_replace(basename(__DIR__) . '/' . basename(__FILE__), '', realpath(__FILE__)) . '/required.php';

or for php < 5.3:

str_replace(basename(dirname(__FILE__)) . '/' . basename(__FILE__), '', realpath(__FILE__)) . '/required.php';

I use this, if there is an absolute path (this is an example):

$img = imagecreatefromjpeg($_SERVER['DOCUMENT_ROOT']."/Folder-B/image1.jpg");

if there is a picture to show, this is enough:

echo("<img src='/Folder-B/image1.jpg'>");

You could use PHP's dirname function. <?php echo dirname(__DIR__); ?>. That will give you the name of the parent directory of __DIR__, which stores the current directory.