How PHP can tell if a remote file exists

Source: Internet
Author: User
Tags file url

<?php

/*
Function: remote_file_exists
Function: Determine whether a remote file exists
Parameters: $url _file-Remote file URL
Return: Presence returns true, no presence or other reason returned false
*/
function remote_file_exists ($url _file) {
Detection 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);

Determine if a file exists
if (Trim ($first _header) = = "") {return false;}
if (!preg_match ("/2002881064151/", $first _header)) {
return false;
}
return true;
}

?>


function description and examples

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

How PHP can tell if a remote file 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.