1. 当前位置:
  2. 首页
  3. »
  4. 随笔
  5. »
  6. PHP判断远程图片是否存在

PHP判断远程图片是否存在

零分 3,065

PHP判断远程图片是否存在,如果不存在则调用默认的图片,存在使用远程图片,有时候是蛮有用处的。

PHP 代码:

function check_remote_file_exists($url) {
    $curl = curl_init($url);
    // 不取回数据
    curl_setopt($curl, CURLOPT_NOBODY, true);
    // 发送请求
    $result = curl_exec($curl);
    $found = false;
    // 如果请求没有发送失败
    if ($result !== false) {
        // 再检查http响应码是否为200
        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        if ($statusCode == 200) {
            $found = true;
        }
    }
    curl_close($curl);


    return $found;
}

判断代码:

$exists = check_remote_file_exists($img);
if (!$exists) {
    echo $img.' 这张图片不存在<br><br>';
        }else{
    echo '<img src="'.$img.'"><br><br>'     ;
        }

例子:

<?php
@header('Content-type: text/html;charset=UTF-8');
function check_remote_file_exists($url) {
    $curl = curl_init($url);
    // 不取回数据
    curl_setopt($curl, CURLOPT_NOBODY, true);
    // 发送请求
    $result = curl_exec($curl);
    $found = false;
    // 如果请求没有发送失败
    if ($result !== false) {
        // 再检查http响应码是否为200
        $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        if ($statusCode == 200) {
            $found = true;
        }
    }
    curl_close($curl);


    return $found;
}
?>
<?php
$imgarr=array(
"//img.32xp.com/photo_20150816221103.jpg",
"//img.32xp.com/photo_201508162211030.jpg"
);
foreach($imgarr as $img){
    $exists = check_remote_file_exists($img);
if (!$exists) {
    echo $img.' 这张图片不存在<br><br>';
        }else{
    echo '<img src="'.$img.'"><br><br>'     ;
        }
}
?>

其实,这个应该也可以判断其他文件类型是否存在

头像
支持作者
联系微信二维码
0%