Global include with output plus headers

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
SirChick
Forum Contributor
Posts: 125
Joined: Tue Jul 31, 2007 11:55 am

Global include with output plus headers

Post by SirChick »

I have a problem... i wanted to make a global include which contained the html menu for every page as the layout is same through.

So i put it into my current include which carries sessions of the user ID and connection to table/database.
But this means i have to have this as the first line in the script because of the connection plus session.

Which means i cannot do any headers if output of the html menu has already begun prior to the header location part of my php.. how can i get around this?

The headers i put inside if statements so they will only happen when the user does something yet it still produces the problem when the page loads straight away...
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Post by s.dot »

You should process the actions before your HTML is called, that way no headers are sent until you send them. If you change locations perhaps on a form submission, a popular solution is to use what's called the POST-REDIRECT-GET pattern. You post the form to a separate script, process it, and then redirect to the appropriate url with appropriate values. The end user never sees the intermediate page and you avoid having to process a script inside of HTML and having headers already sent issues.

Example:

page1.php

Code: Select all

<?php

if (!empty($_GET['message']))
{
    echo '<p>' . $_GET['message'] . '</p>';
}

?><form action="someSeparatePage.php" method="post">
<input type="text" name="name" size="20" />
<input type="submit" value="submit" />
</form>
someSeparatePage.php

Code: Select all

<?php

if (!empty($_POST))
{
    //process form data
    //redirect back to page
    header('Location: page1.php?message=thank%20you');
    exit;
}
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
Post Reply