Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why this php cURL function can't work

Tags:

php

function get_data($url) {
  $ch = curl_init();
  $timeout = 5;
  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;
}

i find this function from the internet. when i test it in a php file using this code $returned_content = get_data('http://google.com'); but it can't work.and get a "301 Moved Permanently" The document has moved here. error. why?

like image 772
runeveryday Avatar asked Feb 10 '11 09:02

runeveryday


People also ask

Can I use cURL in PHP?

cURL is a PHP extension that allows you to use the URL syntax to receive and submit data. cURL makes it simple to connect between various websites and domains.

How can get cURL value in PHP?

PHP cURL GET requestphp $ch = curl_init('http://webcode.me'); curl_exec($ch); curl_close($ch); In the example, we send a GET request to a small website. The output is directly shown in the standard output.

Is cURL default in PHP?

cURL is enabled by default but in case you have disabled it, follow the steps to enable it. Open php. ini (it's usually in /etc/ or in php folder on the server). Search for extension=php_curl.


2 Answers

According to your comments, you are getting a 302 status code. Try

curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);

to follow 30x redirects.

Manual on curl_setopt()

like image 65
Pekka Avatar answered Sep 20 '22 16:09

Pekka


add one more option to your get_data function :

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

Google is redirecting you to the local google servers and your curl call currently isn't chasing redirects.

oh yeah,
and do a var_dump($returned_content); to see the results :P

like image 20
Shrinath Avatar answered Sep 18 '22 16:09

Shrinath