用php代码检测一个文件是否可以下载,网上没有找到合适的代码,自己实现了一个还挺好用的,分享给有需要的朋友。
基本原理:使用http的HEAD方法,检测报文的头里httpcode是否为200。
1 public static function curlDetectFileExists($url) 2 { 3 $ch = curl_init($url); 4 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 5 curl_setopt($ch, CURLOPT_HEADER, true); 6 curl_setopt($ch, CURLOPT_NOBODY, true); 7 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); 8 $result = curl_exec($ch); 9 $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 10 $httpInfo = curl_getinfo($ch); 11 $httpInfoString = json_encode($httpInfo); 12 $errMsg = null; 13 $errCode = null; 14 if ($httpCode !== 200) 15 { 16 $errMsg = $httpInfoString; 17 $errCode = false; 18 } 19 else 20 { 21 $errMsg = "OK"; 22 $errCode = true; 23 } 24 $obj = array( 25 'code' => $errCode, 26 'HttpCode' => $httpCode, 27 'HttpInfo' => $httpInfoString, 28 ); 29 return $obj; 30 }