PHP- setcookie不能修改头信息


PHP- setcookie cannot modify header information

我是PHP新手,我试图研究这个问题,但也许我没有问对…我可以告诉从其他帖子/指令,我不能用户header()或setcookie()打印出HTML后…

我注释掉了标题"重定向"——我可以把它放在HTML之后吗?现在是setcookies失败了:

我没有看到什么?我总是出错,但我的HTML在PHP后面:

if (!isset($_COOKIE["user"])) {
$sUserIdentity = $_POST["userIdentity"];
//username is not accepted as a get value
$sPassword = $_POST["password"];
$sEmail = $_POST["email"];

$cnn= odbc_connect("Driver={SQL Server};Server=$server;Database=$dbI", $user, $password);
//check to see if email account or username already used
$sql2 = "select id from i_user where email = '" . $sEmail  . "' or username ='" . $sUserIdentity . "'";
//echo $sql2 ."<br>";
$result = odbc_exec($cnn, $sql2);
$id = odbc_result($result,"id");

if ($id == ''){
    $cnnCreate = odbc_connect("Driver={SQL Server};Server=$server;Database=$dbI", $user, $password);
    $sqlCreate  = "insert into i_user (username,email,salt,active) values ";
    $sqlCreate .= "(";
    $sqlCreate .= "'" . $sUserIdentity  . "',";
    $sqlCreate .= "'" . $sEmail  . "',"; 
    $rsCreate = odbc_exec($cnnCreate, $sqlCreate);
    $sql2 = "select * from i_user where email = '" . $sEmail  . "' and username ='" . $sUserIdentity . "'";
    //echo $sql2 ."<br>";
    $result = odbc_exec($cnn, $sql2);
    $expire=time()+60*60*24*30;
    setcookie("uid", odbc_result($result,"id"), $expire);
    setcookie("user", odbc_result($result,"username"), $expire);
    if ($rsCreate){ 
        $sMsg = "congratulations " . $_COOKIE["user"] . " and welcome "; 
    } 
    else { 
        $sMsg = "There was an error with the query"; 
    }  
}else{
    $sMsg =  "User " . $id . " already in DB";
    //header('Location: ../fec/createuser.php?error=id');
}
}
//echo $sqlCreate;
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>User Form</title>
<script type="text/javascript" src="../js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="../js/jquery-ui-1.10.2.custom.min.js"></script>
<link rel="stylesheet" href="../css/styles.css" type="text/css">
<style>
</style>
</head>
<body>

</body> 
</html>

确保<?php位于文件的最开头,前面没有空行。并且在调用setcookie()之前不能打印或回显任何内容。

为什么不使用输出缓冲呢?

<?php
    ob_start();
?>
<html>
<body>
...
</body>
</html>
<?php
    ob_end_flush();
?>

这将把任何输出放入缓冲区,只要缓冲区没有被刷新,您就可以修改头信息。这样还可以避免在写入头文件之前将PHP警告或错误消息发送到输出时出现问题。