PHP: Redirect ( header) - php

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
?>

Related

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.

How can I send a user to another url without a header redirect?

I'm learning PHP and been looking for this for a while. What I want to achieve is something like so:
if (true/false) {
go to this url;
}
Every time I search terms like php redirects or php links etc., 99% of the time I get something "headers". I read that header redirects can achieve this but no code can go before it, that it must be first on the page else it wont work.
If that's so, then how can I achieve this?
i read that header redirects can achieve this but no code can go before it. that it must be first on the page else it wont work.
That's wrong. There must be no output before this. Thus you have to ensure, that you don't echo, print, ?>something<?php (or whatever) anything before.
if (true) {
header('Location: ' . $url, false, 302);
exit; // Ensures, that there is no code _after_ the redirect executed
}
You can ready everything about it in the official manual. Especially:
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.
echo '<script type="text/javascript"> document.location = "http://yoururl.com";</script>'
and this will be executed when this part of script is executed.
You can use this if you need some output before the redirect:
header("refresh: $time_in_seconds; url=$your_url);
You still must call this before output is actually sent however. Send the header, then send your output - the page will "redirect" in the time specified.
Disclaimer: I must admit, I'm not sure what the implications of this are and can't find docs on it, so I can't necessarily recommend it - but I can validate that it works.

PHP/HTML/Javascript: Automatically leave page?

I've written a some PHP that interacts with a SQL database and is just around as an intermediate between two pages.
I want a user to automatically be forced to leave that page and move to another (or even a back to previous page function)
What is the easiest way to do this? I'm happy to use PHP, HTML, or JavaScript to do it.
From php you can use the header() function to change the location:
header("Location: newpage.html");
Just be aware that if you're using header, you can't emit any html or whitespace before you make this call unless you're buffering output. Doing so will cause warnings to the effect that headers have already been sent (there is a way to work around this).
To "move" to a page in PHP you can use the header function.
Ex: header('Location: http://www.example.com/');
In PHP I use the following code at the end of a script to move the user to the next page
<?php
// MYSQL SECTION
// PHP SECTION
header('Location: /next.php');
?>
Just make sure you haven't passed any actual HTML in the page before the header code or the script will break with an error that headers have already been sent.
If you script just interacts with SQL database and does not output anything just simply send a redirect header.
<?php
// sql interaction code goes here.
header('Location: /uri/to/secondpage.php');
exit;
?>
from PHP you can call JavaScript by this way
echo "<script>document.location.href = \"yourpage.php\"</script>";
This code wont bother if there any white space or html content before the line.
you can use the php header function
void header ( string $string [, bool $replace = true [, int $http_response_code ]] )
with following example it would be more clear to you.
<html>
<?php
/* This will give an error. Note the output
* above, which is before the header() call */
header('Location: http://www.example.com/');
?>
but there is some limitation with the header function in php
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.
in php
<?php
//the user must leave now
echo"<meta http-equiv='refresh' content='".$time_in_seconds."; URL=abc.com'>";//will move after the time specified,,0 can be specified to move immediately
exit();
?>
in js
window.location="abc.com";//will move immediately,you can time using setTimeout function

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.

Header in PHP to redirect the page

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.

Categories