Setcookie, Cannot Modify Header Information - Headers Already Sent

setcookie, Cannot modify header information - headers already sent

The warning is clear.

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\test\index.php:9) in C:\xampp\htdocs\test\index.php on line 12

Cookies are sent in the HTTP response header. Since the HTML content already started, you cannot go back to the header and add the cookie.

From http://php.net/setcookie:

setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including <html> and <head> tags as well as any whitespace.

Move that setcookie statement before any HTML appears:

<?php
$value = 'something from somewhere';

setcookie("TestCookie", $value);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
....

PHP - setcookie(); not working ( Cannot modify header information - headers already sent )

<!--Database Connections--> is HTML output, even if it is just a comment. Remove that and try again.

EDIT:
There is also a space between the PHP blocks. Try putting the include in the main PHP block.

php setcookie() not working - Cannot modify header information

In case you have done already HTML output prior the use of setcookie you need to find the place where your HTML output started. Above that line place the ob_start Docs function which will start output buffering.

With output buffering enabled, your program can still "output" HTML but it will not be send immediately. Then you should be able to call setcookie with no problems:

  <?php
function login($username,$pwd)
{
$mysqli=dbconnect(); //no output
$query = "SELECT * FROM `users` WHERE `name`='$username' AND `password`='$pwd'";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
if($result->num_rows == 1) {
while($row = $result->fetch_assoc()) {
ob_start(); //set output buffering before setting cookies..
setcookie("ID", $row['userid'], time()+3600*24*365);
ob_end_flush(); // flush data
if (isset($_COOKIE['UNIQUE_ID']))
{echo 'Connected';}
else{echo 'No cookie today :(';}
}
}
dbclose($mysqli); //no output
}
?>

The output buffer will be automatically send to the browser when your script finishes, so there is not much more you need to care about, the rest works automatically.



Related Topics



Leave a reply



Submit