我花了很多天来解决这个问题,但我找不到解决方案。在我使用我的 ajax 表单 + php 后端登录后,用户被重定向的页面显示“缺少会话”消息,如果我尝试转储 $_SESSION 它看起来像空的。然后,如果我返回并进行相同的登录,它将正常工作。这发生在不同的浏览器(通常是当他们清除 cookie 和缓存时)和不同的托管服务提供商。
这是我的ajax代码:
$(document).ready(function(){
$('#loginbtn').click(function(){
if($('#username').val() == "" || $('#password').val() == ""){
return false;
}
else
{
$.ajax
({
type: 'POST',
url: 'ajax_login.php',
cache: false,
dataType: 'json',
data:
{
username: $('#username').val(),
password: $('#password').val()
},
success:function(data)
{
if(data.error === true){
alert("Failed to login: "+data.message)
}
else
{
setTimeout(function()
{
window.location = 'http://www.mywebsite.com/dashboard.php';
},2000);
}
},
error:function(XMLHttpRequest,textStatus,errorThrown){
alert("An error occured!");
}
});
return false;
}
});
});
这是 PHP 登录后端:
<?php
include "config.php"; // start session and connect to mysql db, also contain functions sanitize(), getip()
$username = sanitize(htmlspecialchars($_POST['username'],ENT_QUOTES));
$pass = sanitize($_POST['password']);
// FUNCTION TO LOGIN
$sql = mysql_query("SELECT * FROM members WHERE username = '$username' AND password = '$pass'");
$array = mysql_fetch_array($sql);
if(mysql_num_rows($sql) === 0){
$message['error'] = true;
$message['message'] = "Wrong username or password.";
echo json_encode($message);
exit;
}
$_SESSION['username'] = ucwords(strtolower($username));
$_SESSION['points'] = $array['points'];
$_SESSION['ip'] = getip();
$_SESSION['welcome'] = true;
$message['error'] = false;
$message['message'] = "Completato.";
echo json_encode($message);
exit;
最后这是 dashboard.php 检查会话代码:
<?php
include "config.php";
if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start();
if($_SESSION['username'] == "") {
header("Location: index.php?nosession");
exit;
}
编辑:这是 config.php 里面的内容
<?
session_start();
date_default_timezone_set("Europe/Rome");
$hostname = ""; //hostname
$data_username = "dbxxxxxxxx"; //database username
$data_password = "xxxxx"; //database password
$data_basename = "dbxxxxxxx"; //database name
$conn = mysql_connect("".$hostname."","".$data_username."","".$data_password."");
mysql_select_db("".$data_basename."") or die(mysql_error());
function sanitize($text) { // funzione che pulisce le stringe per prevenire exploit;
if(get_magic_quotes_gpc() == 0) {
$text = addslashes($text);
}
$text = htmlentities($text);
$text = strip_tags($text);
$escape = mysql_real_escape_string($text);
$arraydangerous = array('SELECT *', 'LOAD_FILE', 'DELETE', 'TRUNCATE', '\' OR', '<javascript>', 'src=', '<?', '?>', 'document.cookie', 'http://', 'www.');
$text = str_replace($arraydangerous, "", $text);
return $text;
}
function getip()
{
return filtra($_SERVER['HTTP_CF_CONNECTING_IP']); // I use CloudFlare ,so i must use this way :)
}
我怎样才能解决这个问题?谢谢