【问题标题】:How to return response from text file to web api using codeigniter?如何使用 codeigniter 从文本文件返回响应到 web api?
【发布时间】:2020-06-13 05:26:18
【问题描述】:
$url='https://example.com/demo/webservice/register?auth_key=cghjcgfchai1723y12y321hjvbv1asdas';
$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_POSTFIELDS,$posted_data);
$response  = curl_exec($ch);

if($response === false)
{
    echo 'Curl error: ' . curl_error($ch);
}
else
{
    $my_file = 'file.txt';
    $handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file);
    fwrite($handle,$response);
}
curl_close($ch);
return $response;

regiter.php

public function register()
{
    $key='cghjcgfchai1723y12y321hjvbv1asdas';
    $secretKey=$this->input->get('auth_key');
    if($key!=$secretKey)
    {
        echo json_encode(array("response"=>"error","result"=>array("message"=>"Invalid key ")));
        exit;
    }
    print_r($_POST);
    exit();
}

文件.txt

Array
(
    [email] => testn@gmail.com
    [std_name] => testing
    [menu-590] => 1000SK
    [sex] => MALE
    [father_name] => xyz
    [mother_name] => abc
    [dob] => 2020-02-21
    [phone] => 9876543211
    [address] => GHAZIABAD
    [pin] => 201206
    [aadhar] => 123456789012
)

我正在使用 curl 将响应从 file.txt 文件返回到 register 文件,我只是使用 print_r($_POST) 来知道响应是否到来,但它向我显示空白数组。我不知道为什么?请帮帮我。

谢谢

【问题讨论】:

  • 觉得你需要curl_setopt($ch, CURLOPT_POST, 1);
  • 什么都没发生@NigelRen

标签: php rest api codeigniter curl


【解决方案1】:

在您的 cURL 请求中,您没有打印任何内容,您只是返回响应。将其更改为打印

return $response;

在注册函数中而不是打印返回结果。

public function register()
{
    $key='cghjcgfchai1723y12y321hjvbv1asdas';
    $secretKey=$this->input->get('auth_key');
    if($key!=$secretKey)
    {
        echo json_encode(array("response"=>"error","result"=>array("message"=>"Invalid key ")));
        exit;
    }
    else
   {
      $content = trim(file_get_contents("php://input"));
      return $content
   }
}

在上面的注册函数中,如果key错误会报错,如果正确则会收到发送过来的数据

【讨论】:

    【解决方案2】:

    我复制了您的代码并在我的 codeigniter 项目中进行了测试。我得到相同的空白屏幕或 string(0) ""。后来我发现构造函数中的一些代码只是根据会话值重定向我的脚本。试试你的代码是否也是这种情况。

    【讨论】:

      猜你喜欢
      • 2014-08-10
      • 2012-06-22
      • 1970-01-01
      • 2016-04-23
      • 2018-07-17
      • 1970-01-01
      • 1970-01-01
      • 2016-12-17
      • 2016-04-23
      相关资源
      最近更新 更多