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

后端 未结 9 2047
暗喜
暗喜 2020-11-30 21:52

I have a folder structure as follows:

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

I have a string from Database that is \'../Folder-B/imag

相关标签:
9条回答
  • 2020-11-30 22:17

    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

    0 讨论(0)
  • 2020-11-30 22:20

    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));
    
    0 讨论(0)
  • 2020-11-30 22:26

    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'>");
    
    0 讨论(0)
  • 2020-11-30 22:27
    dirname(__DIR__,level);
    dirname(__DIR__,1);
    

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

    0 讨论(0)
  • 2020-11-30 22:28

    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.

    0 讨论(0)
  • 2020-11-30 22:29

    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);
    
    0 讨论(0)
提交回复
热议问题