繁体   English   中英

PHP file_exists else

[英]PHP file_exists else

当我用来跟随PHP代码时;

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

我的浏览器总是显示kaars1.png而不是Maurice.jpg我也尝试了!file_exists但是当Maurice.jpg不存在时它没有显示kaars1.png 有没有简单的方法来解决这个问题?

file_exists仅适用于服务器(本地)文件系统上的文件。 您需要实际尝试请求URL并查看它是否存在。

您可以使用cURL执行此操作。

$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);

(此问题的代码: https//stackoverflow.com/a/408416

这是你第二个问题的答案

正确的解决方案取决于你的实际的目录结构和脚本文件相对于实际的文件夹位置和文件你正在寻找,但开始找到解决办法的/"/foto/Maurice.jpg"说回去根目录并查找名为/foto的目录

因此,如果此文件夹位于DocumentRoot下,请尝试使用

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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