## PHP判斷遠程文件是否存在
~~~
<?php
/*
函數:remote_file_exists
功能:判斷遠程文件是否存在
參數: $url_file -遠程文件URL
返回:存在返回true,不存在或者其他原因返回false
*/
function remote_file_exists($url_file){
//檢測輸入
$url_file = trim($url_file);
if (empty($url_file)) { return false; }
$url_arr = parse_url($url_file);
if (!is_array($url_arr) || empty($url_arr)){return false; }
//獲取請求數據
$host = $url_arr['host'];
$path = $url_arr['path'] ."?".$url_arr['query'];
$port = isset($url_arr['port']) ?$url_arr['port'] : "80";
//連接服務器
$fp = fsockopen($host, $port, $err_no, $err_str,30);
if (!$fp){ return false; }
//構造請求協議
$request_str = "GET ".$path."HTTP/1.1";
$request_str .= "Host:".$host."";
$request_str .= "Connection:Close";
//發送請求
fwrite($fp,$request_str);
$first_header = fgets($fp, 1024);
fclose($fp);
//判斷文件是否存在
if (trim($first_header) == ""){ return false;}
if (!preg_match("/200/", $first_header)){
return false;
}
return true;
}
?>
~~~
> 函數描述及例子
~~~
<?
//測試代碼
$str_url = 'http://www.8thzone.cn/case.html';
$exits = remote_file_exists($str_url);
echo $exists ? "Exists" : "Not exists";
?>
~~~
### 方法一(需要開啟allow_url_fopen):
~~~
<?php
$url = "http://cn.wordpress.org/wordpress-3.3.1-zh_CN.zip";
$fileExists = @file_get_contents($url, null, null, -1, 1) ? true : false;
echo $fileExists; //返回1,就說明文件存在。
?>
~~~
### 方法二(需要服務器支持Curl組件):
~~~
<?php
function check_remote_file_exists($url) {
$curl = curl_init($url); // 不取回數據
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET'); // 發送請求
$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;
}
$url = "http://cn.wordpress.org/wordpress-3.3.1-zh_CN.zip";
echo check_remote_file_exists($url); // 返回1,說明存在。
?>
~~~
- 常用函數
- 簡單的php生成靜態html代碼
- PHP寫文件函數
- PHP生成GUID的函數
- PHP常用正則表達式匯總
- php字符串壓縮
- PHP無限分組
- PHP簡單 對象(object) 與 數組(array) 的轉換
- PHP數組常用函數
- PHP調式測試函數
- PHP常用字符串的操作函數
- mysql 常用內置函數
- PHP通用請求函數CURL封裝
- 裁剪圖片PHP代碼
- PDO操作MYSQL封裝類
- 10個實用的PHP代碼片段
- 獲取訪問者IP地址
- PHP實現發紅包程序
- PHP把文本轉換成圖片
- curl重寫php file_get_contents
- PHP生成一個隨機字符串
- PHP讀文件和寫文件
- PHP根據key 給二維數組分組
- php中curl模擬post提交多維數組
- 33個超級有用必須要收藏的PHP代碼樣例
- PHP防XSS 防SQL注入的代碼
- php常用數組array函數實例總結
- 用PHP遍歷目錄下的全部文件
- GBK2UTF8