PHP simply implements relative path conversion to absolute path

王林
Release: 2023-02-28 16:56:01
Original
5112 people have browsed it

PHP simply implements relative path conversion to absolute path

函数介绍:

realpath() 函数返回绝对路径。该函数删除所有符号连接(比如 '/./', '/../' 以及多余的 '/'),返回绝对路径名。若失败,则返回 false。比如说文件不存在的话。

is_dir() 函数检查指定的文件是否是一个目录。如果目录存在,该函数返回 TRUE。

相关视频教程推荐:php视频教程

示例如下:

/**
 * 简单方式 start
 */
$rel_path = '../abc/qwe/';//相对路径
 
$rel_path = iconv('UTF-8', 'GBK', $rel_path);//使用iconv转换中文编码,防止乱码
if (!is_dir($rel_path)){
	mkdir($rel_path,0777,true);
}
$abs_path = realpath($rel_path) . '/';//转换成绝对路径
echo $abs_path;
echo &#39;<hr>&#39;;
 
/* 删除带盘符段的路径 */
 
$new_abs_path = str_replace(&#39;\\&#39;,&#39;/&#39;,$abs_path);
echo $new_abs_path;
echo &#39;<hr>&#39;;
 
$rdl_path =  str_ireplace($_SERVER[&#39;PHP_SELF&#39;],&#39;&#39;,str_replace(&#39;\\&#39;,&#39;/&#39;,__FILE__));
echo $rdl_path;
echo &#39;<hr>&#39;;
 
$file_abs_url = str_replace($rdl_path,"",$new_abs_path);
echo $file_abs_url;
echo &#39;<hr>&#39;;
 
/**
 * 简单方式 end
 */
Copy after login

另一种方式:

/**
 * 相对路径-转换->绝对路径
 * @param string $RelUrl 相对路径
 * @param string $PrefixUrl 前缀拼接路径
 * @param string $SuffixUrl 后缀拼接路径
 * @return string 返回值
 */
function RelToAbs($RelUrl,$PrefixUrl = &#39;&#39;,$SuffixUrl = &#39;&#39;){
	$RelUrlRep = str_replace(&#39;\\&#39;,&#39;/&#39;,$RelUrl);
	$UrlArr = explode(&#39;/&#39;,$RelUrlRep);
	$NewUrlArr = array();
	foreach ($UrlArr as $key=>$value){
		if ($value == &#39;..&#39; && !empty($NewUrlArr)){
			array_pop($NewUrlArr);
		}else if ($value != &#39;..&#39; && $value != &#39;.&#39; && $value != &#39;&#39;){ 
		// && $value != &#39;&#39; 防止多重 斜杠(/)
			$NewUrlArr[] = $value;
		}
	}
	$UrlStr = !empty($NewUrlArr) ? implode(&#39;/&#39;,$NewUrlArr) : &#39;/&#39; ;
	return $PrefixUrl.$UrlStr.$SuffixUrl;
}
$file_abs_path = RelToAbs($rel_path);
print_r($file_abs_path);
Copy after login

相关文章教程推荐:php教程

The above is the detailed content of PHP simply implements relative path conversion to absolute path. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template