Header in PHP to redirect the page - php

I want to redirect the page by using tag in the header, but it's not working.

At the top of your page add the following (before any html or php):
<?php
header('Location: http://stackoverflow.com/users/300204/zaf');
exit();
?>
If that redirects you (to the homepage of an awesome programmer) then you need to check that you have not output any content before using this header() function. The header() function needs to be called before ANY content is sent to the user.

Most usual reason of this is "headers already sent" error. Thus, you have 2 problems to solve.
From absence of error message text in your question, I can assume you don't have this text. But it is necessary for the programmer to see every error message occurred. You have to turn display_errors setting on in the developer's environment or peek logs in the production. Also, error_reporting() level must be set to E_ALL.
Application design. Your application must be divided into 2 parts: business logic and presentation logic. First one getting data from the user, from the database, etc.etc. Latter one displays gathered data. Not a single byte must be sent to the browser before presentation logic part get to run. In this case you'll never have such an error.
One exception is BOM - Byte Order Mark, a symbol, being put into your files silently by some editors. Just use "Save without BOM" feature.

You need:
header('Location: http://google.com');
It might not work because you have some php output before the header make sure there are no empty spaces or any characters, or ECHOs outputted before the headers function. Usually it will give an error and you can located where you have this extra space something like "Headers already sent by page on line 1 in index.php"

As some have pointed out, you have to output headers before content. The ideal way to do this is to separate your business logic and presentation logic into different parts, but sometimes you're stuck with legacy code that doesn't do this.
In this situation, PHP's output control functions can be useful; use ob_start() and ob_end_flush() to capture your output then flush it at the end. This allows your code use header() more or less anywhere, e.g.
<?php
function doSomeStuff() {
echo 'look, outputting stuff here';
header('Location: /');
}
doSomeStuff();
?>
The above code will give you the error about headers already being sent, but the following code will work.
<?php
function doSomeStuff() {
echo 'look, outputting stuff here';
header('Location: /');
}
ob_start();
doSomeStuff();
ob_end_flush();
?>
In this case, the output from echo() is not sent until ob_end_flush(), so the header() call works correctly. This approach can be used to wrap legacy code that doesn't properly separate business and presentation logic.

Related

PHP header location not working with clean urls

<?php
$result = mysqli_query($link, $query);
$url=$_SERVER['REQUEST_URI'];
if (!$result) {
$url.="/signup";
header("Location:".$url);
} else {
$url.="/home";
header("Location:".$url);
}
?>
Hello friends I am in a bit problem I am doing a project and using clean urls my htaccess is good everything is going good but after a signup form submission when I want to change header location
php gives an error can't change header location
kindly help
I would post a comment but I dont have enought rep.
Anyway, probably you are seeing error about headers already sent. It is common problem and it have nothing to do with clean urls. what you can do?
1. Make sure you are not outputting anything before header() call
Problem is based on fact how web server and HTTP works. When you are outputting server will send headers and content as soon as it is ready. And you may be outputting even whitespaces, so double check this first.
2. Turn on output buffering
If for any reason you need to output something before headers manipulation, you can turn on output buffering. This way server first "buffers" your data and then sents everything out. Hovewer you are paying in load time for this. Use only rarely, when it is really needed!
You can use a ob_start()for this
If that is your PHP script, I can see whitespaces before <?php tag.
<?php
^^^^--- WHITESPACES
These whitespaces will be written to output buffer even before PHP interpreter kicks in, and when you call header() it will give an error. This is because no output should be sent to client before calling header().

header within html document not working - new server

I moved my documents to a new host and the headers stopped working(refresh,redirect,etc).They used to work in my old server.I have googled and tried adding a ob_start before sending headers, that did not work.
Here is a part of the code...
if(isset($_GET['reflink']))
{
echo '<h3>Already Logged In<h3><p>Please logout before registering an account.Redirecting you back to where you came from...';
header('Refresh: 3; url="http://www.xacnr.com'.$_GET['reflink'].'"');
}
*It used to work before, it must be a problem with the server settings or something :|
A short answer is:
It is not possible to send http headers after the output of anything else.
So if you want to output headers, you must do this at the beginning of your output. To be even more precise: HTTP-Headers must be the first thing of your output, if you have to send them - before anything else.
Please read the documentation:
http://www.php.net/manual/en/function.header.php
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
Please be also aware of the fact that the Refresh-Header is AFAIK not part of the official HTTP-Standard. It's a jurassic artifact from Netscape which will be still accepted and interpreted by most browsers, but this may change even without special notice.
If you need such a refresh and if you want to stay on the safe side, you should consider using the Meta-Refresh within the HTML-Header.
Please read here:
http://en.wikipedia.org/wiki/Meta_refresh
BTW: It's also a bad idea to use unsanitized, unprocessed values from $_GET, $_POST etc. Your example should never be used in any public available environment.
You do an output (echo) before you send the header:
echo '<h3>Already Logged In<h3><p>Please logout before registering an account.Redirecting you back to where you came from...';
header('Refresh: 3; url="http://www.xacnr.com'.$_GET['reflink'].'"');
The simple but strict rule is:
No output before the header!
From the Docs:
Remember that header() must be called before any actual output is
sent, either by normal HTML tags, blank lines in a file, or from PHP.
It is a very common error to read code with include, or require,
functions, or another file access function, and have spaces or empty
lines that are output before header() is called. The same problem
exists when using a single PHP/HTML file.

alternate php redirection method that works with output preceding it

so apparently if you do this:
<?php
echo 'something';
header("Location: http://something/");
?>
it will not work because there is an output preceding the header...
is there any other alternative php redirection method that works straight from php without installing anything and in which it will still work even if there's an output preceding it so that I don't have to worry about making sure that there is no output before, etc...
not, unless you do something in javascript or html tags in the page that you output itself
if preceding output is a problem
you can also use output buffering, see ob_start, ob_get
to get around that
There is no other way to do a php redirect, but you can fool it to still work even with code prior. You would buffer the content and only output it if there is no redirect or reaches the end of the script. Note: this may be resource heavy in some cases.
ob_start()
....CONTENT...
ob_end_flush();
There are no ways in PHP except using header()... before output is sent (headers be already sent)...
You can either use meta refresh in HTML that is set at zero seconds, or javascript.
But I wouldn't recommend javascript as some will have it disabled.
You could use a meta refresh tag.
You understand why this is impossible, right?
As soon as you echo "something" you have sent content to the client, and as part of that client headers were already sent. You can't retroactively modify headers you already sent, and you can't make two responses to one HTTP request.
ob_start() and ob_end_flush() will buffer the output instead of sending it to the client, which will allow you to get around this problem, BUT
a better solution would be to:
separate your logic code from your template so that you don't write anything to the screen until you already know you aren't going to redirect.

PHP: Redirect ( header)

header("profil.php?id=" . $show["id"]);
What i tried to do, but headers are already sent at top, so how can I redirect the user? Should I use window.location.replace("URL"); (javascript) instead?
If you can't control the very beginning of the script, where headers would be sent, then yes, your only method is to use JavaScript.
Also, the proper syntax is header('Location: profil.php?id=' . $show['id']);
You need the Location: part so the browser knows what header it's receiving. Also, don't forget to do an exit() or die() right after the redirect.
Someone correct me if i'm wrong, but I think you can use ob_start() at the beginning of your page and that will allow you to redirect via PHP even if headers are already sent.
You should redesign your application, to make it more sensible.
It should start output only when it necessary, not just every time this file is called.
You have to modify all your code by dividing every script to 2 parts. First part will contain all data manipulations and second will contain output only. It will be better to put the latter one into separate file, called template. thus your profiles php will looks like
include 'dbc.php';
//some code that sends headers, gets data etc
//after it's all done, call your template files
include 'top.php';
include 'profiles.tpl.php';
include 'bottom.php';
there can be some variations, but the main idea would be the same: separate your data manipulation from data presentation.
From the header documentation:
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
The headers are being sent before your call to header() due to output from the script. You just need to track down where the output is coming from.
I see it that you have two options
1) You try to ensure that your headers are not set until after you have executed your code. Your headers being set before you have even determined what you are sending back to the user suggests your code is a little messy, or you are constrained in some way.
2) You can use your javascript solution. However, I would consider this as a hack, rather than an appropriate solution. Try to figure out the answer to why you can't use approach 1.
EDIT: A code example added
Your code should look something like this
<?php
// perform logic to determine if you need to do the redirect or not.
// if you do need to redirect, set the following
$iNeedToRedirect = true;
// if you do not need to redirect, set the following
$iNeedToRedirect = false;
if ($iNeedToRedirect) {
header("Location: profil.php?id=" . $show["id"]");
die();
}
// if code gets here, carry on as normal
include("dbc.php");
include("top.php");
... etc etc etc
?>

PHP / XHTML. Should I place everything in echo tags?

A quick question involving PHP development, I seem to be wondering about this more and more as I develop more complex sites. Basically say we have a basic PHP / XHTML inbox (messaging system). I perform checks at the top (check if user is logged in, check if user has correct permissions etc). Then use the 'header('location:www.abc.com)' function if the authentication fails. The question is do I write the rest of the inbox code in a huge 'else' block or just use standard html. I read somewhere about about it being bad to put any code after using the 'header' function.
Just follow your header with
exit();
Than it won't be a problem.
see third example here
Also you don't need a big echo like that, you can echo html like this aswell if you want:
<?php
//php stuff
if(test){
?>
html here
<?php
}
else{
?>
other html
<?php
}
?>
The reason you read it's bad, is that clients don't have to honor the Location: abc header - so if you keep sending them data they might just show it, perhaps making it possible to snoop on your users data.
What you can do, is after you send the Location: abc header, you simply exit the script, like this:
if(!$user->is_authenticated()) {
header("Location: abc");
exit();
}
After the header redirection, you put a fat "return" or "exit", so your script terminates there, then you close the if. Then you can happily code as you would normally.
It's not true that you should not put anything after a header() call. You should however remember that if you output anything before a header call, the script will fail. There are headers which require you to code on, like the Content-type header. After a redirection header, however you should always put an exit() call, in case the browser doesn't obey the instruction.
I read somewhere about about it being bad to put any code after using the 'header' function.
That's not entirely true, because it's not permitted to send output (HTML or raw output) to the browser, before you send out a header. When you DO send output before you send a header, you'll get a 'Header already sent' error.
After a header function, the rest wont be executed, so a return or exit is not required.
For the question if you need to put everything in an if/else structure: This is also not required, the only thing you have to do is a basic check if some's logged in and if not, you'll perform a redirect using the header function. No need for an extensive if/else structure.

Categories