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

孤街浪徒 提交于 2019-11-28 03:32:39

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

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

Abhishek

Try this

dirname(dirname( __ FILE__))

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

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.

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

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

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'>");
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!