首次登录Session未初始化,二次登录才生效的PHP问题求助
Hey Andrew, let's dig into why your session isn't saving on the first login—this is a common gotcha for new PHP devs, so don't feel stuck!
First, the Critical Fix: session_start() Must Come Before Any Output
Looking at your login page code, you're calling session_start() after the HTML table. That's a big problem! PHP needs to send session cookies via HTTP headers, and headers can't be sent once any HTML (even whitespace) has been output. This breaks session initialization on the first visit, which explains why your first login fails to save the username.
Fix your login page by moving session_start() to the very top, before any HTML:
<?php session_start(); // This has to be the first line of code! ?> <table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC"> <tr> <form name="form1" method="post" action="checkLogIn.php"> <!-- Rest of your HTML form -->
Second: Ensure Session Data Writes Before Redirecting
In checkLogIn.php, you're using a meta tag to redirect immediately after setting $_SESSION['user']. Sometimes PHP delays writing session data to the server until the script finishes executing—if the browser redirects before that happens, the new page won't see the session data.
Fix this by adding session_write_close() to force PHP to save the session right away before redirecting:
if($count==1){ $_SESSION['user'] = $myusername; echo "Welcome ".$_SESSION['user']."!"; session_write_close(); // Save session data immediately echo "<meta http-equiv=\"refresh\" content=\"2;URL=http://www.morgan-data.co.uk/logInHome.php\">"; }
If you want a more reliable server-side redirect, use PHP's header() function (just make sure no output comes before it—remove the welcome echo if you go this route):
if($count==1){ $_SESSION['user'] = $myusername; session_write_close(); header("Location: http://www.morgan-data.co.uk/logInHome.php"); exit; // Stop script execution after redirect to prevent extra code from running }
Third: Verify Session Cookie Scope
If your site uses subdomains or specific paths, the session cookie might not be accessible across pages. Add this before session_start() in all your PHP files (login, checkLogIn, logInHome) to ensure the cookie works across your entire domain:
session_set_cookie_params(0, '/', 'morgan-data.co.uk'); // Set cookie for the full domain session_start();
Bonus: Replace Deprecated mysql_* Functions
Your code uses mysql_* functions, which were removed in PHP 7.0. Switch to mysqli_* for compatibility and better security (use prepared statements to avoid SQL injection):
// Connect with mysqli $conn = mysqli_connect($host, $username, $password, $db_name); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // Use prepared statements instead of manual escaping $stmt = mysqli_prepare($conn, "SELECT * FROM $tbl_name WHERE username=? AND password=?"); mysqli_stmt_bind_param($stmt, "ss", $myusername, $mypassword); mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); $count = mysqli_num_rows($result);
Try these fixes in order—moving session_start() to the top is the most likely culprit here. Let me know if you run into any other issues!
内容的提问来源于stack exchange,提问作者Andrew Booth

