'PHP curl doesn't send POST params
I have the file1.php which contains curl which call file2.php. When running this code on localhost, everything works fine, but when running this code on the server, the file2 can't see POST params. (With GET params everything works well both on localhost and on server.)
file1.php:
<?php
$Url = $_SERVER['HTTP_HOST'] . '/file2.php';
$PostFields = http_build_query([
'name' => 'John',
'age' => 24
]);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $Url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $PostFields);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
curl_exec($curl);
file2.php
<?php
echo 'Received params: ' . json_encode($_POST);
Output on localhost:
Received params: {"name":"John","age":"24"}
Output on server:
Received params: []
Why POST params works on localhost, but not on server?
Solution 1:[1]
Ok, I've found an answer.
The reason why it was not working on server was the redirections the server was doing for some reason. During the redirection POST data was lost, so I have to add curl_setopt($curl, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL); to the code.
Now it works fine.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Przemek |
