Reputation: 36839
How to check if a file exist on an External Server? I have a url "http://logs.com/logs/log.csv" and I have an script on another server to check if this file exists. I tried
$handle = fopen("http://logs.com/logs/log.csv","r");
if($handle === true){
return true;
}else{
return false;
}
and
if(file_exists("http://logs.com/logs/log.csv")){
return true;
}else{
return false;
}
These methos just do not work
Upvotes: 9
Views: 19007
Reputation: 23
Requesting only headers will be much faster. I use this:
function isItAlive($url){
stream_context_set_default(
array(
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
],
'http' => array(
'method' => 'HEAD'
)
)
);
$headers = @get_headers($url);
$status = substr($headers[0], 9, 3);
return ($status >= 200 && $status < 300 )?true:false;
}
Upvotes: 0
Reputation: 714
function checkExternalFile($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$retCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $retCode;
}
$fileExists = checkExternalFile("http://example.com/your/url/here.jpg");
// $fileExists > 400 = not found
// $fileExists = 200 = found.
Upvotes: 14
Reputation: 382696
This should work:
$contents = file_get_contents("http://logs.com/logs/log.csv");
if (strlen($contents))
{
return true; // yes it does exist
}
else
{
return false; // oops
}
Note: This assumes file is not empty
Upvotes: 2
Reputation: 11859
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 4file dir);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
$data = curl_exec($ch);
curl_close($ch);
preg_match_all("/HTTP\/1\.[1|0]\s(\d{3})/",$data,$matches); //check for HTTP headers
$code = end($matches[1]);
if(!$data)
{
echo "file could not be found";
}
else
{
if($code == 200)
{
echo "file found";
}
elseif($code == 404)
{
echo "file not found";
}
}
?>
Upvotes: 1
Reputation: 70819
Make sure error reporting is on.
Use if($handle)
Check allow_url_fopen is true.
If none of this works, use this method on the file_exists page.
Upvotes: 3