PHP 问题 "Cannot send session cookie"

标签 php session cookies

请查看附件中我的代码:

<?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();
}
}
?>

尽管代码在我的本地主机 (wampserver) 上运行良好,但它在我的主机上不起作用并且出现错误:

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

session_start(); 代码已放在 PHP block 的顶部,并且在生成任何 HTML 输出之前,我完全被难住了。

有什么想法吗?

最佳答案

  • 下载Notepad++并在那里打开文件,删除 <?PHP 之前的所有花哨字符
  • 确保在 <?PHP 之前没有空格字符,如 ""、制表符或换行符.
    • 在 Notepad++ 中点击 Encoding然后 UTF-8 without BOM将文件转换为不带 BOM 的 UTF-8,然后保存。
  • 同时添加 ob_start();之前session_start();为了安全。

关于PHP 问题 "Cannot send session cookie",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15367131/

相关文章:

PHP设置COOKIE,用JQUERY COOKIE插件改的,用php不能编辑?

未在 Safari 6 中设置 Cookie

php - 如何在 WordPress 中将菜单位置添加为管理仪表板菜单

php - 在 PHP 的一次调用中追加/连接多个字符串?

session - Grails 3 Controller 范围

php - PHP 从 5.3.1 升级到 5.3.2 后 session 不起作用

php - 两个 CodeIgniter 应用程序之间的 session 共享

javascript - 使用 cookie 更改背景图像

javascript - 在 AJAX 内容渲染之前加载所有 JS 和 CSS

javascript - 编辑器数据表 : Not Working