Wednesday, August 21, 2013

PHP CURL functions for POST and GET request using Codeigniter

Install the curl library from https://github.com/philsturgeon/codeigniter-curl
CodeIgniter-cURL is a CodeIgniter library which makes it easy to do simple cURL requests and makes more complicated cURL requests easier too.
  //load the Curl library
  $this->load->library('Curl');        

  //Request using POST Method
   $url = 'http://postexample.com/json.php';       
   echo $this->curl->simple_post($url, false, array(CURLOPT_USERAGENT => true));

   //Request using GET Method
   $get_url = http://getexample.com/json.php;  
   echo $this->curl->simple_get($get_url, false, array(CURLOPT_USERAGENT => true)); 
It is very important to set CURLOPT_USERAGENT, otherwise many servers may refuse your request if you don't pass user agent.
   //PHP version, you can put anyvalue for CURLOPT_USERAGENT, but it shouldn't be empty or blank.
    curl_setopt($ch,  CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"); 
I tried without setting CURLOPT_USERAGENT in GOOGLE CHROME, it didn't worked. I spent more than 4 hours to find a solution, why it is not returning the result. Finally, I found this post http://www.silverphp.com/php-curl-function-for-post-and-get-request.html and try with my luck. And it worked. :)

3 comments:

  1. I guess you for got to change the comment on get method

    ReplyDelete
  2. hi,
    I get this message Call to a member function library() on null
    when i call $this->load->library('Curl');

    ReplyDelete