12

I need to send data to URL, i have done this before by method GET and using url_encode()

Now that I need to POST with the framework CodeIgniter, I am not very well aware what to use

Any help will be appreciated

Sanjeev
  • 534
  • 1
  • 5
  • 16

1 Answers1

16

Ok, posting answer for avoiding time lapse for searching solution in future

Target : Sending POST data to specific URL i.e. to API

Framework : Codeigniter

Solution :

Lets say the required data to pass is an array with name, email, password

$params= array(
           "name" => $_name,
           "email" => $_email,
           "password" => $_pass
        );
$url = '192.168.100.51/AndroidApi/v2/register';

echo '<br><hr><h2>'.$this->postCURL($url, $params).'</h2><br><hr><br>';

Function to Send data via POST to url : yes we will use cURL here

public function postCURL($_url, $_param){

        $postData = '';
        //create name value pairs seperated by &
        foreach($_param as $k => $v) 
        { 
          $postData .= $k . '='.$v.'&'; 
        }
        rtrim($postData, '&');


        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_HEADER, false); 
        curl_setopt($ch, CURLOPT_POST, count($postData));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);    

        $output=curl_exec($ch);

        curl_close($ch);

        return $output;
    }

To Test whether or Not cURL is available to use

echo (is_callable('curl_init')) ? '<h1>Enabled</h1>' : '<h1>Not enabled</h1>' ;

Thanks, and it is working very well with output as

Failure :

{"error":true,"message":"Email address is not valid"}

OR Success :

{"error":false,"message":"You are successfully registered"}

Atish Agrawal
  • 2,857
  • 1
  • 23
  • 38
Sanjeev
  • 534
  • 1
  • 5
  • 16