Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter sending POST data to specific URL - API data

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

like image 460
Sanjeev Avatar asked Jun 29 '15 03:06

Sanjeev


1 Answers

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"}

like image 66
Sanjeev Avatar answered Nov 04 '22 06:11

Sanjeev