I am getting this error:
An error Occured in script '/home/path/to/file/php' on line 35:Cannot modify header information - headers already sent by (output started at /home/path/to/file/to/header.html:7)
I understand that I am getting the error when I try to set a cookie, and I know that the setcookie can't have any output before it... the problem is there, I have to add the include file for database connection and redirection of file. So I have added the setcookie after the include file. I also tried putting the setcookie above the include file, but it doesn't also help.
My Code
<?php # Script 2.5 - main.inc.php 2 3
// Redirect if this page was accessed directly:
if (!defined('BASE_URL')) {
// Need the BASE_URL, defined in the config file:
require('../includes/config.inc.php');
// Redirect to the index page:
$url = BASE_URL . 'index.php?p=vote';
header ("Location: $url");
exit;
}
$vote = new Vote;
//get vote and options data
$voteData = $vote->getVotes();
//if vote is submitted
if(isset($_POST['voteSubmit'])){
$votesData = array(
'vote_id' => $_POST['voteID'],
'vote_option_id' => $_POST['voteOpt']
);
//insert vote data
$voteSubmit = $vote->vote($votesData);
if($voteSubmit){
//store in $_COOKIE to signify the user has voted
setcookie($_POST['voteID'], 1, time()+60*60*24*365); //Error Occurs here
$statusMsg = 'Your vote has been submitted successfully.';
}else{
$statusMsg = 'You cannot vote more than once.';
}
}
?>
//The html form code goes here
I have also tried
setcookie($_POST['voteID'], 1, time()+60*60*24*365, '\');
and
setcookie($_POST['voteID'], 1, time()+60*60*24*365, '\', domainName);
But these also didn't solve my problem.
Also I have created a new file named it as test.php and tested the following code.
<?php
$cookie = 'test';
$cookie_name = "cookieName";
$cookie_value = $cookie;
setcookie($cookie_name, $cookie_value, time() + (86400 * 365));
if((isset($_COOKIE[$cookie_name])) && ($_COOKIE[$cookie_name] != "")) {
echo 'yes';
}
else{
echo 'no';
}
phpinfo();
?>
It prints the yes
And the same code when I tried in my main php file than it displays the error and also prints the yes. I didn't know what's wrong with my code.
I have also tried googling but didn't got any luck.