PHP determines if a remote picture or file or URL exists-180

Source: Internet
Author: User

I usually use curl to determine whether a remote picture or file exists:

/**
* @link http://www.phpddt.com
*/
function Url_exists ($url) {
$ch = Curl_init ();
curl_setopt ($ch, Curlopt_url, $url);
Do not download
curl_setopt ($ch, curlopt_nobody, 1);
Set timeout
curl_setopt ($ch, Curlopt_connecttimeout, 3);
curl_setopt ($ch, Curlopt_timeout, 3);
Curl_exec ($ch);
$http _code = Curl_getinfo ($ch, Curlinfo_http_code);
if ($http _code = = 200) {
return true;
}
return false;
}


There are, of course, many other ways, more or less limited and flawed, such as:
(1) using the fopen () function, it should be in the state of Allow_url_open open, otherwise it will be an error.

$url = ' Http://www.phpddt.com/img/qrcode_for_phpddt.JPG ';
if (@fopen ($url, ' R ')) {
echo ' file exists ';
} else {
Echo ' file does not exist ';
}


(2) Get_headers get the server response to an HTTP request sent by all headers, less efficient, you can test under.

$url = ' Http://www.phpddt.com/img/qrcode_for_phpddt.JPG ';

Stream_context_set_default (
Array
' http ' = = Array (
' Timeout ' = 1,
)
)
);

$headers = Get_headers ($url);

if (Preg_match ('/200/', $headers [0])) {
echo ' file exists ';
} else {
Echo ' file does not exist ';
}


(3) file_get_contents () function

$opts = Array (
' HTTP ' =>array (
' Timeout ' =>3,
)
);
$context = Stream_context_create ($opts);
$resource = @file_get_contents (' Http://www.phpddt.com/img/qrcode_for_phpddt.JPG ', false, $context);

if ($resource) {
echo ' file exists ';
} else {
Echo ' file does not exist ';
}

This article is from the "Yanzi" blog, make sure to keep this source http://daddysgirl.blog.51cto.com/1598612/1887742

PHP determines if a remote picture or file or URL exists-180

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.