Is there a better way to check whether a file exists (it is on different domain so file_exists won't work) than this?
$fp = fsockopen($fileUri, 80, $errno, $errstr, 30);
if (!$fp) {
// file exists
}
fclose($fp);
Is there a better way to check whether a file exists (it is on different domain so file_exists won't work) than this?
$fp = fsockopen($fileUri, 80, $errno, $errstr, 30);
if (!$fp) {
// file exists
}
fclose($fp);
I do like this. It work always fine:
$url = "http://www.example.com/index.php";
$header_response = get_headers($url, 1);
if ( strpos( $header_response[0], "404" ) !== false )
{
// FILE DOES NOT EXIST
}
else
{
// FILE EXISTS!!
}
see this example and the explanations
$url = "http://www.example.com/index.php";
$header_response = get_headers($url, 1);
if ( strpos( $header_response[0], "404" ) !== false )
{
// FILE DOES NOT EXIST
}
else
{
// FILE EXISTS!!
}
or
file_get_contents("http://example.com/path/to/image.gif",0,null,0,1);
set maxlength to 1
You could use curl and check the headers for a response code.
This question has a few examples you could use.
When using curl, use curl_setopt to switch CURLOPT_NOBODY to true so that it only downloads the headers and not the full file. E.g. curl_setopt($ch, CURLOPT_NOBODY, true);
From http://www.php.net/manual/en/function.fopen.php#98128
function http_file_exists($url)
{
$f=@fopen($url,"r");
if($f)
{
fclose($f);
return true;
}
return false;
}
All my tests show that it works as expected.
I would use curl to check the headers for this and validate the content type.
Something like:
function ExternalFileExists($location,$misc_content_type = false)
{
$curl = curl_init($location);
curl_setopt($curl,CURLOPT_NOBODY,true);
curl_setopt($curl,CURLOPT_HEADER,true);
curl_exec($curl);
$info = curl_getinfo($curl);
if((int)$info['http_code'] >= 200 && (int)$info['http_code'] <= 206)
{
//Response says ok.
if($misc_content_type !== false)
{
return strpos($info['content_type'],$misc_content_type);
}
return true;
}
return false;
}
And then you can use like so:
if(ExternalFileExists('http://server.com/file.avi','video'))
{
}
or if your unsure about the extension then like so:
if(ExternalFileExists('http://server.com/file.ext'))
{
}
what about
<?php
$a = file_get_contents('http://mydomain.com/test.html');
if ($a) echo('exists'); else echo('not exists');