PHP function to determine if a remote file exists

Source: Internet
Author: User
function | Is there a

Determines whether a remote file exists.

<?php

/*
Function: remote_file_exists
Function: To determine whether a remote file exists
Parameters: $url _file-Remote file URL
Return: Existence returns TRUE, does not exist, or other reason returns false
*/
function remote_file_exists ($url _file) {
Detect input
$url _file = Trim ($url _file);
if (Empty ($url _file)) {return false;}
$url _arr = Parse_url ($url _file);
if (!is_array ($url _arr) | | | empty ($url _arr)) {return false;}

GET Request data
$host = $url _arr[' host '];
$path = $url _arr[' path ']. $url _arr[' query '];
$port = isset ($url _arr[' Port ')? $url _arr[' Port ']: "80";

Connecting to a server
$fp = Fsockopen ($host, $port, $err _no, $err _str, 30);
if (! $fp) {return false;}

Construct the Request protocol
$request _str = "Get". $path. " Http/1.1\r\n ";
$request _str. = "Host:". $host. " \ r \ n ";
$request _str. = "connection:close\r\n\r\n";

Send Request
Fwrite ($fp, $request _str);
$first _header = fgets ($fp, 1024);
Fclose ($FP);

To determine whether a file exists
if (Trim ($first _header) = = "") {return false;}
if (!preg_match ("/200/", $first _header)) {
return false;
}
return true;
}

Test code
$str _url = ' http://www.phpx.com/viewarticle.php?id=119617 ';
$exits = remote_file_exists ($str _url);
Echo $exists? "Exists": "Not Exists";

?>



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.