Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP header redirect not working

Tags:

redirect

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?

like image 384
JasonDavis Avatar asked Aug 06 '09 23:08

JasonDavis


People also ask

Why PHP redirect is not working?

The root cause of this error is that php redirect header must be send before anything else. This means any space or characters sent to browser before the headers will result in this error. Like following example, there should not be any output of even a space before the headers are sent.

How redirect URL in PHP?

Answer: Use the PHP header() Function You can simply use the PHP header() function to redirect a user to a different page. The PHP code in the following example will redirect the user from the page in which it is placed to the URL http://www.example.com/another-page.php . You can also specify relative URLs.

What we can use instead of header in PHP?

PHP redirect without header() The best solution is not to pass headers (send html/output to browser) till the point header() function is fired. Another way is to use output buffering. Without output buffering (the default), your HTML is sent to the browser in pieces as PHP processes through your script.

Can PHP redirect to another page?

In PHP, when you want to redirect a user from one page to another page, you need to use the header() function. The header function allows you to send a raw HTTP location header, which performs the actual redirection as we discussed in the previous section.


2 Answers

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.

like image 96
Mike B Avatar answered Nov 03 '22 00:11

Mike B


Try this (working for me):

echo '<script>window.location.replace("http://www.example.com")</script>';

Instead of

header("Location: http://www.example.com");

like image 39
Umair Sultan Avatar answered Nov 03 '22 01:11

Umair Sultan