PHP header redirect not working - php

I know this has been covered before but I cannot find an answer to this,
I have always used this;
header("Location: http://www.website.com/");
exit();
This has always worked in my current project and all of a sudden it is not working in any of my browsers
I would like to figure out the problem and fix it instead of using
echo "<script type='text/javascript'>window.top.location='http://website.com/';</script>";
I also have error reporting enabled and it shows no errors
// SET ERROR REPORTING
error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE);
ini_set('display_errors', TRUE);
Any ideas why it will not work?

Try:
error_reporting(E_ALL | E_WARNING | E_NOTICE);
ini_set('display_errors', TRUE);
flush();
header("Location: http://www.website.com/");
die('should have redirected by now');
See what you get. You shouldn't use ^ (xor) in your error_reporting() call because you're unintentionally asking for all errors EXCEPT notices and warnings.. which is what a 'headers already sent' error is.
Edit:
Also try putting flush() right above your header() call.

COMMON PROBLEMS:
1) there should not be any output (i.e. echo.. or HTML codes) before the header(.......); command.
2) there should not be a white-space(or newline) before <?php and after ?> tags.
3) GOLDER RULE! - the file (and other include()-d files) should have UTF8 without BOM encoding (and not just UTF-8). That is problem in many cases (because typical UTF8 encoded file has something special character in the start of file output)!!!!!!!!!!!
4) When redirecting, after header(...); you must use exit;
5) Recommended practice - always use 301 or 302 in reference:
header("location: http://example.com", true, 301 ); exit;
6) If none of above helps, use JAVSCRIPT redirection(but it's highly not recommended By Google), but it may be the last chance...:
echo "<script type='text/javascript'>window.top.location='http://example.com/';</script>"; exit;

Try removing the Space Between location and the first h in http.
header("Location: http://www.website.com/");
exit();
turns into
header("Location:http://www.website.com/");
exit();
I had this problem on my WAMP Server.
Although it shouldn't be the problem, considering that is how it is documented in the PHP documentation. But you should probably try it anyway. I know it has worked for me in a number of cases.

try this. worked for me.
echo "<meta http-equiv='refresh' content='0;url=http://www.yoursite.com'>";

Also when you are using the header function it has to be the first thing called before any text (even a space) is written to the client, so check again that there is no spaces being output prior to your call even before th
<?php

It may be strange solution but try this, change the page encoding from utf8 to ANSI and it will work.
use any text editor and save the page as ANSI encoding and upload it to your online server.

Adding ob_start() solved this issue.

Try this (working for me):
echo '<script>window.location.replace("http://www.example.com")</script>';
Instead of
header("Location: http://www.example.com");

What exactly happens when you visit the page? You can try Firebug or any other tool that allows you to analyze HTTP headers and check if the redirect really happens and whether the Location header is really present.

You should also verify that you are redirecting to a valid location, and that the location has proper 404 and 500 error messages/pages setup. It could be that you are simply redirecting a bad place.

Weird, but removing blank lines in php worked for me :-\
code before:
<?php
header("Location: http://www.website.com/");
?>
code that worked:
<?php header("Location: http://www.website.com/"); ?>

If your index page is a html file, it may not work. Change it to index.php and use this code:
<?php
header("Location: http://ea.tc");
?>

I actually had a case similar to this where I had an admin page that was included at the top of all my other pages. At the top of each page below the line:
<?php include '../../admin.php' ?>
I would have the php logic:
<?php if($_SESSION['username'] === null){ header("Location: ./adminLogin.php");}?>
The problem with this was that somewhere else I was also calling/manipulating the header(.... After a lot of time going through my code I admit I could not figure out where the problem was. Then I thought that each of these files hits my admin.php file before doing anything else. So I thought about what would happen if I would put the logic that was at the top of each of my views (because I didn't want anything to be visible unless you were logged in) into my admin.php file?
What happened was that before it even got to any of the php/html in my views it evaluated whether or not someone was logged in ($_SESSION['username'])) and if it was NULL then I just redirected to the adminLogin page. I put this logic right before my switch and it's worked perfectly for all my files that once required the logic. The way I had it worked in development, but posed a lot of issues in production. I found that moving the redirection logic to my admin.php file not only avoided the duplicate header(... manipulation but actually made my code more efficient by removing the excess logic from my view files and into my admin.php file.
Rather than putting the logic in every view file, put it in your controller once, before your switch. Works like a charm! This is useful if you don't want anyone to access any of the sensitive views unless they log in. In my case this was important for my CMS. However, if there are some files that you want to be viewable without logging in then I think the original logic would be sufficient. It seems like you already found a solution but hopefully this can be helpful if you run into this error again. :)

Related

HTML Login form with PHP Authentication [duplicate]

Does somebody know why my header() does not redirect?
The last part of my script is:
header("location: test.php");
die('died');
It writes:
died.
:(((
It should has to redirect before it dies, but it does not.
Do you have you any idea?
It's probably that you're calling header() after you are outputting some text/HTML to the browser, which is a no-no. Your header() call will be ignored if even so much as a single space of output has been sent before the call.
In other words, your header() code needs to be at the start of your script, before you display anything to the user. If that still isn't working, make sure you don't have any spaces or other whitespace by mistake outside of your php tags.
Maybe there is some invisible output before header, which is preventing setting header, and informative warnings are suppressed.
Additionally Location-Headers should contain an absolute URL:
// Show Errors
error_reporting(E_ALL);
ini_set('display_errors','On');
// Redirect
header('Location: http://example.com/path/test.php');
die('redirect');
You should use a fully-qualified address for your location header, and not output any content:
header('Location: http://example.com/test.php');
die();
Additionally make sure that no other content was sent before setting the header, otherwise it wont be sent as the headers will have already been sent to the browser.
location: should be Location:.
Moreover...
Scroll to the top of this page.
Click on your account name.
Click on a random question
Check mark a random answer
Come back to find more serieus answers
Good luck.
Just resolve it by removing ALL things before the php tag.
Remove the SPACE before the php tag
Select all before the tag and then push the erase button.
I was stuck on this error, too, and tried to show errors with error_reporting(E_ALL),
but this didn't worked for me. Info: I was using a hosting service on Strato.
The solution to all this was answered by Floem, thanks for this great setup.
If you ever don't get errors in case you put error_reporting(E_ALL) once in,
-> You must additionally add ini_set('display_errors', 'On'), to force PHP to show all your Errors. This solved my Error issue on
Then it's possible to read out, why PHP wouldn't make your redirect.
One tip on my side: I would recommend you to build a little redirect Class, as shown in this Video: Redirect Class for easy use, if you're going to use this redirect more than usual.
If the file containing the 'header()' instruction is required directly/indirectly in a HTML file, then the instruction {include 'someFile'} should be the first line of that HTML file. Place this instruction on the top of your HTML file, as shown in this image.
Add
ob_start();
before
header("location: test.php");

Php header location redirect not working

No idea why this is not working. Here is the code:
if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
header('Location: page1.php');
echo $_POST['cancel'];
}
Instead of redirecting the page, this output's cancel to the webpage. It skipped over the redirect. Why? How can I fix this? page1.php is a real page located in the same folder as the current page. The above code is the very first lines of the php file. Nothing before it. Nothing. Not even whitespace.
This is likely a problem generated by the headers being already sent.
Why
This occurs if you have echoed anything before deciding to redirect. If so, then the initial (default) headers have been sent and the new headers cannot replace something that's already in the output buffer getting ready to be sent to the browser.
Sometimes it's not even necessary to have echoed something yourself:
if an error is being outputted to the browser it's also considered content so the headers must be sent before the error information;
if one of your files is encoded in one format (let's say ISO-8859-1) and another is encoded in another (let's say UTF-8 with BOM) the incompatibility between the two encodings may result in a few characters being outputted;
Let's check
To test if this is the case you have to enable error reporting: error_reporting(E_ALL); and set the errors to be displayed ini_set('display_errors', TRUE); after which you will likely see a warning referring to the headers being already sent.
Let's fix
Fixing this kinds of errors:
writing your redirect logic somewhere in the code before anything is outputted;
using output buffers to trap any outgoing info and only release it at some point when you know all redirect attempts have been run;
Using a proper MVC framework they already solve it;
More
MVC solves it both functionally by ensuring that the logic is in the controller and the controller triggers the display/rendering of a view only at the end of the controllers. This means you can decide to do a redirect somewhere within the action but not withing the view.
I have experienced that kind of issue before and now I'm not using header('Location: pageExample.php'); anymore, instead I'm using javascript's document.location.
Change your:
header('Location: page1.php');
To something like this:
echo "<script type='text/javascript'> document.location = 'page1.php'; </script>";
And what is the purpose of echo $_POST['cancel']; by the way?, just delete that line if what you want is just the redirection. I've been using that <script> every time and it doesn't fail me. :-)
Use #obstart or try to use Java Script
put your obstart(); into your top of the page
if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
header('Location: page1.php');
exit();
}
If you use Javascript Use window.location.href
window.location.href example:
if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
echo "<script type='text/javascript'>window.location.href = 'page1.php';</script>"
exit();
}
I had also the similar issue in godaddy hosting.
But after putting ob_start(); at the beginning of the php page from where page was redirecting, it was working fine.
Please find the example of the fix:
fileName:index.php
<?php
ob_start();
...
header('Location: page1.php');
...
ob_end_flush();
?>
I had similar problem...
solved by adding ob_start(); and ob_end_flush();
...
<?php
ob_start();
require 'engine/vishnuHTML.class.php';
require 'engine/admin/login.class.php';
$html=new vishnuHTML();
(!isset($_SESSION))?session_start():"";
/* blah bla Code
...........
...........
*/
</div>
</div>
<?php
}
ob_end_flush();
?>
Think of ob_start() as saying "Start remembering everything that would normally be outputted, but don't quite do anything with it yet."
ob_end_clean() or ob_flush(), which either stops saving things and discards whatever was saved, or stops saving and outputs it all at once, respectively.
For me also it was not working. Then i try with javascript inside php like
echo "<script type='text/javascript'> window.location='index.php'; </script>";
This will definitely working.
Pekka answered my question in the comments. He didn't post an answer, so I am now. Use the exit() method after the header redirect. For some reason the rest of the code of the page continues to execute after the header() method redirect. When the rest of the code executes, the echo statement is outputted to the page. And you can't redirect using the header function after you output to the page. To avoid rest of the code from executing, use exit(). Thanks Pekka.
UPDATE: When using the web browser Internet Explorer, I have noticed that $_POST['cancel'] is not reliable. I am not exactly sure why this is, but I suspect IE posts additional variables on a form submit, specifically the variable 'cancel' is posted. I solved this by using a variable name other than 'cancel'. The combination of using exit() and a unique variable name is working for me.
Neer to specify exit code here so php not execute further
if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
header('Location: page1.php');
exit(0); // require to exit here
}
Try adding
ob_start();
at the top of the code i.e. before the include statement.
Make Sure that you don't leave a space before <?php when you start <?php tag at the top of the page.
Be very careful with whitespace and other stuff that may affect the "output" already done. I certainly know this but still suffered from the same problem. My whole "Admin.php"-file had some spaces after the closing php-tag ?> down the bottom on the last row :)
Easily discovered by adding...
error_reporting(E_ALL);
...which told me which line of code that generated the output.
Try this, Add #ob_start() function in top of the page,
if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
header('Location: page1.php');
exit();
}
Use the following code:
if(isset($_SERVER['HTTPS']) == 'on')
{
$self = $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
?>
<script type='text/javascript'>
window.location.href = 'http://<?php echo $self ?>';
</script>"
<?php
exit();
}
?>
put < ?php tag on the top of your file (starting on frist line of document)
not:
--- Blank space or something ---
<?php
but:
<?php
..your code
header('Location: page1.php');
...

redirection in a required page in php

I have two scripts get.php and auth.php where i 've required auth.php in get.php, so here's the deal the redirection statement in auth.php i.e, header() is not working for some reason, any quick thoughts on this problem if this can be achieved or not??
As per my understanding, your problem is that:
header("location:[XYX.PHP]") is not working.
It generally does not work due to some output is print already on the page.
Please use
ob_start();
at very the beginning of the page.
This starts output buffering.
And the redirection works.
header("Location: $URL") may not work if you already sent headers by some echo, print_r or similar function.
Look at your web server error logs, does it mention something like "headers already sent" ? If yes that means you're probably outputting something before your header() function call
get.php
<?php include_once("auth.php"); ?>
auth.php
Redirect using the code below which is based on the example found at http://php.net/manual/en/function.header.php.
<?php header("Location: http://www.stackoverflow.com/"); ?>
If it still doesn't work, make sure (like it says on http://php.net/manual/en/function.header.php) that you are not outputting any html or even blank spaces or before calling the header() function. (Perhaps your get.php page is outputting empty space or HTML tags before including auth.php.)
you can use javascript function for this task
echo "window.open(url1, "name1", params);";

PHP header redirect not working on production, blank page

I am about to throw the towel in. Can somebody help me figure this out.
On my local dev server this bit of PHP works fine, its just doing a redirect by constructing a url out of some variables. So I get redirected to this page as expected.
$status = "0"; //unsubscribed
header('Location:http://www.skandium.com/manage-your-mailing-list.asp?status='.$status);
die();
On the production server I just get a blank page. I know the PHP page itself is working because all other things that happen upto and before this line work fine. I can replace this line with a simple echo and can see the URL is correct also.
Other details:
Hosted on a windows box (dev is also windows)
same PHP version running via FASTCGI
EDIT: the plot thickens
The following code on its own in a new page works fine on production. Still doesn't explain why the above code works locally and not on production. All I seemed to have ruled out is that the header redirect statement by itself is not the culprit.
<?php
//test.php
//prevent page caching
header("Cache-Control: no-cache");
header("Expires: -1");
$status = "0"; //unsubscribed
header('Location:http://www.abc.com/manage-your-mailing-list.php?status='.$status);
die();
?>
Make sure there is no whitespace before php tag
A few thing you can try is:
Check if headers_sent() is true before sending the redirect header
Set error_reporting(E_ALL) and ini_set('display_errors', 1)
Use firebug to check what (if any) headers are being sent to the browser
Try this..
header('Location: http://www.abc.com/manage-your-mailing-list.php?status='.$status)
I just add a space between colon(:) and the url..
I don't know this happened to others, but sometimes this kind of things happened to me and sometime this works for whatever reasons..
Also, have you tried relative path?
or at other pages, i mean does "header location" works on other places?
or it happens on this script only?
Is the file UTF-8 encoded? Any output can prevent the code to be executed, including a BOM. Maybe the encoding was not explicitly set, but your dev machine assumed UTF-8 (and ignored the mark) while your production server didn't.
None of these worked.
I ended up echoing a meta redirect.
I could also have echoed a javascript location.replace

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