【发布时间】:2019-04-04 22:47:12
【问题描述】:
在我原来的 php5 代码中,一旦用户打开索引页面,就会有一个 ajax 调用来检查是否存储了任何 $_SESSION['user']。如果有会话,将显示用户。否则页面会重定向到登录页面。一旦我升级到 php 7,它就停止工作了。
$.ajax({
type: 'POST',
url: "php/checksession.php",
})
.done(function(response) {
console.log(response);
var code = response[0].code;
///// if no loging session is stored, redirect back to loging page
if (code == 0) {
window.location.href = "login";
///// Session is found, update balance
} else {
$('body').show();
///////////////////// Do other stuff
}
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Title Goes Here</title>
</head>
<body style="display:none">
<p>PageContent</p>
</body>
</html>
这里是 php7 代码。
<?php
header('Content-type: application/json');
require 'connection.php';
// Get Access to DB
// if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST))
{
ob_start();
session_start();
if (isset($_SESSION['user']))
{
$responseArray = array(
'code' => '1',
'type' => 'good',
'message' => 'found'
);
}
else
{
$responseArray = array(
'code' => '0',
'type' => 'bad',
'message' => 'no session'
);
}
}
else
{
$responseArray = array(
'code' => '0',
'type' => 'bad',
'message' => 'no POST'
);
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
$Arrays = [];
array_push($Arrays, $responseArray);
$encoded = json_encode($Arrays);
header('Content-Type: application/json');
echo $encoded;
}
else
{
echo $responseArray['message'];
} // else just display the message
?>
$_POST为空且Json数据不回传给浏览器因为不符合这条语句:
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
【问题讨论】:
-
您能否格式化您的代码以使其更易于阅读。
-
将
ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(-1);添加到 PHP 脚本的顶部以检查错误 -
您之前的 PHP 安装可能没有设置错误报告,并且可能正在抑制错误。
-
我想知道你为什么使用这个
<body style="display:none">。你知道那是做什么的,对吗? -
@FunkFortyNiner 我会冒险猜测并说他们正在隐藏页面并且仅在会话有效时才显示它。更好的方法是显示登录页面并在会话存在时重定向。
标签: php html arrays ajax session