PHP pathinfo 被查询字符串中的 url 欺骗了,有什么解决方法吗?

发布于 2024-09-05 06:17:16 字数 721 浏览 3 评论 0原文

我正在开发一个小函数来接收 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
)

这显然是错误的。有什么解决办法吗?

I am working on a small function to take in a url and return a relative path based on where it resides itself.

If the url contains a path in the query string, pathinfo returns incorrect results. This is demonstrated by the code below:

$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>';

That code outputs:

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
)

Which obviously is wrong. Any workaround?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

云归处 2024-09-12 06:17:16

有什么解决办法吗?

是的,这样做正确;)

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

Any workaround?

Yeah, doing it right ;)

$url = urlencode('http://localhost/demos/some/dir/afile.txt');
$p = 'http://localhost/demos/image_editor/dir_adjuster.php?u='.$url;

and for URLs, especially those with query strings, parse_url() should be more reliable to extract the path component; After that, run the pathinfo() on it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文