我正在为我的网站编写登录脚本。我已经编写了登录脚本,并且通过 jQuery 的 AJAX 调用将表单绑定(bind)到它。
这是表单调用的 php:
<?PHP
# Make sure form data was passed to the script
IF (isset($_POST) && isset($_POST['username']) && isset($_POST['password'])){
# Connect to the database
REQUIRE('../../../../my_db.php');
# Define variables
$given_username = $_POST['username'];
$given_password = $_POST['password'];
$hashed_password = md5($given_password);
$matched_username = "";
$matched_password = "";
# See if there is matching info in the database
$sql = 'SELECT username, pass FROM users WHERE username="'.$given_username.'" AND pass = "'.$hashed_password.'"';
$result = mysql_query($sql);
WHILE($row = mysql_fetch_assoc($result)){
$matched_username = $row['username'];
$matched_password = $row['pass'];
};
# If there was a match
IF ($matched_username != "" && $matched_password != ""){
# Double check the values match
IF ($given_username == $matched_username && $hashed_password == $matched_password){
# If there is only one result returned
$session_sql = 'SELECT * FROM users WHERE username="'.$matched_username.'" AND pass = "'.$matched_password.'"';
$session_result = mysql_query($session_sql);
IF(count(mysql_fetch_assoc($session_result)) != 0 && count(mysql_fetch_assoc($session_result)) < 2){
# If they do, start a session
if(!isset($_SESSION)) {
session_start();
session_regenerate_id();
};
# Set our session values
WHILE($session_row = mysql_fetch_assoc($session_result)){
$_SESSION['id'] = $session_row['id'];
$_SESSION['last_login'] = $session_row['last_login'];
$_SESSION['username'] = $session_row['username'];
$_SESSION['signup_date'] = $session_row['signup_date'];
};
# Set users last login date and time to this login
$update_sql = 'UPDATE users SET last_login = NOW WHERE username="'.$matched_username.'" AND pass = "'.$matched_password.'"';
$update = mysql_query($update_sql);
echo json_encode(array("success"=>"user logged in", "session"=>$_SESSION));
}ELSE
echo json_encode(array("error"=>"More than one user with the same information. What did you do?!"));
}ELSE
echo json_encode(array("error"=>"invalid login provided"));
}ELSE
echo json_encode(array("error"=>"invalid login provided"));
}ELSE
echo json_encode(array("error"=>"you must supply a username and password"));
?>
但是如果我执行 console.log(result.session)
我会得到 []
,这让我认为要么通过 ajax 设置 session 变量是不可行的,或者 session 本身无法正常工作。
这段代码没有错误。
有人能指出我正确的方向吗?
我不认为我可以访问 php.ini,但我记得很久以前你必须将 session 设置为在某个文件中运行,但对于我来说我找不到一个例子.
最佳答案
确保您的脚本开头有 session_start()
。如果在 到达 session_start()
之前抛出任何通知或任何东西,那么您将收到如下错误:
Warning: session_start(): Cannot send session cookie - headers already sent by (output started at...
此外,您的脚本对 SQL 注入(inject)开放。确保正确转义用户名和密码! 注意:最好的办法是使用 prepared statements .
关于php - 使用 AJAX/jQuery 设置 $_SESSION | PHP session 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8496588/