When you make a Picture preview, you may encounter a problem: to determine whether a remote file exists (not the same server ).
The Code is as follows:
Copy codeThe Code is as follows:
// Method 1
Function file_exists ($ url)
{
$ Ch = curl_init ();
Curl_setopt ($ ch, curlopt_url, $ url );
Curl_setopt ($ ch, curlopt_nobody, 1); // do not download
Curl_setopt ($ ch, curlopt_failonerror, 1 );
Curl_setopt ($ ch, curlopt_returntransfer, 1 );
If (curl_exec ($ ch )! = False)
Return true;
Else
Return false;
}
// Method 2
Function file_exists2 ($ url)
{
If (file_get_contents ($ url, 0, null, 0, 1 ))
Return 1;
Else
Return 0;
}
// Method 3
Function file_exists ($ url ){
$ Curl = curl_init ($ url );
// Do not retrieve data
Curl_setopt ($ curl, CURLOPT_NOBODY, true );
// Send the request
$ Result = curl_exec ($ curl );
$ Found = false;
// Failed to send the request
If ($ result! = False ){
// Check whether the http response code is 200.
}
Method 1: FALSE is returned regardless of whether the image is present;
Method 2: It is feasible in windows. In LINUX, TRUE is added no matter the image is absent;
Method 3 should be the most appropriate
In addition, the get_headers () method has an efficiency problem. We recommend that you do not use this solution.
Fsockopen:
Copy codeThe Code is as follows:
$ Url = "http://www.baidu.com/img/baidu_sylogo1.gif ";
$ Info = parse_url ($ url );
$ Fp = fsockopen ($ info ['host'], 80, $ errno, $ errstr, 30 );
Fputs ($ fp, "GET {$ info ['path']} HTTP/1.1 \ r \ n ");
Fputs ($ fp, "Host: {$ info ['host']} \ r \ n ");
Fputs ($ fp, "Connection: close \ r \ n ");
$ Headers = array ();
While (! Feof ($ fp )){
$ Line = fgets ($ fp );
If ($ line! = "\ R \ n "){
$ Headers [] = $ line;
} Else {
Break;
}
}
Echo "<pre> ";
Print_r ($ headers );
The http status code is used to determine whether a file exists. For example, if the response 302,301,404 does not exist, or if it is 200,304, the file may exist.
Fopen () method:
Copy codeThe Code is as follows:
<? Php
$ Url = 'HTTP: // www.test.com/images/test.jpg ';
If (@ fopen ($ url, 'R '))
{
Echo 'file exists ';
}
Else
{
Echo 'file Do Not Exits ';
}
?>
CURL method:
Copy codeThe Code is as follows:
<? Php
$ Url2 = 'HTTP: // www.test.com/test.jpg ';
$ Ch = curl_init ();
$ Timeout = 10;
Curl_setopt ($ ch, CURLOPT_URL, $ url2 );
Curl_setopt ($ ch, CURLOPT_HEADER, 1 );
Curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1 );
Curl_setopt ($ ch, CURLOPT_CONNECTTIMEOUT, $ timeout );
$ Contents = curl_exec ($ ch );
// Echo $ contents;
If (preg_match ("/404/", $ contents )){
Echo 'file does not exist ';
}
?>