Midgetlegs
Midgetlegs

Reputation: 35

Cookie Worked Correctly Once, but Now Isn't Set

Edit

Okay, so currently my search page is

<?php

 ...
        while($row = $search->fetch(PDO::FETCH_ASSOC)){
           $result .= "Title: " . $row['comicTitle'];
           $result .= " Issue: " . $row['comicIssue'];
           $result .= " Release: " . $row['releaseDate']."<BR>";

        }
         setcookie('results', $result);

    }

    ?>


    <!doctype html>
    <html>

and my results page is:

<?php 
if (isset($_COOKIE['results'])) {
        echo $_COOKIE['results'];
        }else{
        echo "There are no results to display.";    

}
?>
<!doctype html>
<html>

The results show correctly the first time, but if I go to the search page and search again I get the previous results. Is the echo in my if(isset) statement causing that or something else?


Original Post

I have a variable, $results, that I'm trying to save to a cookie so it can be displayed on a results page.

On the search page, to set the cookie, I use this: setcookie ('resultcookie', $result, time()+300);

On the results page, I use this:

if (isset($_COOKIE['resultcookie'])) {
        echo $_COOKIE['resultcookie'];
        setcookie('resultcookie', "", time()-86400);
    }else{
        echo "There are no results to display.";    

The first time I tried using the page, the results showed up correctly. Now, when I try to search I always get the "There are no results to display." I've tried not unsetting the cookie, so it would write over it but it didn't seem to work. I tried unsetting it with $result in place of "", but that also didn't work. What am I doing wrong?

Upvotes: 1

Views: 48

Answers (1)

Greg Kelesidis
Greg Kelesidis

Reputation: 1054

You can't set a cookie after an echo. It is the same as any other http header. I don't see all of your code, but here

 echo $_COOKIE['resultcookie'];
 setcookie('resultcookie', "", time()-86400);

you don't delete the cookie. This setcookie() fails for sure. Use setcookie() before you output anything from your script, and it will be fixed.

Upvotes: 1

Related Questions