【问题标题】:Why Im get 400 bad request?为什么我收到 400 错误请求?
【发布时间】:2014-01-21 23:07:40
【问题描述】:

我正在使用 Codeigniter 框架,我想做这样的事情:

我想将 $_GET 变量从服务器 1 发送到服务器 2,如下所示:www.server1.com?foo=123

现在在服务器 2 上,检查 $_GET==123 是否返回一些数据。

我的代码如下所示:

在服务器 1 上,例如:www.server1.com?foo=hello

if(isset($_GET['foo'])){
        $post_fields = array(
            'foo' => $_GET['foo']
        );
        $ch = curl_init('http://server2.com/master.php');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,  $post_fields);
        curl_setopt($ch, CURLOPT_POST, 1);
        $result = curl_exec($ch);
        die($result);
    }

服务器 2 上的代码如下所示:

$variable = $_POST['foo'];
if($variable=="hellow"){
    echo "right!";
}else{
    echo "wrong";
}

当我运行此代码时,我收到 400 个错误请求 - nginx:

【问题讨论】:

  • 首先,您是否允许获取变量?请参阅此问题:stackoverflow.com/questions/334708/… - 另外,如果您使用 CI,您可能需要考虑使用 $this->input->post('foo')
  • server 2 不能使用 CI,所以我不需要使用 $this->input->post('foo'),并且在我的 get variables allowed...另一个想法?谢谢

标签: php codeigniter curl


【解决方案1】:

这行得通:

服务器 1:

<?php
 // for debug purposes removed it on production
error_reporting(E_ALL); 
ini_set('display_errors', 1);
// end debug

if(isset($_GET['foo'])){
        $post_fields = array(
            'foo' => $_GET['foo']);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://server2.com/master.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_fields));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec ($ch);
curl_close ($ch);

if ($result == "OK"){
echo "Post OK";
}else{
echo "Post NOT OK";
}

}else{
die("GET NOT Received");
}
?>

服务器 2:

<?php
 // for debug purposes removed it on production
error_reporting(E_ALL); 
ini_set('display_errors', 1);
// end debug

if(isset($_POST['foo'])){
$variable = $_POST['foo'];

if($variable=="hello"){
    echo "right!";
}else{
    echo "wrong";
}

}else{
  die("POST NOT Received");
}
?>

【讨论】:

  • @PHPIL 总是乐于提供帮助 ;)
【解决方案2】:

尝试使用类似的东西可能会有所帮助

$url = 'http://server2.com/master.php';
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS,  $post_fields);
curl_setopt($ch, CURLOPT_POST, 1);
echo $ret = curl_exec($ch);

并调试结果

【讨论】:

    【解决方案3】:

    您要发布一个数组,所以添加这一行:

    curl_setopt ($ch, CURLOPT_HTTPHEADER, Array("Content-Type: multipart/form-data"));
    

    参考:http://au1.php.net/curl_setopt

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-04
      • 1970-01-01
      • 2014-12-06
      • 1970-01-01
      • 2022-12-03
      • 2013-01-26
      • 2021-12-20
      • 1970-01-01
      相关资源
      最近更新 更多