Home > Back-end >  PHP curl send POST to nginx api, the POST doesn't hit the target
PHP curl send POST to nginx api, the POST doesn't hit the target

Time:10-28

the GET requests work fine, but if i tried to POST sent... nginx vhost conf

    location /api/b1/ {
        auth_request /_validate_apikey;
        try_files $uri $uri/ /api.php?$args;
        rewrite ^/api/b1/([^/] )/([^/] )/?$ /api.php?data1=$1&data2=$2? last;

}

nginx log

185.111.90.223 - - [28/Oct/2022:13:16:59  0200] "GET /api/b1/1951/ugyfel_modul HTTP/1.1" 200 16039 "-" "-"
185.111.90.223 - - [28/Oct/2022:13:16:59  0200] "POST /api/b1/1951/adatkuldes HTTP/1.1" 200 19 "-" "-"

The request is ok apparently, no token error, but the api.php you don't get the POST array.

php curl call

$array=json_encode($array,JSON_FORCE_OBJECT);

$ch = curl_init($server.'/'.$data1.'/'.$data2);                                                               
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $array);                                                                  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($array),
    'X-API-KEY:  '.$token)                                                                       
);                                                                                                                   
       
                                                                                                                     

$result = curl_exec($ch);   curl_close($ch);
$api = json_decode($result, true);  

Remote code:

if(!empty($_POST)) { 
  $json = array("ok"=>1); 
}
else {
  $json = array("ok"=>0);
}

and the answer is: ok=>0

What could be the reason why the POST data is not received? What am I not noticing? I mean an nginx configuration error....

CodePudding user response:

POST variable is populated only when you send data using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type (check out the manual https://www.php.net/manual/en/reserved.variables.post.php). Try:

$data = json_decode(file_get_contents('php://input'), true);
  • Related