Reputation:
I want to set a cookie but it wont work. Im pretty new in PHP but I searched on the internet how to set a cookie, but it doesn't work.
<div id="content">
<?php
if(isset($_GET['search-item']) && !isset($_COOKIE["searchRequest"])) {
setcookie("searchRequest", $_GET['search-item']);
include 'search_engine.php';
}
else {
$page = $_COOKIE['page'];
if(isset($page)){
require_once $page;
}
else {
require_once 'startpage.php';
}
}
?>
</div>
I really dont know what Im doing wrong :( Can someone help me and explain why this wont work. Everything else works flawlessly
Upvotes: 1
Views: 117
Reputation: 9420
First enable error reporting:
error_reporting(E_ALL);
ini_set('display_errors', 1);
then you should see following:
PHP Warning: Cannot modify header information - headers already sent
Because you cannot output anything before setcookie, and you do here:
<div id="content">
Manual says:
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 and tags as well as any whitespace.
Just move it after you set a cookie:
<?php
if(isset($_GET['search-item']) && !isset($_COOKIE["searchRequest"])) {
setcookie("searchRequest", $_GET['search-item']);
echo '<div id="content">';
include 'search_engine.php';
}else{
echo '<div id="content">';
if(isset($_COOKIE['page'])){
$page = $_COOKIE['page'];
require_once $page;
}else{
require_once 'startpage.php';
}
}
echo '</div>';
?>
And beware : it is not safe to include file that comes from cookie, I hope you just experiment, and it is not a part of serious code.
Upvotes: 3