Page 1 of 1
Which comes first
Posted: Tue Mar 22, 2011 11:38 pm
by Wootah
Hi all,
When putting some php code in a webpage I generally put my php code very first. Is that wise or should I allow doctype information first?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "
http://www.w3.org/TR/1999/REC-html401-1 ... /loose.dtd">
Inside the php code which should come first of session_start, header and includes? I think the current order I have is best.
<php
header(.....);
session_start();
include(....);
?>
Thanks,
Mat
Re: Which comes first
Posted: Wed Mar 23, 2011 1:38 am
by divedj
Some practical considerations:
I would put sesion_start() on top of everything cause than the session is also avilable in your includes!
Next would be INCLUDE() so what ever is needed for further execution is avilable.
And 3. the headers. There you have to make sure they come before an output to the browser is made otherwise they don't work.
Than what ever code is needed before you display your page.
Your html output and what ever php code is needed within.
Somwhere are also some standarts about that I am just to lazy to read

Re: Which comes first
Posted: Wed Mar 23, 2011 10:04 am
by Bind
the exception to the previous posters comment is that when redirecting with header('Location: '.$url) after sessions have been altered and if you need that data on the redirected page or include down the line in the script execution, then you would neeed to use session_write_close() prior to header('Location: '.$url) to preserve the session data, else it would not be accessible until a subsiquent script execution.
Re: Which comes first
Posted: Wed Mar 23, 2011 10:10 am
by pickle
The order you have is definitely best. You can't send headers after output has already been sent - so you need that PHP code before your HTML code starts. If you're doing proper separation of business & display logic, almost all your PHP code should go first - determining actions to take & data to modify, followed by your template output.
Re: Which comes first
Posted: Wed Mar 23, 2011 10:30 am
by Bind
of course sometimes its simply impossible to always follow these rules in which case
php output buffer control, while not ideal, can come in handy.