Jump to content
Larry Ullman's Book Forums

Recommended Posts

Probably a very silly question to a knowledgeable person, but still:

 

I know nothing should be sent to a browser before header() is sent there.

 

I also know that nothing should be sent to a browser before a cookie is set.

 

What if I need a header AND a cookie on the same page?

 

Would they interfere with each other? Should a cookie be set before a header, or vice versa?

 

Thanks in advance for your help!

Link to comment
Share on other sites

Hmm... Thank you very much for the prompt reply, HartleySan, but why do I have a feeling you're sending mixed messages?

 

You're saying the order doesn't matter - and yet you're also saying that any number of PHP operations can be performed before setting a header...

 

Does that mean, that a cookie should come before the header?

Link to comment
Share on other sites

He said output, as in using print, echo or displaying HTML. To explain WHY, the server can use the header() call to set content type. For that reason, you cannot call header() once anything is displayed. To illustrate the point, this would not work:


<?php
header(); // Some call here
?>

 

Notice the line break before the PHP tag? That is considered content. Therefor, it won't work. BEFORE you output anything to the browser, the header call can appear anywhere.

  • Upvote 1
Link to comment
Share on other sites

Thank you Antonio!

 

But that wasn't what I was asking, actually. I totally understand the idea that no output comes before the headers.

 

But my question is: can 1) a cookie be set after the header(s), or 2) should setting of the cookie be done before the header(s), or 3) it truly doesn't matter as long as both the cookie(s) and the header(s) are declared before anything is output to the browser?

 

As I said from the beginning, it's a silly question, but I'm genuinely confused about that topic.

Link to comment
Share on other sites

Number 3 is correct.

 

Nothing to get confused about. Calling cookie() is nothing more serious than starting a session and adding a key => value pair. header() can even be called inside your own functions, or be applied login to.

 

Don't over complicate things here. If you are in doubt, do a quick test. It takes less time and will give you confidence. Sometimes brute-forcing solutions is a good thing. ;)

  • Upvote 2
Link to comment
Share on other sites

 Share

×
×
  • Create New...