php realpath 不产生可用的结果

发布于 2024-09-09 02:17:50 字数 471 浏览 1 评论 0原文

<?php
    $server = $_SERVER["SERVER_NAME"];
    $pathpath = realpath("../../files/uploaded_file.jpg");
    echo "You can link to the file using the following link... $server$pathpath";
?>

不幸的是,这会产生以下结果...

www.example.com/home/fhlinux123/g/example.com/user/htdocs/ninja/base/files/1.doc

而我所追求的结果如下...

www.example.com/files/uploaded_file.jpg

我不能假设文件夹“文件”将始终位于同一目录中。

<?php
    $server = $_SERVER["SERVER_NAME"];
    $pathpath = realpath("../../files/uploaded_file.jpg");
    echo "You can link to the file using the following link... $server$pathpath";
?>

Unfortunately this produces the following...

www.example.com/home/fhlinux123/g/example.com/user/htdocs/ninja/base/files/1.doc

Whereas what I am after is as follows...

www.example.com/files/uploaded_file.jpg

I can't assume that the folder 'files' will always be in the same directory.

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

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

发布评论

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

评论(1

蓝天白云 2024-09-16 02:17:50

这是因为 realpath 返回服务器框根的绝对路径,而不是 Web 服务器 htdocs 根的绝对路径。
您可以从 $_SERVER["DOCUMENT_ROOT"] 检索网络服务器 htdocs 根目录,然后从 realpath 返回的结果的开头将其删除

简单而肮脏的示例:

$server = $_SERVER["SERVER_NAME"]; 
$pathpath = realpath("../../files/uploaded_file.jpg"); 
$serverPath = $_SERVER["DOCUMENT_ROOT"];
$pathpath = substr($pathpath,strlen($serverPath));

echo "You can link to the file using the following link... $server$pathpath"; 

That's because realpath returns the absolute path from the server box root, not the webserver htdocs root.
You can retrieve the webserver htdocs root from $_SERVER["DOCUMENT_ROOT"], then strip that from the beginning of the result returned by realpath

Quick and dirty example:

$server = $_SERVER["SERVER_NAME"]; 
$pathpath = realpath("../../files/uploaded_file.jpg"); 
$serverPath = $_SERVER["DOCUMENT_ROOT"];
$pathpath = substr($pathpath,strlen($serverPath));

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