PHP判斷遠端檔案是否存在

2021-09-07 06:52:22 字數 1628 閱讀 3247

<?php

/* 函式:remote_file_exists

功能:判斷遠端檔案是否存在

引數: $url_file -遠端檔案url

返回:存在返回true,不存在或者其他原因返回false

*/function remote_file_exists($url_file)

$url_arr = parse_url($url_file);

if (!is_array($url_arr) || empty($url_arr))

//獲取請求資料

$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)

//構造請求協議

//傳送請求

fwrite($fp,$request_str);

$first_header = fgets($fp, 1024);

fclose($fp);

//判斷檔案是否存在

if (trim($first_header) == "")

if (!preg_match("/200/", $first_header))

return true;

}?>

函式描述及例子

<?

//測試**

$str_url = '';

$exits = remote_file_exists($str_url);

echo $exists ? "exists" : "not exists";

?>

方法一(需要開啟allow_url_fopen):

<?php

$url = "";

$fileexists = @file_get_contents($url, null, null, -1, 1) ? true : false;

echo $fileexists; //返回1,就說明檔案存在。

?>

方法二(需要伺服器支援curl元件):

<?php

function check_remote_file_exists($url)

} curl_close($curl);

return $found;

}$url = "";

echo check_remote_file_exists($url); // 返回1,說明存在。

?>

判斷遠端檔案是否存在的PHP函式

可以利用get headers 函式判斷遠端檔案是否存在 get headers函式說明 取得伺服器響應乙個 http 請求所傳送的所有標頭 array get headers string url int format get headers 返回乙個陣列,包含有伺服器響應乙個 http 請求所傳...

php 判斷檔案是否存在

sha1 file file 語法 sha1 file file,raw 引數 file 必需。規定要計算的檔案。raw 可選。布林值,規定十六進製制或二進位制輸出格式 true 原始 16 字元二進位制格式 false 預設。32 字元十六進製制數 版本 php 4.2.0 說明 sha1 fil...

curl判斷遠端檔案是否存在

在專案中遇到了要判斷乙個是否存在,遠端伺服器上 首先想到了用file get contents 這個函式,可以打到效果,但是發現,會很慢,一直在請求,產看資料發現,file get contents fopen 每次請求都會重新做dns查詢,並不對 dns資訊進行快取,curl函式則不一樣 fope...