Which comes first

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Wootah
Forum Newbie
Posts: 13
Joined: Wed Jul 14, 2010 7:08 pm

Which comes first

Post 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
divedj
Forum Commoner
Posts: 47
Joined: Wed Dec 29, 2010 4:32 am
Location: Malta

Re: Which comes first

Post 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 :)
Bind
Forum Contributor
Posts: 102
Joined: Wed Feb 03, 2010 1:22 am

Re: Which comes first

Post 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.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Which comes first

Post 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.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Bind
Forum Contributor
Posts: 102
Joined: Wed Feb 03, 2010 1:22 am

Re: Which comes first

Post 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.
Post Reply