【问题标题】:How to process POST in php file sent by curl如何处理curl发送的php文件中的POST
【发布时间】:2016-05-04 05:41:16
【问题描述】:

我在 bluehost 服务器 test.php 上创建了一个文件,并使用该文件从另一台服务器 (godaddy) 发送 curl 请求。

$url = 'http://dev.testserver.com/test.php';
        $data_string = json_encode($fields);
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_POST, 1); 
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
        curl_setopt($curl, CURLOPT_POSTFIELDS,$data_string );                                                                  
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);                                                                      
        $curl_response = curl_exec($curl);

如何在 test.php 上捕获发布的数据并进行处理? 我正在尝试使用 $_POST,但它显示为空白。

【问题讨论】:

  • @VictorSmirnov 我看不出这两个问题之间有任何相似之处。其他问题仅针对 $_POST,我提到了特定的 curl 而不是 POST。但是感谢您的链接,答案非常有用。
  • 我认为问题是“如何在 test.php 上捕获发布的数据并进行处理?”您发送 JSON 数据而不是“application/x-www-form-urlencoded”数据,这就是为什么您无法使用$_POST 读取它的原因。另一个答案是针对这个问题 - 如何使用 POST 发送日期以确保它可用于$_POST。可能这是您需要的,但您正式提出了不同的问题。

标签: php curl


【解决方案1】:

问题接近这个How to send raw POST data with cURL? (PHP)

我根据建议稍微修改了您的客户端代码:

<?php

$fields = ['a' => 'aaaa', 'b' => 'bbbb'];

$url = 'http://localhost/test.php';
$data_string = json_encode($fields);

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($curl, CURLOPT_POSTFIELDS, urlencode($data_string));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$curl_response = curl_exec($curl);

echo 'Response: '.$curl_response.PHP_EOL;

我为发送的数据做urlencode 并设置标题。

问题How to get body of a POST in php?中解释了如何读取数据的逻辑我用下面的代码做了一个简单的test.php文件

<?php

$body = file_get_contents('php://input');
if (!empty($body)) {
    $data = json_decode(urldecode($body), true);
    var_export($data);
}

我们读取数据,对其进行解码并解析 JSON。

正如人们所期望的,客户端脚本的测试输出如下

$ php client.php 
Response: array (
  'a' => 'aaaa',
  'b' => 'bbbb',
)

【讨论】:

    【解决方案2】:

    尝试替换这个,直接发array而不是json

    curl_setopt($curl, CURLOPT_POSTFIELDS,$data_string );
    

    curl_setopt($curl, CURLOPT_POSTFIELDS,$fields );
    

    检查这个:http://php.net/manual/en/function.curl-setopt.php

    【讨论】:

      猜你喜欢
      • 2011-05-12
      • 1970-01-01
      • 2021-05-05
      • 1970-01-01
      • 2019-09-02
      • 1970-01-01
      • 2018-02-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多