Reputation: 2795
Trying to get the content of the a certain URL using cURL and PHP. The code is supposed to run on the sourceforge.net project web hosting server.
code:
<?php
function get_data($url)
{
$ch = curl_init();
$timeout = 10;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$url1 = urlencode("http://www.google.com");
$url2 = "http://www.google.com";
$output = get_data($url2);
echo $output;
?>
I've checked that cURL is supported. But the above code is not working, the page is loading till timeout with no output. I've tried the encoded url as well. Why?
Error 503 Service Unavailable
. PHP version 5.3.2
Upvotes: 0
Views: 13644
Reputation: 690
You might want to use file_get_contents
$content = file_get_contents('http://www.google.com');
/some code here if needed/
return $content;
You can also set files inside file_get_contents ex:
$content = file_get_contents('textfile.txt');
More information about the function file_get_conents
Some info which I noticed when working with cUrl:
One thing I've also noticed when working with cUrl is that it works differently when the URL has http or https. You need to make sure that you code can handle this
Upvotes: 5
Reputation: 8071
I replaced my curl code with yours and its not working. I tried with 'gmail.com' and it showed fine with my code and with yours it gave a '301 Moved' Error.
My Code is as follows:
function get_web_page($url)
{
//echo "curl:url<pre>".$url."</pre><BR>";
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_USERAGENT => "spider", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 15, // timeout on connect
CURLOPT_TIMEOUT => 15, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
);
$ch = curl_init($url);
curl_setopt_array( $ch, $options );
$content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch,CURLINFO_EFFECTIVE_URL );
curl_close( $ch );
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
//change errmsg here to errno
if ($errmsg)
{
echo "CURL:".$errmsg."<BR>";
}
return $content;
}
Upvotes: 4