Archive

Posts Tagged ‘headers’

Sending headers

February 7th, 2008 No comments

There are many reasons to send headers in the middle of you PHP script. Sometimes you want to redirect the user based on some computed information or display different content types (mime-type). Have you ever had a problem with PHP complaining about “output already sent”?

To solve this problem, there is a workaround with ob_start/ob_flush. As pointed out in a past comment, you can put ob_start in the beginning of the script and ob_flush at the end, thus preventing any output before the script finishes executing.

A more neat solution (in my opinion) is to review your output approach. You should not send any output before you are absolutely sure about it (why would you sent kilobytes of HTML if you’re going to redirect anyway?). My approach is to store output in a variable or a class and then send it when ready. I also try to limit html generation until after I processed my GET/POST requests.

Tags: , ,

Refresh form but do not resubmit (PHP)

September 2nd, 2007 4 comments

This question has been asked so many times that most of you don’t want to hear it again. Unfortunately, the solutions that people are proposing are less than ideal.

For those who are new to the concept, a quick explanation is in order. You have a form that you display, validate and act upon (send e-mail, save to database, upload files, etc.) Once this is done, the user might refresh the page and you will end up with duplicate entries.

Bad ideas to handle it are: splitting into multiple files to work around this problem, using the meta-refresh tag, setting unique identifiers and store them in session or in hidden fields, checking for duplicates after resubmission, using javascript…
If you want to know why they are bad, just post a comment and I will give you a detailed explanation of the particular case.

I found a quick and neat way to do it (perhaps I’m not the first, but I feel the need to share it). Append “?submit=true” to your form action and use header(“Location: …”) with the current URL. Thus, once form data has been saved, you will be redirected to the same page without the POST variables. If PHP complains that output was already sent, then you have a bad approach for your output. I usually store all my output in a variable(s) and echo it when everything is okay. More on output in another entry.

Tags: , ,