Andy Cheeseman
Andy Cheeseman

Reputation: 293

php realpath not producing usable outcome

<?php
    $server = $_SERVER["SERVER_NAME"];
    $pathpath = realpath("../../files/uploaded_file.jpg");
    echo "You can link to the file using the following link... $server$pathpath";
?>

Unfortunately this produces the following...

www.example.com/home/fhlinux123/g/example.com/user/htdocs/ninja/base/files/1.doc

Whereas what I am after is as follows...

www.example.com/files/uploaded_file.jpg

I can't assume that the folder 'files' will always be in the same directory.

Upvotes: 1

Views: 563

Answers (1)

Mark Baker
Mark Baker

Reputation: 212522

That's because realpath returns the absolute path from the server box root, not the webserver htdocs root. You can retrieve the webserver htdocs root from $_SERVER["DOCUMENT_ROOT"], then strip that from the beginning of the result returned by realpath

Quick and dirty example:

$server = $_SERVER["SERVER_NAME"]; 
$pathpath = realpath("../../files/uploaded_file.jpg"); 
$serverPath = $_SERVER["DOCUMENT_ROOT"];
$pathpath = substr($pathpath,strlen($serverPath));

echo "You can link to the file using the following link... $server$pathpath"; 

Upvotes: 2

Related Questions