Search code examples
phpimagefile-existsgetimagesize

php finding file with relative but not with absolute path


I wrote the following code and got the following result, but I don't understand why. I also don't know or find any solution to this online. Ideally I would like to have it work all four ways.

<?php
// Note: the file containing this script is located in
// "http://www.example.com/code.php" and the directories as
// listed below are all correct in relation to this script.

$link1 = "https://www.example.com/folder/image.png";
$link2 = "http://www.example.com/folder/image.png";
$link3 = "/folder/image.png";
$link4 = "folder/image.png";

var_dump(getimagesize($link1),file_exists($link1));
// returns bool(false) bool(false)

var_dump(getimagesize($link2),file_exists($link2));
// returns bool(false) bool(false)

var_dump(getimagesize($link3),file_exists($link3));
// returns bool(false) bool(false)

var_dump(getimagesize($link4),file_exists($link4));
// returns array(6) { [0]=> int(192) [1]=> int(250)
// [2]=> int(3) [3]=> string(24) "width="192" height="250""
// ["bits"]=> int(8) ["mime"]=> string(9) "image/png" }
// bool(true)

echo "<img src=\"$link1\" />";
echo "<img src=\"$link2\" />";
echo "<img src=\"$link3\" />";
echo "<img src=\"$link4\" />";
?>

In all four instances the image shows up properly using the <img> tag.


Solution

  • UPDATED

    $link3 is not working because file_exists() is looking for /folder/ all the way back to your root. file_exists() doesn't treat (relative) paths the same way the browser does.

    So file_exists('/folder/image.png') isn't stemming off your public directory, it's rooting all the way back in the same fashion you would expect by entering in /home/username/public_html/ or /var/www/website/ know what I mean?

    Entering in file_exists('/path/to/your/public/dir/folder/image.png'); would work.

    And file_exists() will always return false if trying to add an http:// link to your asset in question. It only resolves absolute paths in the server directory path structure.