4

我正在研究一个小函数来接收一个 url 并根据它所在的位置返回一个相对路径。

如果 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
)

这显然是错误的。任何解决方法?

4

1 回答 1

10

任何解决方法?

是的,做了;)

$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()它。

于 2010-06-10T10:17:39.837 回答