我正在开发一个小函数来接收一个url并根据它所在的位置返回一个相对路径。
如果网址在查询字符串中包含路径,则pathinfo
会返回不正确的结果。以下代码证明了这一点:
$p = 'http://localhost/demos/image_editor/dir_adjuster.php?u=http://localhost/demos/some/dir/afile.txt';
$my_path_info = pathinfo($p);
echo $p . '<br/><pre>';
print_r($my_path_info);
echo '</pre>';
该代码输出:
http://localhost/demos/image_editor/dir_adjuster.php?u=http://localhost/demos/some/dir/afile.txt
Array
(
[dirname] => http://localhost/demos/image_editor/dir_adjuster.php?u=http://localhost/demos/some/dir
[basename] => afile.txt
[extension] => txt
[filename] => afile
)
这显然是错的。任何解决方法?
答案 0 :(得分:8)
任何解决方法?
是的,这样做right;)
$url = urlencode('http://localhost/demos/some/dir/afile.txt');
$p = 'http://localhost/demos/image_editor/dir_adjuster.php?u='.$url;
对于URL,尤其是具有查询字符串的URL,parse_url()
应该更可靠地提取路径组件;之后,在其上运行pathinfo()
。