Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP header( "Location: /404.php", true, 404 ) does not work

I'd like to use the following to redirect pages that are no longer present in the database to the custom 404 page:

ob_start();
....
if ( !$found ):
  header( "Location: /404.php", true, 404 );
  exit();
endif;

But this actually does not redirect, but just shows an empty page (because of the exit() call before any output to the browser).

I've also tried the following:

if ( !$found ):
  header( "HTTP/1.1 404 Not Found" );
  exit();
endif;

With a 'ErrorDocument 404 /404.php' in my .htaccess file, but this also just shows an empty page.

And if I do this:

if ( !$found ):
  header( "HTTP/1.1 404 Not Found" );
  header( "Location: /404.php" );
  exit();
endif;

It does redirect, but with a 302 header.

Any help would be greatly appreciated.

like image 763
Vivienne Avatar asked May 26 '11 16:05

Vivienne


People also ask

Why my header is not working in PHP?

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.

Can a 404 page be PHP?

php file, you can create one as a simple HTML file with a . php extension and then upload it to your site's theme directory. Any time a 404 error occurs, WordPress will serve up this 404. php page to the user.

Where is header located in PHP?

PHP Header Location In order for your PHP redirect to be successful, the header() function must execute — and before any output is sent. This is why your code must appear above the <! DOCTYPE html> or <html> tags in your index. php file.


2 Answers

I've tried and make sure to check error_log file that is correct way is send 404 headers and then include error page to next line.

<?php
header('HTTP/1.1 404 Not Found');
include 'search.php'; // or 404.php whatever you want...
exit();
?>

Finally you have to use exit() for text based browsers.

like image 78
Aydın Antmen Avatar answered Sep 20 '22 18:09

Aydın Antmen


I know it's a old issue but I just found it handy:

php set status header to 404 and add a refresh to correct page, like a 2 seconds after.

header('HTTP/1.1 404 Not Found');
header("Refresh:0; url=search.php");

Then you have the 404 page showing up a few second before redirecting to fx search page.

In my case, Symfony2, with a exception listener:

$request  = $event->getRequest();
$hostname = $request->getSchemeAndHttpHost();
$response->setStatusCode(404);
$response->setContent('<html>404, page not found</html>');
$response->headers->set('Refresh', '2;url='.$hostname.'/#!/404');

time ( 2) can be 0.2 if you wish very short time.

like image 37
Jacob Christensen Avatar answered Sep 16 '22 18:09

Jacob Christensen