我使用Ajax將登錄表單細節從HTML傳遞到PHP。細節得到正確傳遞,並且所有功能都能正常工作並且警報也基於輸出進行工作。調用「json_encode」後PHP頭和會話標籤不工作
但是,如果我在json_encode
之下添加以下會話語句,則不起作用。在執行「檢查元素」後,Chrome的「網絡標籤」中的輸出是正確的,但標題功能不起作用,並且警報也不會在成功或失敗時在Ajax中指定。
下面是代碼:
<?php
ob_start();
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "kites";
//Create Connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
//Check connection
if(!$conn)
{
die("Connection failed: " . mysqli_connect_error());
alert("Connection failed");
}
else
{
if(empty($_POST['loginusername']) && empty($_POST['loginpassword']))
{
echo json_encode(array('status'=>false,'msg'=>'No arguments provided'));
}
else
{
$loginusername = $_POST['loginusername'];
$loginpassword = $_POST['loginpassword'];
$stmt = $conn->prepare("SELECT * FROM register_form WHERE username = ?");
$stmt->bind_param("s", $loginusername);
if($stmt->execute())
{
$result = $stmt->get_result();
$num_of_rows = $result->num_rows;
if($num_of_rows > 0)
{
$user = $result->fetch_assoc();
$salt = $user['salt'];
$encrypted_password = $user['password'];
function checkhashSSHA($salt,$password)
{
$hash = base64_encode(sha1($password . $salt, true) . $salt);
return $hash;
}
$hash = checkhashSSHA($salt,$loginpassword);
if($encrypted_password == $hash)
{
echo json_encode(array('status'=>true, 'msg'=>'Login Successfull'));
session_regenerate_id();
$_SESSION['username']=$loginusername;
session_write_close();
//here you can redirect on your file which you want to show after login just change filename ,give it to your filename.
header("Location:http://localhost/kites/profile.php");
}
else
{
echo json_encode(array('status'=>false,'msg'=>$encrypted_password));
}
}
else
{
echo json_encode(array('status'=>false,'msg'=>'Wrong username. Please check it and try again'));
}
}
else
{
echo json_encode(array('status'=>false,'msg'=>'Something went wrong. Please try again!'));
}
} } ?>
如果我刪除下面的語句:
session_regenerate_id();
$_SESSION['username']=$loginusername;
session_write_close();
header("Location:http://localhost/kites/profile.php");
的代碼工作正常。
的可能的複製[如何修復「頭已發送」錯誤在PHP中](http://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php) – JakeGould