特定のファイルがリモート サーバーに存在するかどうかを確認する必要があります。使用is_file()
してfile_exists()
動作しません。これをすばやく簡単に行う方法はありますか?
8 に答える
そのためにCURLは必要ありません...ファイルが存在するかどうかを確認したいだけではオーバーヘッドが多すぎます...
PHP の get_headerを使用します。
$headers=get_headers($url);
次に、$result[0] に 200 OK が含まれているかどうかを確認します (ファイルが存在することを意味します)。
URL が機能するかどうかを確認する関数は次のようになります。
function UR_exists($url){
$headers=get_headers($url);
return stripos($headers[0],"200 OK")?true:false;
}
/* You can test a URL like this (sample) */
if(UR_exists("http://www.amazingjokes.com/"))
echo "This page exists";
else
echo "This page does not exist";
CURLを使用する必要があります
function does_url_exists($url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code == 200) {
$status = true;
} else {
$status = false;
}
curl_close($ch);
return $status;
}
私はちょうどこの解決策を見つけました:
if(@getimagesize($remoteImageURL)){
//image exists!
}else{
//image does not exist.
}
ソース: http://www.dreamincode.net/forums/topic/11197-checking-if-file-exists-on-remote-server/
こんにちは、2 つの異なるサーバー間のテストによると、結果は次のとおりです。
curl を使用して 10 個の .png ファイル (それぞれ約 5 mb) をチェックすると、平均で 5.7 秒かかりました。同じことに対してヘッダー チェックを使用すると、平均 7.8 秒かかりました。
したがって、私たちのテストでは、より大きなファイルをチェックする必要がある場合、curl の方がはるかに高速でした。
curl 関数は次のとおりです。
function remote_file_exists($url){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if( $httpCode == 200 ){return true;}
return false;
}
ヘッダー チェックのサンプルは次のとおりです。
function UR_exists($url){
$headers=get_headers($url);
return stripos($headers[0],"200 OK")?true:false;
}
関数 file_get_contents(); を使用できます。
if(file_get_contents('https://example.com/example.txt')) {
//File exists
}
curl でリクエストを実行し、404 ステータス コードが返されるかどうかを確認します。HEAD リクエスト メソッドを使用してリクエストを実行し、ボディなしでヘッダーのみを返すようにします。