Do you have a question? Post it now! No Registration Necessary. Now with pictures!
- Posted on
- setting cookie before leaving page
January 16, 2008, 3:16 pm
rate this thread
I've been learning and using PHP for a couple months now,
working on a couple of somewhat different sites.
On one site, I have a page with a form,
and that form includes a couple of ACTION=SUBMIT buttons,
so that clicking either button will immediately reload the page
only with an argument tacked on, e.g. "?size=128" or "?size=256".
This causes some images to be resized,
but otherwise the page appears the same.
I would like to save choice made by clicking either of those two buttons
by setting a cookie on the visitor's computer.
(At least, I *think* that's how I should do it.)
I can put some code at the tippy-top of the page
that looks at the incoming $_GET arg and call setcookie() accordingly.
This really seems like it ought to do the job.
However, what I'm finding is that the cookie does not get set
unless and until the visitor clicks REFRESH in the browser
(or does anything equivalent);
if they don't think to do that, the cookie remains obsolete.
Are my expectations out of whack?
If not, any likely ideas re what I'm doing wrong?
Oh, fine, here's the code:
if ( strcmp( $size_str_fm_get, "small" ) == 0 )
setcookie("size", "small", $time);
elseif ( strcmp( $size_str_fm_get, "large" ) == 0 )
setcookie("size", "large", $time);
(The slightly strange conditional is so that if the value of the $_GET arg
is neither of the expected values, the cookie is not set at all.)
(And, yes, this code is at the very top of the file, *before* any HTML code.)
- Mike Placentra II
January 17, 2008, 3:41 am
Re: setting cookie before leaving page
This is absolutely normal. From the man':
"Cookies will not become visible until the next loading of a page that the
cookie should be visible for."
> if they don't think to do that, the cookie remains obsolete.
Well do it for them; after setcookie(), just do a header('Location: ' .
$_SERVER['PHP_SELF']) and, of course, a die().
Basically, this isn't necessary since you've got the date you need in the
$_GET. However, the refreshing method might be a better solution to avoid
the user to be prompted by his browser to resend the post data if he reloads
the page manually, for whatever reason.
Read about the PRG design pattern.
- Mike Placentra II
January 20, 2008, 7:17 pm