Summary of PHP instance determination of remote/network files

Source: Internet
Author: User
Tags curl response code

Method 1:

The code is as follows: Copy code

<? Php
$ Url = http://www.111cn.net ";
$ FileExists = @ file_get_contents ($ url, null, null,-1, 1 )? True: false;
Echo $ fileExists; // If 1 is returned, the file exists.
?>

Method 2:

The code is as follows: Copy code

// Php determines whether a remote file exists
Function url_exists ($ url ){
$ Handle = curl_init ($ url );
If (false ===$ handle ){
Return false;
    }
Curl_setopt ($ handle, CURLOPT_HEADER, false );
Curl_setopt ($ handle, CURLOPT_FAILONERROR, true );
Curl_setopt ($ handle, CURLOPT_NOBODY, true );
Curl_setopt ($ handle, CURLOPT_RETURNTRANSFER, false );
$ Connectable = curl_exec ($ handle );
 
Curl_close ($ handle );
Return $ connectable;
}


Method 3

The code is as follows: Copy code


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

The code is as follows: Copy code


$ Url = "http://www.111cn.net ";
 
$ Info = parse_url ($ url );
$ Fp = fsockopen ($ info ['host'], 80, $ errno, $ errstr, 30 );
Fputs ($ fp, "GET {$ info ['path']} HTTP/1.1rn ");
Fputs ($ fp, "Host: {$ info ['host']} rn ");
Fputs ($ fp, "Connection: closernrn ");
$ Headers = array ();
While (! Feof ($ fp )){
$ Line = fgets ($ fp );
If ($ line! = "Rn "){
$ Headers [] = $ line;
} Else {
Break;
    }
    }
 
Echo "<pre> ";
Print_r ($ headers );

Method 4

The code is as follows: Copy code

<? Php
$ Url = 'http: // www.111cn.net ';
 
If (@ fopen ($ url, 'r '))
    {
Echo 'file exists ';
    }
Else
    {
Echo 'file Do Not Exits ';
    }
?>

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.