PHP - Convert File system path to URL

Solution 1:

More accurate way (including host port) would be to use this

function path2url($file, $Protocol='http://') {
    return $Protocol.$_SERVER['HTTP_HOST'].str_replace($_SERVER['DOCUMENT_ROOT'], '', $file);
}

Solution 2:

Assume the directory is /path/to/root/document_root/user/file and the address is site.com/user/file

The first function I am showing will get the current file's name relative to the World Wide Web Address.

$path = $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'];

and would result in:

site.com/user/file

The second function strips the given path of the document root.

$path = str_replace($_SERVER['DOCUMENT_ROOT'], '', $path)

Given I passed in /path/to/root/document_root/user/file, I would get

/user/file

Solution 3:

IMHO such automation is really error prone. You're far better off using some explicit path helpers (eg. one for uploads, one for user pics, etc) or just encapsulate for example an uploaded file with a class.

// Some "pseudo code"
$file = UploadedFile::copy($_FILES['foo']);
$file->getPath(); // /var/www/example.org/uploads/foo.ext
$file->getUri();  // http://example.org/uploads/foo.ext

Solution 4:

Make it easy on yourself and just define the correct locations for both the filesystem and web folders and prepend the image filename with them.

Somewhere, you'd declare:

define('PATH_IMAGES_FS', '/var/www/example.com/uploads/');
define('PATH_IMAGES_WEB', 'uploads/');

Then you can just swap between paths depending on your need:

$image_file = 'myphoto.jpg';

$file = PATH_IMAGES_FS.$image_file;
//-- stores: /var/www/example.com/uploads/myphoto.jpg

print PATH_IMAGES_WEB.$image_file;
//-- prints: uploads/myphoto.jpg

Solution 5:

Try this:

$imgUrl = str_replace($_SERVER['DOCUMENT_ROOT'], '', $imgPath)