php判斷遠端圖片是否存在的方法:
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版:
$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.1rn"); fputs($fp, "Host: {$info['host']}rn"); fputs($fp, "Connection: closernrn"); $headers = array(); while(!feof($fp)) { $line = fgets($fp); if($line != "rn") { $headers[] = $line; }else { break; } } echo "<pre>"; print_r($headers);
通過http狀態碼來判斷檔案是否存在,比如,響應 302,301,404等都為不存在,如果是200,304,等可以視為檔案存在。
fopen()方法:
<?php $url = 'http://www.test.com/images/test.jpg'; if( @fopen( $url, 'r' ) ) { echo 'File Exits'; } else { echo 'File Do Not Exits'; } ?>
CURL方法:
<?php $url2 = 'http://www.test.com/test.jpg'; $ch = curl_init(); $timeout = 10; curl_setopt ($ch, CURLOPT_URL, $url2); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $contents = curl_exec($ch); //echo $contents; if (preg_match("/404/", $contents)){ echo '檔案不存在'; } ?>以上就是php怎麼判斷遠端圖片是否存在的詳細內容,更多請關注TW511.COM其它相關文章!