简体   繁体   中英

PHP file_exists else

When I use to following PHP code;

<?php if (file_exists("/foto/Maurice.jpg"))
{
echo "<center><img src='/foto/Maurice.jpg'/></center>";
}
else {
echo "<center><img src='/afbeeldingen/kaars1.png'/></center>"; 
?>

My browser always shows kaars1.png instead of Maurice.jpg I also tried !file_exists but then it doesn't show kaars1.png , when Maurice.jpg doesn't exist. Is there a simpel way to fix this?

file_exists is only for files on your server's (local) filesystem. You need to actually try to request the URL and see if it exists or not.

You can use cURL to do this.

$handle = curl_init('https://picathartes.com/foto/Maurice.jpg');
curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($handle, CURLOPT_NOBODY, TRUE);
$response = curl_exec($handle);

// Check for 404 (file not found).
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if($httpCode == 404) {
    echo "<center><img src='https://picathartes.com/afbeeldingen/kaars1.png'/></center>"; 
}   
else{
    echo "<center><img src='https://picathartes.com/foto/Maurice.jpg'/></center>";
} 
curl_close($handle);

(Code from this question: https://stackoverflow.com/a/408416 )

This is an answer to your second question

The correct solution depends upon your actual directory structure and the location of the script file in relation to the actual folder and file you are looking for, but to start finding a solution the / in "/foto/Maurice.jpg" say go back to the root directory and look for a directory called /foto

So if this folder is under your DocumentRoot try using

if (file_exists("foto/Maurice.jpg"))

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