|
-
Jul 18th, 2009, 09:38 AM
#1
Thread Starter
Lively Member
Header and page redirection
On the top of page, even before html tags are open, I have placed script to check for sessions. Later in the page according to the user submitted options, user is redirected to different pages using header.
PHP Code:
switch($rsl){
case "A":
header("location: pagea.php");
break;
case "B":
header("location: pageb.php?");
break;
case "C":
header("location: pagec.php?");
break;
default:
header("location: paged.php?");
}
This works perfect in wampserver on my system. But on the web server, I get an error that header has already been sent.
Should I include this code on top of the page, but remember the page direction should occur only after user makes some selections.
Save trees, avoid plastics, say no to zoo, go veg, recycle as much, live holistic
-
Jul 18th, 2009, 11:55 AM
#2
Re: Header and page redirection
The difference between your servers may be that your local setup has output_buffering turned on by default. header() doesn't work if you've already sent output to the client, but output buffering prevents output from being sent (aside from headers) until you explicitly tell it to, or the end of the script is reached.
You can turn on output buffering for a single page with ob_start(). So, for example, the following use of header() will fail because "headers have already been sent":
Code:
<?php
echo "Hello World.";
header("Location: http://www.example.com");
?>
But the following header() will work:
Code:
<?php
ob_start();
echo "Hello World.";
header("Location: http://www.example.com");
?>
-
Jul 18th, 2009, 01:40 PM
#3
Thread Starter
Lively Member
Re: Header and page redirection
Got it, thanks!
Assume that the output buffering is turned on using ob_start(), should the headers for redirection be declared before any html output? I mean can we use header anywhere in the page within html body?
Save trees, avoid plastics, say no to zoo, go veg, recycle as much, live holistic
-
Jul 18th, 2009, 03:54 PM
#4
Re: Header and page redirection
If you use ob_start(), you can use header() anywhere - before or after any HTML. Be careful not to do this, though:
Code:
<?php
ob_start();
?>
<p>Some html.</p>
<?php
header("Location: http://www.example.com");
?>
This won't work because the first line of the file is whitespace, which counts as output. If you get rid of that first line though, this example would work fine.
EDIT: It got rid of my whitespace line. :/ Well, imagine there's a line of whitespace prior to the "<?php" line
-
Jul 19th, 2009, 03:25 AM
#5
Thread Starter
Lively Member
Re: Header and page redirection
Thanks,
I chose to use the header redirect before outputting any html.
Save trees, avoid plastics, say no to zoo, go veg, recycle as much, live holistic
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|