【问题标题】:Curl command not getting executed卷曲命令没有被执行
【发布时间】:2017-11-02 17:15:31
【问题描述】:

我正在尝试从 php 脚本运行 curl 命令,但它没有按预期工作。问题出在 curl 命令或我用 .htacccess 文件编写的 url 重写规则中。

curl 命令文件中的代码:我只是尝试使用此命令发布数据并期望返回一个数组。

    <?php
     $data=array(
    'product_name' =>'Television',
    'price' => 1000,
    'quantity' => 10,
    'seller' =>'XYZ Traders'
   );
   $url = 'http://localhost/API2/products';
    $ch = curl_init($url);
     curl_setopt($ch, CURLOPT_POST, true);
   curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   $response_json = curl_exec($ch);
   curl_close($ch);
   $response=json_decode($response_json, true);
   echo $response;

  ?>

我的 .htaccess 文件用于 url 重写,这意味着 http://localhost/API2/products 应该用于 CRUD 操作。网址规则为:

  RewriteEngine On # Turn on the rewriting engine
  RewriteRule ^products/?$ products.php [NC,L]
  RewriteRule ^products/([0-9]+)/?$ products.php?product_id=$1 [NC,L]

因此,如果您可以在我运行 curl 命令 file.php 时帮助找到问题,它不会返回任何内容,也不会执行代码。

【问题讨论】:

  • $response_json 中有什么?您是否尝试过回应?
  • $request_method=$_SERVER["REQUEST_METHOD"]; switch($request_method) { case 'POST': $response=array('status' => 1, 'status_message' =>'产品添加成功。'); header('Content-Type: application/json');回声 json_encode($response); default: // 无效的请求方法标头("HTTP/1.0 405 Method Not Allowed");休息; }
  • 我没有得到你想要的这个评论男人
  • 在我的其他文件中是这样的。我编辑了它。我使用 switch 语句,具体取决于它需要进入它并返回数组的 request_method。
  • 重点是在使用 json_decode 之前你必须检查 curl 的原始响应并检查里面的内容

标签: php .htaccess curl


【解决方案1】:

问题是你试图 POST 一个数组 ($data),而你应该 POST 一个字符串。

要解决这个问题,请在下面添加函数 URLify。

function URLify( $arr, $encode = FALSE ) {

    $fields_string = '';
    foreach( $arr as $key => $value ) {
        if ( $encode ) {
      $key = urlencode( $key );
            $value = urlencode( $value );
        }
        $fields_string .= $key . '=' . $value . '&';
    }
    $fields_string = substr( $fields_string, 0, (strlen($fields_string)-1) );

    return $fields_string;

}

然后添加:

$data = URLify( $data, TRUE );

以上:

$url = 'http://localhost/API2/products';

【讨论】:

  • 从 curl 发布数据时,我如何接收 products.php 上的数据。我正在尝试使用 $_POST 。像这样:echo“到了这里”; $_product_name=$_POST["product_name"]; $_price=$_POST["价格"]; $_quantity=$_POST["数量"]; $_seller=$_POST["卖家"]; echo"data:= "+$_product_name+$_price+$_quantity+$_seller;
  • @Rahila 重要的是不要在 cmets 区域提出其他问题。我提供的答案就是您所提问题的答案。请将其标记为正确答案,然后将您的新问题添加为 StackOverflow 上的问题。如果您在此处发布新问题的链接,我会尽力回答。
  • 感谢您告诉我它有效,但如果您能告诉我如何接收数据并解包。我正在尝试 $_POST 从 url 获取数据,但它得到 1 和 0。谢谢
  • @Rahila 您没有使用 $_POST 从 URL 获取数据。这是使用 $_GET 完成的。如果您在新问题中发布代码,帮助会容易得多。
  • @Rahila 关于上面发布的代码......你会遇到问题,因为你试图回显数组 $response。要回显一个数组,请使用类似 echo '
    ';打印_r($响应);回声'
    ';
猜你喜欢
  • 1970-01-01
  • 2016-11-08
  • 1970-01-01
  • 2016-03-14
  • 1970-01-01
  • 2017-07-15
  • 2021-10-05
  • 1970-01-01
  • 2021-01-21
相关资源
最近更新 更多