>  기사  >  백엔드 개발  >  realpath를 통해 상대 경로를 절대 경로로 변환하는 PHP 코드 예제

realpath를 통해 상대 경로를 절대 경로로 변환하는 PHP 코드 예제

不言
不言원래의
2018-08-07 11:19:563171검색

이 글의 내용은 PHP에서 realpath를 통해 상대 경로를 절대 경로로 변환하는 코드 예제입니다. 필요한 친구들이 참고할 수 있기를 바랍니다.

상대 경로-> 절대 경로:

<?php
/**
 * @param string $in_rel: relative directory
 * @param string $out_abs: absolute directory
 */
define(&#39;PATH_MAX&#39;, 255);
function sub_rel2abs(string $in_rel, string &$out_abs) {
    $i_rtn = 0;  // return value
    $ss_rel = "";  // for relative path build
    $st_fpos = 0;    // front separator index
    $sv_path = [];   // pide path to array
 
    $st_pos = strpos($in_rel, DIRECTORY_SEPARATOR);
    $npos = 0;
    while ($npos != $st_pos) {
        if ($st_pos != 0) {
            array_push($sv_path, substr($in_rel, $st_fpos, $st_pos - $st_fpos));
        }
// next...
        $st_fpos = $st_pos;   // set current pos to last pos
        $st_pos++;            // from next index
        $st_pos = strpos($in_rel, DIRECTORY_SEPARATOR, $st_pos);  // next separator index
    } // while ( $npos != $st_pos )
// final separator
    array_push($sv_path, substr($in_rel, $st_fpos));
 
    $lpc = 0;    // loop count
    $i_max = count($sv_path);
    while ($lpc < $i_max && 0 === $i_rtn) {
        $ss_rel .= $sv_path[$lpc];
// relative path => relative path
        $c_abs = realpath($ss_rel);
        if ($c_abs === false) {
            $i_rtn = -1;
        } else {
            $ss_rel = $c_abs;
            $i_rtn = 0;
        }
        $lpc++;
    } // while (count($sv_path)>0)
 
// normal ending
    if (0===$i_rtn) {
        $out_abs = $ss_rel;  // set converted path
    }
    return $i_rtn;
}
 
// test
$inDir = "/Users/Mch/Code/php/Directory";
is_dir($inDir) || mkdir($inDir, 0777, true);
 
$wd = __DIR__;
chdir($inDir);
 
$out = "";
echo sub_rel2abs("../../../eclipse-workspace/blog.zip", $out).PHP_EOL;
echo $out.PHP_EOL;
 
chdir($wd);
@rmdir($inDir);
?>

output:

0
/Users/Mch/eclipse-workspace/blog.zip

여기서는 realpath를 직접 사용할 수 있는데 굳이 귀찮게 할 필요가 없나요?

추천 관련 기사:

데이터베이스에 세션을 저장하고 사용하는 방법 PHP (코드 첨부)

PHP로 URL에 액세스하는 방법은 무엇입니까? URL(코드)에 액세스하는 PHP 방법 요약

위 내용은 realpath를 통해 상대 경로를 절대 경로로 변환하는 PHP 코드 예제의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.