Unfortunately, this answer here by @EatOng is not correct. After reading his answer I added a dummy variable to every AJAX request I was firing (even if some of them already had some fields) just to be sure the error never appears.
But just now I came across the same damn error from PHP. I double-confirmed that I had sent some POST data (some other fields too along with the dummy variable). PHP version 5.6.25
, always_populate_raw_post_data
value is set to 0
.
Also, as I am sending a application/json
request, PHP is not populating it to $_POST
, rather I have to json_decode()
the raw POST request body, accessible by php://input
.
As the answer by @rr- cites,
0/off/whatever: BC behavior (populate if content-type is not registered or request method is other than POST).
Because the request method is for sure POST, I guess PHP didn't recognize/like my Content-Type: application/json
request (again, why??).
OPTION 1:
Edit the php.ini
file manually and set the culprit variable to -1
, as many of the answers here suggest.
OPTION 2:
This is a PHP 5.6 bug. Upgrade PHP.
OPTION 3:
As @user9541305 answered here, changing the Content-Type
of AJAX request to application/x-www-form-urlencoded
or multipart/form-data
will make PHP populate the $_POST
from the POSTed body (because PHP likes/recognizes those content-type
headers!?).
OPTION 4: LAST RESORT
Well, I did not want to change the Content-Type
of AJAX, it would cause a lot of trouble for debugging. (Chrome DevTools nicely views the POSTed variables of JSON requests.)
I am developing this thing for a client and cannot ask them to use latest PHP, nor to edit the php.ini file. As a last resort, I will just check if it is set to 0
and if so, edit the php.ini
file in my PHP script itself. Of course I will have to ask the user to restart apache. What a shame!
Here is a sample code:
<?php
if(ini_get('always_populate_raw_post_data') != '-1')
{
// Get the path to php.ini file
$iniFilePath = php_ini_loaded_file();
// Get the php.ini file content
$iniContent = file_get_contents($iniFilePath);
// Un-comment (if commented) always_populate_raw_post_data line, and set its value to -1
$iniContent = preg_replace('~^\s*;?\s*always_populate_raw_post_data\s*=\s*.*$~im', 'always_populate_raw_post_data = -1', $iniContent);
// Write the content back to the php.ini file
file_put_contents($iniFilePath, $iniContent);
// Exit the php script here
// Also, write some response here to notify the user and ask to restart Apache / WAMP / Whatever.
exit;
}