Mohammed H
Mohammed H

Reputation: 7048

How to check a url exist or not in php

I want to check the url http://example.com/file.txt exist or not in php. How can I do it?

Upvotes: 4

Views: 7442

Answers (5)

Vinay Sikarwar
Vinay Sikarwar

Reputation: 456

I am agree with the response, I got success by doing this

$url = "http://example.com/file.txt";       
if(! @(file_get_contents($url))){
    return false;
}
$content = file_get_contents($url);
return $content;

You can follow the code to check the file exist at location or not.

Upvotes: 0

Landon
Landon

Reputation: 4108

if(! @ file_get_contents('http://www.domain.com/file.txt')){
  echo 'path doesn't exist';
}

This is the easiest way to do it. If you are unfamiliar with the @, that will instruct the function to return false if it would have otherwise thrown an error

Upvotes: 4

Soojoo
Soojoo

Reputation: 2156

$filename="http://example.com/file.txt";    

if (file_exists($filename)) {
   echo "The file $filename exists";
} else {
   echo "The file $filename does not exist";
} 

OR

if (fopen($filename, "r"))
{
   echo "File Exists"; 
}
else
{
   echo "Can't Connect to File";
}

Upvotes: 0

Amit Garg
Amit Garg

Reputation: 3907

Try this function on Ping site and return result in PHP.

function urlExists($url=NULL)  
    {  
        if($url == NULL) return false;  
        $ch = curl_init($url);  
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);  
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
        $data = curl_exec($ch);  
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
        curl_close($ch);  
        if($httpcode>=200 && $httpcode<300){  
            return true;  
        } else {  
            return false;  
        }  
    }

Upvotes: 0

doublesharp
doublesharp

Reputation: 27609

The would use the PHP curl extension:

$ch = curl_init();                                  // set up curl
curl_setopt( $ch, CURLOPT_URL, $url );              // the url to request
if ( false===( $response = curl_exec( $ch ) ) ){    // fetch remote contents
    $error = curl_error( $ch );                  
    // doesn't exist
}
curl_close( $ch );                                  // close the resource

Upvotes: 3

Related Questions