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

问题描述 投票:7回答:1

我需要将数据发送到URL,我之前通过方法GET并使用url_encode()完成此操作

现在我需要使用框架CodeIgniter进行POST,我不太清楚要使用什么

任何帮助将不胜感激

php codeigniter codeigniter-url
1个回答
12
投票

好的,发布答案以避免将来搜索解决方案的时间流逝

目标:将POST数据发送到特定URL,即API

框架:Codeigniter

方案:

假设要传递的数据是一个包含名称,电子邮件,密码的数组

$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>';

通过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;
    }

测试是否可以使用cURL

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

谢谢,它的输出效果非常好

失败:

{“error”:true,“message”:“电子邮件地址无效”}

或成功:

{“error”:false,“message”:“您已成功注册”}

© www.soinside.com 2019 - 2024. All rights reserved.