我有一個index.html
頁面,點擊一個鏈接沿着登錄表單滑動。
登錄按鈕的click事件對PHP腳本執行Ajax,成功時用戶將被重定向到另一個頁面(test.php
)。jquery ajax無法創建php會話
問題是:我沒有得到任何錯誤。
瀏覽器創建一個PHPSESSID,頁面不會重定向。
直接瀏覽test.php
結果$ _SESSION變量未定義錯誤。下面
代碼:
PHP登錄腳本:
<?php
$servername = "localhost";
$username = "abcd";
$password = "12345";
$dbname = "abcdmaster";
$obj = new stdClass();
$obj->msg = '';
$obj->err = '';
$obj->uname = '';
// Create Database connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if($conn->connect_error) {
die("connection failed: " . $conn->connect_error);
} elseif(isset($_POST['userid']) and isset($_POST['password'])) {
session_start();
$username = $_POST['userid'];
$password = $_POST['passwd'];
$sql = "select * FROM `adminuser` WHERE username=$username";
$result = $conn->query($sql);
if($result->num_rows == 1) {
$row = $result->fetch_assoc();
if(strcmp($row['password'],$password)==0) {
$obj->msg = "yes";
$_SESSION['username'] = $row['username'];
$obj->uname = $_SESSION['username'];
} // end strcmp
} else {
$obj->msg = "no";
//$obj->err = "Invalid Login Credentials";
}
header('Content-Type: application/json');
echo json_encode($obj);
return false;
} // end isset
?>
的jQuery:
/* click event for login button */
$('.loginrow').on('click', 'input[value="Login"]', function() {
var creds = {}
creds.userid = $('#userid').val();
creds.passwd = $('#password').val();
console.log(creds);
$.ajax({
url: 'http://localhost/server/adminlogin.php',
data: creds,
type: 'POST',
dataType: 'json',
}).done(function(data) {
if(data == 'yes') {
console.log("login ok");
window.location.href = './server/test.php';
} else {
console.log("login unsuccessful");
}
});
return false;
});
test.php的:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Logged on user is " . $_SESSION["username"] . ".<br>";
?>
</body>
</html>
任何想法?
添加'在session_start();'在adminlogin.php ...... –
你必須在session_start添加到您的第一頁 – Icewine
哎呀......你的代碼是脆弱的到SQL注入,你需要解決這個問題,另外,你需要以明文存儲密碼,這也是你需要修復的。 – Enstage