views:

46

answers:

5

Is there any way I can display a links location absolutely when I only reference it relatively.

I.e. A file is relatively referenced like...

<a href='../../files/uploaded_file.jpg'>Your Uploaded File</a>

But I would also like to display some text saying...

You can link to your file via www.example.com/files/uploaded_file.jpg

The catch being I dont want to explicity state what the domain is, as the script will be used on a variety of different domains without the need to edit the script.

Basically I want to somehow echo the text you see in the status bar of firefox when you hover over a link.

A: 

this first thingie google spit out...: http://www.web-max.ca/PHP/misc_24.php

this one is even shorter: http://nashruddin.com/PHP_Script_for_Converting_Relative_to_Absolute_URL

santa
+1  A: 

Do a:

var_dump($_SERVER);

and you will see which one you can count on as being the domain url.

Cups
A: 

If a link is relative, you can prefix it with the current host + path in PHP. You would have to format the path to resolve the relative url parts like /../, a simple loop would do this.

Peter Kruithof
+1  A: 
<a href="<?php echo 'http://'.$_SERVER['HTTP_HOST'] . '/files/uploaded_file.jpg'; ?>">Your file</a>
Kieran Allen
+1  A: 

Assuming that the page that contains the example code is two directories deep from the root of the site e.g.

http://www.example.com/one/two/example-page.php

then you could do this:

<a href='http://&lt;?php echo htmlentities($_SERVER['SERVER_NAME'], ENT_QUOTES)?>/files/uploaded_file.jpg'>Your Uploaded File</a>

If that assumption is wrong and the files are stored in a directory that is at least one directory deeper than the root e.g.

http: //www.example.com/content/files/uploaded_file.jpg

then you have to a little more work to get the absolute url.

<?php
$FilesystemPath = str_replace("\\", "/", realpath(dirname(__FILE__) . "/../../files/")) . "/uploaded_file.jpg";
$DocRoot = $_SERVER['DOCUMENT_ROOT'];
$Uri = str_replace($DocRoot, '', $FilesystemPath);
?>
<a href='http://&lt;?php echo htmlentities($_SERVER['SERVER_NAME'] . $Uri, ENT_QUOTES)?>'>Your Uploaded File</a>

This example assumes that you know that the files directory is in the directory that is two directories up from the page's directory.

All of these example assume a one to one mapping of directories on the file system and there's no url rewriting going on. Also I'm assuming you are using just plain http and not https. If you want to present links in the same protocol as what the page is served under then that's a separate question.

emurano