2

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/"

Community
  • 1
  • 1
M -
  • 26,908
  • 11
  • 49
  • 81

2 Answers2

3
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.
Mooseman
  • 18,763
  • 14
  • 70
  • 93
  • Thanks! But I'd like to avoid this because I'm sending the files to another person who will upload to their own server, and I doubt that their folder structure will start with `/home/user/` – M - Dec 09 '14 at 23:38
  • Unfortunately, preq_replace kept giving me the following error: `Unknown modifier 'n' in...` After some digging, this is the code that worked: `echo str_replace($_SERVER['DOCUMENT_ROOT'], 'http://www.domain.com', realpath('img/share.jpg'));` Thanks for the push in the right direction! – M - Dec 10 '14 at 00:57
1

How about

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