file_get_contents (“php://input”) 返回一个长字符串


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

我正在尝试通过AJAX将JSON发送到我的PHP,但$_POST什么都没有,file_get_contents(“php://input”)返回一个长字符串。

AJAX 代码:

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

显示 AJAX 之前的警报{"用户名":"用户","密码":"长哈希在这里","op":"登录"}

PHP代码:

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

这是我在日志文件中得到的内容

userpassSERVER-REQUEST_METHODPOSTgetfileusernameasdpasswordcd8d627ab216cf7fa8992ca4ff36653ca6298566dc5f7d5cc9b96ecf8141c71boplogin

这是我在 AJAX 中成功返回警报时得到的错误:空

我无法解码file_get_contents("php://input"),因为没有分隔符。

编辑:logme 函数正在中断日志字符串文本。我已经修复了这个问题,这就是我现在的日志文件中的内容。用户: 通过: 服务器REQUEST_METHOD: 开机获取文件: {"用户名":"asd","密码":"cd8d627ab216cf7fa8992ca4ff36653ca6298566dc5f7d5cc9b96ecf8141c71b","op":"login"}

所以我应该没事,我会解码file_get_contents("php://input")

quention 是正确的,这是我的日志记录功能的问题。 我在测试中使用它只是因为我有它可用但没有费心去看它。它有一个 cleanString 函数,导致我的问题。

将userData的格式更改为&用户名=某物&密码=某物。

您需要自己填充变量。因为您要发送 JSON,所以 PHP 不会为您构建$_POST

$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

这是另一种常见的方法:

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

首先,$_POST是一个超级全局变量,它不是一个函数$_POST('username'); $_POST['username']

你说

但是$_POST什么都没有,file_get_contents("php://input")返回一个长字符串。

最后,

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

哪个$pass等于

$pass =  $_POST["pass"];

相反,您应该从file_get_contents("php://input")本身读取外部变量。以下用户函数用于解析file_get_contents("php://input"),从PHP文档注释中抓取。

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;
}

并与您的代码一起使用

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