Home>Article>Backend Development> How to determine whether a remote image exists in php
php method to determine whether a remote image exists:
function file_exists($url) { $curl = curl_init($url); // 不取回数据 curl_setopt($curl, CURLOPT_NOBODY, true); // 发送请求 $result = curl_exec($curl); $found = false; // 如果请求没有发送失败 if ($result !== false) { // 再检查http响应码是否为200 }
fsockopen version:
$url = "http://www.baidu.com/img/baidu_sylogo1.gif"; $info = parse_url($url); $fp = fsockopen($info['host'], 80,$errno, $errstr, 30); fputs($fp,"GET {$info['path']} HTTP/1.1\r\n"); fputs($fp, "Host: {$info['host']}\r\n"); fputs($fp, "Connection: close\r\n\r\n"); $headers = array(); while(!feof($fp)) { $line = fgets($fp); if($line != "\r\n") { $headers[] = $line; }else { break; } } echo ""; print_r($headers);Use http status code to determine whether the file exists , for example, responses 302, 301, 404, etc. all mean that the file does not exist. If it is 200, 304, etc., it can be regarded as the file exists.
fopen() method:
CURL method:
Recommendation:php server
The above is the detailed content of How to determine whether a remote image exists in php. For more information, please follow other related articles on the PHP Chinese website!