PHP 如何在 dirname (__FILE__)上升一级

我的文件夹结构如下:

mydomain.example
->Folder-A
->Folder-B

我有一个来自数据库的字符串是 ../Folder-B/image1.jpg,它指向 Folder-B中的一个图像。

Folder-A的脚本中,我使用 dirname(__FILE__)来获取文件名 在这个脚本中,我需要一个字符串来表示 'mydomain.example/Folder-B/image1.jpg

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

这显示为 mydomain.com%2FFolder-A%2F..%2FFolder-B%2Fimage1.jpg

这是一个 Facebook 共享按钮,但是无法获取正确的图像。有人知道怎么找到正确的路径吗?

我希望得到一个网址: mydomain.example%2FFolder-B%2Fimage1.jpg

132623 次浏览

For PHP < 5.3 use:

$upOne = realpath(dirname(__FILE__) . '/..');

In PHP 5.3 to 5.6 use:

$upOne = realpath(__DIR__ . '/..');

In PHP >= 7.0 use:

$upOne = dirname(__DIR__, 1);

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.

Try this

dirname(dirname( __ FILE__))

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

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 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.

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';

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

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));
dirname(__DIR__,level);
dirname(__DIR__,1);

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