简体   繁体   中英

PHP issue “Cannot send session cookie”

Please find attached my code:

<?PHP 
session_start();
if (isset($_POST["usernameform"])){ 

$username = $_POST['usernameform'];
$password1 = $_POST['passwordform'];


$user_name = "XXXX";
$password = "XXXXX";
$database = "XXX";
$server = "XXXX";

$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);


$SQL = "SELECT * FROM login WHERE Username = '$username' AND Password = '$password1' "; //grab all the records from table
$result = mysql_query($SQL)
    or die("Error:" . mysql_error());

if (mysql_num_rows($result) > 0){ //if username and password match return number of rows is always 1

$_SESSION['login'] = $username; //by placing this in session it will remember this variable on the page it directs too

while ( $row = mysql_fetch_assoc($result) ){ //lays out array in $result
$_SESSION['ID'] = $row['ID']; //selects from list of array ID
$_SESSION['firstname'] = $row['First_Name'];
echo'<script> window.location="page1.php"; </script> ';

}
} else {
$_SESSION['login'] = '';
print('
<script type="text/javascript"> //place html script for alert. Use single comma for print command here.
    alert("Sorry, your username or password could not be recognized")
</script>
');
session_destroy();
}
}
?>

Although the code works perfectly on my localhost (wampserver), it does not work on my host and I get the errors:

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /.../vhindex.php:1) in /.../vhindex.php on line 2

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /.../vhindex.php:1) in /.../vhindex.php on line 2

The session_start(); code has been placed at the top of the PHP block and before any HTML output is made and I am completely stumped.

Any ideas?

  • Download Notepad++ and open the file there, delete all fancy characters before the <?PHP
  • Make sure there is no whitespace character like " " or tab or linebreak before the <?PHP .
    • In Notepad++ click Encoding and then UTF-8 without BOM to convert the file to UTF-8 without BOM, then save it.
  • Also add ob_start(); before session_start(); to be safe.

If you load this -.php file from vhindex.php. Make sure that this is done in the right order. Eg. require_once'handle-user-login.php'; callToYourFunction();

If your session already been sent you get this warning. (Yeah like the error code says).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM