Master345
Master345

Reputation: 2266

Simple CURL url exists won't work

I have 2 codes written with PHP

<?php
error_reporting(1);

function url_exists($url) 
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, TRUE);
    curl_setopt($ch, CURLOPT_NOBODY, TRUE);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $status = array();
    preg_match('/HTTP\/.* ([0-9]+) .*/', curl_exec($ch) , $status);
    return ($status[1] == 200);
}

echo "EX:".url_exists("http://www.google.com");

?>

and

<?php
error_reporting(1);

$ch = curl_init("www.yahoo.com");  
curl_setopt($ch, CURLOPT_TIMEOUT, 2);  
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);  
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)
{  
    echo "Found@";  
} 
else 
{  
    echo "Not found";  
}  

?>

None of this of above works? WHY??? Yesterday worked pretty good, why PHP cannot be explain some times?

I have curl extension on from php.ini ... i tried on 3 different servers ...

What i'm doing wrong? Thank you.

Upvotes: 0

Views: 803

Answers (1)

PiTheNumber
PiTheNumber

Reputation: 23542

echo "EX:".url_exists("http://www.google.com");

will always echo EX: because url_exists returns a boolean. Try:

echo "EX:" . (url_exists("http://www.google.com") ? 'true' : 'false');

Maybe this works?

$ch = curl_init("http://www.example.com/favicon.ico");
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// $retcode > 400 -> not found, $retcode = 200, found.
curl_close($ch);

Source https://stackoverflow.com/a/982045/956397

Upvotes: 1

Related Questions