简体   繁体   中英

Checking existence of a remote file using PHP

I'm trying to find a best solution to save from performance, memory usage etc. for checking if a file exist on different domain or not. In my case, the file is an XML and the size can be between 10KB up to 10MB .

Which of these would be the best to use? If you have a better approach, I'll be happy to use it instead.

Thanks

CURL

$ch = curl_init("http://www.example.com/hello.xml");

curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// $retcode > 400 -> not found, $retcode = 200, found.
curl_close($ch);

FOPEN

$url = "http://www.example.com/hello.xml";

if (@fopen($url, "r")) {
   echo "File Exists";
} else {
   echo "Can't Connect to File";
}
$opts = array('http' =>
  array(
    'method'  => 'HEAD'
  )
);

$context  = stream_context_create($opts);

$result = fopen('http://example.com/submit.php', 'rb', false, $context);

Example taken (but shortened) from the manual

Then use stream_get_meta_data() to fetch the response headers, something like

$meta = stream_get_meta_data($result);
var_dump($meta['wrapper_data']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM