分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 软件开发

PHP 相对路径转换为绝对路径 realpath

发布时间:2023-09-06 02:08责任编辑:彭小芳关键词:PHP

* 相对路径 -> 绝对路径 realpath

<?php/** * @param string $in_rel: relative directory * @param string $out_abs: absolute directory */define(‘PATH_MAX‘, 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 = []; ??// divide 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就可以了,为什么多此一举?

*  绝对路径 -> 相对路径

   ... [TO BE DONE]

PHP 相对路径转换为绝对路径 realpath

原文地址:https://www.cnblogs.com/mingzhanghui/p/9434337.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved