14 Replies - 2093 Views - Last Post: 04 March 2011 - 02:55 PM Rate Topic: -----

#1 Merddin  Icon User is offline

  • New D.I.C Head

Reputation: 12
  • View blog
  • Posts: 37
  • Joined: 19-February 10

Best Location for PHP header()

Posted 02 March 2011 - 03:26 PM

Hello,

I was playing around with some PHP code and noted that in my version (5.3.0) I could place a header() call or a session_start() anywhere in the page and it would work. However, everything that I have read seems to indicate that this shouldn't be the case and that those calls need to be the absolute first thing in the document. Is this something that has changed? If so, what is considered the best practice for placing these items?

Thanks everyone

Is This A Good Question/Topic? 1
  • +

Replies To: Best Location for PHP header()

#2 codeprada  Icon User is offline

  • Changed Man With Different Priorities
  • member icon

Reputation: 948
  • View blog
  • Posts: 2,357
  • Joined: 15-February 11

Re: Best Location for PHP header()

Posted 02 March 2011 - 06:06 PM

It's best to place it at the very top but it's not a requirement. An include is simply placing the code from a file in the place where it is called. It's best to place it at the tmr because if you do make session calls or to functions in another file before you use session start or an include you're going to run into some very serious problems
Was This Post Helpful? 2
  • +
  • -

#3 Valek  Icon User is offline

  • The Real Skynet
  • member icon

Reputation: 543
  • View blog
  • Posts: 1,713
  • Joined: 08-November 08

Re: Best Location for PHP header()

Posted 02 March 2011 - 06:08 PM

Additionally, if you try to use header() or session_start() after anything is sent to the browser, the function call will fail and it'll spit out that dreaded 'headers already sent' error.
Was This Post Helpful? 3
  • +
  • -

#4 creativecoding  Icon User is offline

  • Hash != Encryption
  • member icon


Reputation: 928
  • View blog
  • Posts: 3,212
  • Joined: 19-January 10

Re: Best Location for PHP header()

Posted 02 March 2011 - 06:25 PM

I've seen headers mostly use to redirect, but if you can't in the case of "headers already sent", you can just use an HTML redirection. It's a little more sloppy but works if the headers have been sent and you can time it.
Was This Post Helpful? 1
  • +
  • -

#5 Valek  Icon User is offline

  • The Real Skynet
  • member icon

Reputation: 543
  • View blog
  • Posts: 1,713
  • Joined: 08-November 08

Re: Best Location for PHP header()

Posted 02 March 2011 - 06:27 PM

Downside of HTML redirection (also known as meta refresh) is it's deprecated, if memory serves, so I would recommend avoiding it if at all possible.

This post has been edited by Valek: 02 March 2011 - 06:28 PM

Was This Post Helpful? 2
  • +
  • -

#6 creativecoding  Icon User is offline

  • Hash != Encryption
  • member icon


Reputation: 928
  • View blog
  • Posts: 3,212
  • Joined: 19-January 10

Re: Best Location for PHP header()

Posted 02 March 2011 - 06:33 PM

View PostValek, on 02 March 2011 - 06:27 PM, said:

Downside of HTML redirection (also known as meta refresh) is it's deprecated, if memory serves, so I would recommend avoiding it if at all possible.


Didn't know that, thanks.
Was This Post Helpful? 0
  • +
  • -

#7 Merddin  Icon User is offline

  • New D.I.C Head

Reputation: 12
  • View blog
  • Posts: 37
  • Joined: 19-February 10

Re: Best Location for PHP header()

Posted 02 March 2011 - 07:12 PM

Thanks everyone for the replies.

I'm still a bit confused however. My code ran fine (on my localhost) with the header() function appearing after HTML; which should imply that PHP sent a default header already. Is this just because I'm running on localhost or has PHP changed when the default header is sent in later versions?
Was This Post Helpful? 0
  • +
  • -

#8 Valek  Icon User is offline

  • The Real Skynet
  • member icon

Reputation: 543
  • View blog
  • Posts: 1,713
  • Joined: 08-November 08

Re: Best Location for PHP header()

Posted 02 March 2011 - 07:30 PM

Headers are sent the moment any output is sent to the browser. Question is, did that HTML actually get output to the browser before PHP hit the header() call, or was it in part of a conditional that didn't activate during that pass? It's not the order it appears in the file, it's the order it's sent to the browser.
Was This Post Helpful? 1
  • +
  • -

#9 Merddin  Icon User is offline

  • New D.I.C Head

Reputation: 12
  • View blog
  • Posts: 37
  • Joined: 19-February 10

Re: Best Location for PHP header()

Posted 02 March 2011 - 09:07 PM

Here is one of the pieces I am talking about:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
	
<html xmlns="http://www.w3.org/1999/xhtml">

<head>

  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
		
  <title>Number Guessalicious</title>
		
</head>
	
<body>

  <?php
    if (isset($_POST["guessNum"])) {
      $numToGuess = $_POST["guessNum"];
    } 
    else {
      $numToGuess = rand(1, 100);
    } 
			
    if (isset($_POST["numTries"])) {
      $numTries = $_POST["numTries"] + 1;
    } 
    else {
      $numTries = 0;
    }
						
    if (!isset($_POST["guess"])) {
      $message = "Welcome to the Guessing Machine";
    } 
      else if ($_POST["guess"] > $numToGuess) {
      $message = $_POST["guess"]." is too big! Try a smaller number.";
    } 
    else if ($_POST["guess"] < $numToGuess) {
      $message = $_POST["guess"]." is too small! Try a larger number.";
    } 
    else {
      header("Location: win.html"); // Here is the line in question
    }
  ?>



So, the header line (line 41) appears near the bottom of this snippet after all of the preceding HTML that is outside of php delimeters. Based on the consensus in this posting and everywhere else it seems, I should have received an error; however, I successfully get redirected to page win.html.

Once again, thank you everyone for your help

[edited to add in line number location of header call]

This post has been edited by Merddin: 02 March 2011 - 09:08 PM

Was This Post Helpful? 0
  • +
  • -

#10 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6110
  • View blog
  • Posts: 23,670
  • Joined: 23-August 08

Re: Best Location for PHP header()

Posted 03 March 2011 - 05:07 AM

Did you move your code from your local machine to another host? If so, then obviously there is a difference in configuration. Perhaps your local install has output buffering turned on, which would allow HTML to appear before the headers, and the host does not.
Was This Post Helpful? 2
  • +
  • -

#11 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5937
  • View blog
  • Posts: 12,862
  • Joined: 16-October 07

Re: Best Location for PHP header()

Posted 03 March 2011 - 05:50 AM

Headers have to come first. Well, they have to be sent first, but thinking of them coming first avoids confusion.

If you have conditions that might send you elsewhere, then do them before you even think about sending page markup. In your example, it doesn't hurt to do work first. I'm actually confused why you'd stick that code in the body of markup.

e.g.
<?php

$numToGuess = isset($_POST["guessNum"]) ? $_POST["guessNum"] : rand(1, 100);
$numTries = isset($_POST["numTries"]) ? $_POST["numTries"] + 1 : 0;
					
if (!isset($_POST["guess"])) {
	$message = "Welcome to the Guessing Machine";
} else if ($_POST["guess"] > $numToGuess) {
	$message = $_POST["guess"]." is too big! Try a smaller number.";
} else if ($_POST["guess"] < $numToGuess) {
	$message = $_POST["guess"]." is too small! Try a larger number.";
} else {
	header("Location: win.html"); // Here is the line in question
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="content-type" content="text/html; charset=utf-8" />
	<title>Number Guessalicious</title>
</head>
	
<body>
<?php echo $message; ?>



Though, considering you're just doing a redirect, there's no reason you couldn't just include the win condition in the page.

<?php
if (!isset($_POST["guess"])) {
	showWelcome();
} else {
	$guess = $_POST["guess"];
	$numToGuess = isset($_POST["guessNum"]) ? $_POST["guessNum"] : rand(1, 100);
	$numTries = isset($_POST["numTries"]) ? $_POST["numTries"] + 1 : 0;
	if ($guess==$numToGuess) {
		showWinner();
	} else {
		showNextTry();
	}
}


This post has been edited by baavgai: 03 March 2011 - 05:50 AM

Was This Post Helpful? 3
  • +
  • -

#12 RudiVisser  Icon User is offline

  • .. does not guess solutions
  • member icon

Reputation: 1004
  • View blog
  • Posts: 3,562
  • Joined: 05-June 09

Re: Best Location for PHP header()

Posted 03 March 2011 - 06:42 AM

Headers don't have to come first if you're using output buffering.

Your local copy probably has automatic output buffering enabled, which is why it won't throw an error. Either that, or you have errors disabled!
Was This Post Helpful? 3
  • +
  • -

#13 Merddin  Icon User is offline

  • New D.I.C Head

Reputation: 12
  • View blog
  • Posts: 37
  • Joined: 19-February 10

Re: Best Location for PHP header()

Posted 03 March 2011 - 07:36 AM

Thanks baavgai, that makes more sense. The reason for the redirect was actually just to play with redirects. Your modifications to the code are excellent, I will have to review those.

RudiVisser I do have output buffering turned on, so that solves that mystery. My error messaging is also enabled which is why I was confused as to why I wasn't getting any errors for doing something that was supposedly not possible. I wasn't aware of the output buffering option.

Thanks to everyone for their help
Was This Post Helpful? 0
  • +
  • -

#14 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10816
  • View blog
  • Posts: 40,316
  • Joined: 27-December 08

Re: Best Location for PHP header()

Posted 03 March 2011 - 09:21 PM

Also, always good practice to separate your HTML and PHP into separate files. Mixing the two is a recipe for disaster. You can either include/require the HTML, or do something like read it in possibly via file_get_contents(), modify the HTML accordingly, then output. It makes it easier to maintain both your design and your web application this way. CTphpnwb has an excellent tutorial you might want to check out. :)
Was This Post Helpful? 1
  • +
  • -

#15 Thresh  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 04-March 11

Re: Best Location for PHP header()

Posted 04 March 2011 - 02:55 PM

It depends entirely on what your 'header.php' is trying to do. If you make it output things like the DTD and HTML and HEAD tags, then yeah, you're going to run into 'headers already sent' issues. BUT, if you make your header.php simply a place where includes are included, and header-related functions are defined, then you're going to have a much easier time of it. For many of my sites, the title & meta description & meta keyword tags and other things that go in the header area will change based on what's going on - search results, etc., and you want to be able to vary those things from within one common function. To do that, you'll want to be able to pass information to functions inside your header.php file. So, my own personal rule of thumb is: Don't have your header.php file echo anything. Have it define functions that you can use later to output to the browser.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1