PHP: How to get URL of relative file

眉间皱痕 提交于 2020-01-05 13:09:31

问题


Does PHP have a native function that returns the full URL of a file you declare with a relative path? I need to get: "http://www.domain.com/projects/test/img/share.jpg" from "img/share.jpg" So far I've tried the following:

realpath('img/share.jpg');
// Returns "/home/user/www.domain.com/projects/test/img/share.jpg"

I also tried:

dirname(__FILE__)
// Returns "/home/user/www.domain.com/projects/test"

And this answer states that the following can be tampered with client-side:

"http://'.$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI].'img/share.jpg"

plus, my path will vary depending on whether I'm accessing from /test/index.php or just test/ without index.php and I don't want to hard-code whether it's http or https.

Does anybody have a solution for this? I'll be sending these files to another person who will upload to their server, so the folder structure will not match "/home/user/www.domain.com/"


回答1:


echo preg_replace(preg_quote($_SERVER['DOCUMENT_ROOT']), 'http://www.example.com/', realpath('img/share.jpg'), 1);

Docs: preg_replace and preg_quote.

The arguments of preg_replace:

  • preg_quote($_SERVER['DOCUMENT_ROOT']) - Takes the document root (e.g., /home/user/www.domain.com/) and makes it a regular expression for use with preg_replace.
  • 'http://www.example.com/' - the string to replace the regex match with.
  • realpath('img/share.jpg') - the string for the file path including the document root.
  • 1 - the number of times to replace regex matches.



回答2:


How about

echo preg_replace("'". preg_quote($_SERVER['DOCUMENT_ROOT']) ."'",'http://www.example.com/', realpath('img/share.jpg'), 1);


来源:https://stackoverflow.com/questions/27390829/php-how-to-get-url-of-relative-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!