简体   繁体   中英

file_get_contents (“php://input”) returning one long string

I am tryng to send JSON over AJAX to my PHP but $_POST has nothing and file_get_contents(“php://input”) returns one long string.

AJAX code:

function sendData(userData) {
    alert(userData);
    $.ajax({
        type: 'post',
        url: 'testLogin.php',
        dataType : 'json',
        data: userData,
        success: function (msg) {
        if (msg.error) {
            alert("error:" + msg.msg);
            showError(msg.msg);
        } else {  // send to redirection page
            alert("do something here");
        }
    },
    error : function (XMLHttpRequest, textStatus, errorThrown) {
        alert("ajaxError:::" + textStatus + ":::" + errorThrown);
    }
    });
}

the alert before the AJAX shows {"username":"user","password":"long hash here","op":"login"}

PHP code:

$user =  $_POST('username');
$pass =  $_POST["pass"];

$logString = "user: ".$user.
    " pass: ".$pass.
    " SERVER-REQUEST_METHOD: ".$_SERVER['REQUEST_METHOD'].
    " getfile: ".file_get_contents("php://input").  
    "*\n*\n";
// my loging method 
logMe($logString);

$returnMsg['msg']= $pass;
$returnMsg['error'] = true;
echo json_encode($returnMsg);

This is what I get in my log file

userpassSERVER-REQUEST_METHODPOSTgetfileusernameasdpasswordcd8d627ab216cf7fa8992ca4ff36653ca6298566dc5f7d5cc9b96ecf8141c71boplogin

This is what I get at the return alert at success in AJAX error: null

I can't decode the file_get_contents (“php://input”) because there are no delimiters.

edit: the logme function was breaking the logstring text. i have fixed that and this is what i have in my logfile now. user: pass: SERVER-REQUEST_METHOD: POST getfile: {"username":"asd","password":"cd8d627ab216cf7fa8992ca4ff36653ca6298566dc5f7d5cc9b96ecf8141c71b","op":"login"}

so i should be fine i will just decode the file_get_contents(“php://input”)

quention was correct it was a problem with my logging function. i used it in my test just because i had it available but did not bother to look at it. it had a cleanString function in it that was causing my problems.

This is another common way of doing it:

$entityBody = stream_get_contents(STDIN);
$data = json_decode($entityBody, true);
$username = $data['username'];
$password = $data['pass'];

将您的userData格式更改为&username = something&password = something ..

You need to populate the variables yourself. Because you're sending JSON, PHP will not build $_POST for you:

$json_str = file_get_contents("php://input");
$json_obj = json_decode($json_str);

if(is_null($json_obj)): //if there was an error        
    die(json_last_error_msg());
endif;

$username = $json_obj->username;
$password = $json_obj->password

First, $_POST is a super global variable and it's not a function $_POST('username'); $_POST['username']

And you said

but $_POST has nothing and file_get_contents("php://input") returns one long string.

In the end,

$returnMsg['msg']= $pass;  ← ← ←
$returnMsg['error'] = true;
echo json_encode($returnMsg);

which $pass is equal to

$pass =  $_POST["pass"];

Instead, you should read the external variable from file_get_contents("php://input") itself. Following user function used to parse file_get_contents("php://input") , grabbed from PHP docs comment .

function getRealPOST() {
    $pairs = explode("&", file_get_contents("php://input"));
    $vars = array();
    foreach ($pairs as $pair) {
        $nv = explode("=", $pair);
        $name = urldecode($nv[0]);
        $value = urldecode($nv[1]);
        $vars[$name] = $value;
    }
    return $vars;
}

And use along with your codes

header("Content-Type: application/json;charset=utf-8"); //to return the response as json
$post = getRealPOST(); //parse the POST
$user =  $post["username"];
$pass =  $post["pass"];

$logString = "user: ".$user.
    " pass: ".$pass.
    " SERVER-REQUEST_METHOD: ".$_SERVER['REQUEST_METHOD'].
    " getfile: ".file_get_contents("php://input").  
    "*\n*\n";
// my loging method 
logMe($logString);

$returnMsg['msg']= $pass;
$returnMsg['error'] = true;
echo json_encode($returnMsg);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM