Reputation: 110
Well guys, this is my very first time over here, so, hi community.
I'm working in a small school project which requires that I set 2 different cookies (one for saving an Username and other for changing the background color), and as the question title says, it is restricted to PHP only, so I'm constantly receiving: \"Cannot modify header information – headers already sent". So, i'm trying to make this work.
<?php
setcookie('name', $_REQUEST['name'], time()+60*60);
setcookie('color', $_REQUEST['color'], time()+60*60);
header("location:name_of_the_web");
?>
So, in my Index page, I asked for both of the request info, color and name.
<?php
echo "<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>Temario</title>
</head>
<body>";
if(!isset($_COOKIE['name']) && !isset($_COOKIE['color'])){
echo "<form method='post' action='cookies.php'>
...//it keeps going with the form to fill it.
?>
I wonder if there is any other way to ask for both of the cookies at the time? OR if that is wrong? OR what I may be doing wrong so it sends me the header modification error?
Thx.
Added: I just found that the mistake shows up when I'm using both of the \setcookies(args);\ when I'm using only one of them it runs ok, so, may I request the cookies changes in different moments? For instance saving the username in the Index and afterwards changing the background color?
Upvotes: 1
Views: 103
Reputation: 336
So you are recieving "Cannot modify header information – headers already sent". This is an error causes in php page if output from .php file is already printed on the page before header modification.
Example If you try to do something like
<?php
echo "hello";
header("location: anotherPage.php");
?>
Or
<h1> hello <h1/>
<?php
header("location: anotherPage.php");
?>
Then you will get that error in both the cases. Because echo statement has printed something on the screen before the header() call.
So you just have to keep in mind nothing should get printed on the page before header() call.
Else your code is perfect
<?php
setcookie('name', $_REQUEST['name'], time()+60*60);
setcookie('color', $_REQUEST['color'], time()+60*60);
header("location:name_of_the_web");
?>
Just keep in mind not to print anything on the page neither from html nor from php on same .php file.
You can use forms to go run another php page from current page and then set cookies and header back to the same or another page. This will not cause that error. ☺
Upvotes: 1