Reputation: 28462
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/"
Upvotes: 2
Views: 5074
Reputation: 18891
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.Upvotes: 3
Reputation: 3185
How about
echo preg_replace("'". preg_quote($_SERVER['DOCUMENT_ROOT']) ."'",'http://www.example.com/', realpath('img/share.jpg'), 1);
Upvotes: 1