简体   繁体   中英

Displaying a links absolute location

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

Ie 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.

Do a:

var_dump($_SERVER);

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

<a href="<?php echo 'http://'.$_SERVER['HTTP_HOST'] . '/files/uploaded_file.jpg'; ?>">Your file</a>

Assuming that the page that contains the example code is two directories deep from the root of the site eg

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

then you could do this:

<a href='http://<?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 eg

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://<?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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM