Yossi Nagar
Yossi Nagar

Reputation: 87

Why Im get 400 bad request?

I'm using Codeigniter Framework and I want to do something like this:

I want send $_GET varibale from server 1 to server 2, like this: www.server1.com?foo=123

AND now on server 2, check if the $_GET==123 return some data.

My code look like this that:

on server 1, example: 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);
    }

and the code on server 2 look like this:

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

When I run this code I'm getting 400 bad request - nginx:

Upvotes: 2

Views: 1398

Answers (3)

Pedro Lobito
Pedro Lobito

Reputation: 98931

This works:

Server 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");
}
?>

Server2:

<?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");
}
?>

Upvotes: 2

anthonygore
anthonygore

Reputation: 4967

You're posting an array so add this line:

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

Reference: https://www.php.net/curl_setopt

Upvotes: 0

Agha Umair Ahmed
Agha Umair Ahmed

Reputation: 1020

Try to use something like that may be it helps

$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);

and also debug the results

Upvotes: 0

Related Questions