简体   繁体   English

CodeIgniter将POST数据发送到特定URL - API数据

[英]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() 我需要将数据发送到URL,我之前已通过方法GET和使用url_encode()完成此操作

Now that I need to POST with the framework CodeIgniter, I am not very well aware what to use 现在我需要使用框架CodeIgniter进行POST,我不太清楚要使用什么

Any help will be appreciated 任何帮助将不胜感激

Ok, posting answer for avoiding time lapse for searching solution in future 好的,发布答案以避免将来搜索解决方案的时间流逝

Target : Sending POST data to specific URL ie to API 目标:将 POST数据发送到特定URL,即API

Framework : Codeigniter 框架: 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 函数通过POST发送数据到url:是的,我们将在这里使用cURL

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 测试是否可以使用cURL

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"} {“error”:true,“message”:“电子邮件地址无效”}

OR Success : 或成功:

{"error":false,"message":"You are successfully registered"} {“error”:false,“message”:“您已成功注册”}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM