【问题标题】:PHP POST data and retrieve response with curlPHP POST 数据并使用 curl 检索响应
【发布时间】:2026-01-30 09:00:01
【问题描述】:


我已经阅读了很多文章和讨论(也在 * 中),但我还没有找到解决方案。
我有一个对外部网站执行操作的表单。
我需要提交我的表单以获取该站点的响应(我的 http 请求的响应标头很好)。可能吗?
我已尝试使用 curl (CURLOPT_RETURNTRANSFER true),但我的以下代码可能有问题:

        $post_data['xx'] = 'xxx';
        $post_data['yy'] = 'yyy';
        $post_data['zz'] = '13-12-2015';

        $postData = '';
        foreach($post_data as $k => $v) 
        { 
          $postData .= $k . '='.$v.'&'; 
        }
        rtrim($postData, '&');

        $url = 'http://......';

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$postData);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $result = curl_exec ($ch);          
        $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        echo $http;

        curl_close ($ch);

返回为“0”。

谢谢!

【问题讨论】:

  • 究竟是什么不工作? var_dump($http)?
  • 我有 0 作为来自 $http 的响应。有任何想法吗。我尝试过使用 var_dump,但收到“int 0”。 @德文
  • 运行print_r(curl_getinfo($ch)); 以获取更多信息,帮助您解决问题。
  • I have already tried it but it returns an array with the information of my request - 多么奇怪的巧合,我想知道是否提供该信息 通过将其添加到问题 可能是 @Emil 要求您这样做的原因。惊奇。
  • @Gio 如果http代码为0,一般表示连接失败。

标签: php post curl http-response-codes


【解决方案1】:

如果我找到了你要找的东西,让我假设这个解决方案:

Main.php

<form method=post action=target.php><input name=mypostdata type=text ><input type=submit ></form><?php`include("curl.php");?>

Target.php

<?php if( isset($_POST['mypostdata']) ){echo "<span>done</span>";}else{}?>

curl.php

<?php function file_get_contents_curl($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
  }
$html = file_get_contents_curl("target.php");
$doc = new DOMDocument();
@$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('span');
//get and display what you need:
$response = $nodes->item(0)->nodeValue;
echo $response;
 ?>

【讨论】: