用PHP判断远程图片(文件)是否存在

时间:2023-03-10 06:18:02
用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('http://www.baidu.com/img/baidu_sylogo1.gif');
if ($exists) {
    echo '存在';
} else {
    echo '不存在';
}

$exists = check_remote_file_exists('http://www.baidu.com/test.jpg');
if ($exists) {
    echo '存在';
} else {
    echo '不存在';
}