Welcome to WebmasterWorld Guest from 54.167.86.211

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

header redirect question using 404 status code

     
3:36 pm on Jul 19, 2012 (gmt 0)

Junior Member

joined:June 16, 2011
posts: 79
votes: 0


When using a 302 Status code, the below code works, but when I change it to a 404, it does not work....is there something different that needs to be done to redirect to a 404 page and give that HTTP response?

This works:
die(header("Location: /404.php", true, 302));

This does not work:
die(header("Location: /404.php", true, 404));

Thanks for the help!

[edited by: tec4 at 4:02 pm (utc) on Jul 19, 2012]

3:45 pm on July 19, 2012 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Apr 15, 2003
posts:904
votes: 5


Try:

header("Location: /404.php, true, 404);
echo file_get_contents('/404.php');
die();
4:15 pm on July 19, 2012 (gmt 0)

Full Member

joined:Mar 22, 2011
posts:339
votes: 0


It doesn't work because 404 is not a valid response code for redirects. The browser sees the 404 response code and just stops there.

You want to do something like this:

<?php

header( 'HTTP/1.1 404 Not Found' );
include( $_SERVER['DOCUMENT_ROOT'] . '/404.php' );
die();

?>

Adjust the path to
404.php
as necessary.

-Ryan

[edited by: rlange at 4:29 pm (utc) on Jul 19, 2012]

4:18 pm on July 19, 2012 (gmt 0)

Junior Member

joined:June 16, 2011
posts: 79
votes: 0


That's working to yield the desired 404 response, but file_get_contents() reads the contents of a file into a string so instead of giving a functional web page (the page I'm trying to fetch is a PHP page) it renders the actual php code into the page source code.
4:44 pm on July 19, 2012 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Apr 15, 2003
posts:904
votes: 5


Use rdlange's code so that the 'file' is actually a URL and will be parsed by the server and not just have the source echoed (the way mine did. I copied some of my existing code).
5:36 pm on July 19, 2012 (gmt 0)

Junior Member

joined:June 16, 2011
posts: 79
votes: 0


Oh...well guess that would make for a good reason...lol.

Works great :) Thanks you both for the help!
5:59 pm on July 19, 2012 (gmt 0)

Senior Member

WebmasterWorld Senior Member g1smd is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:July 3, 2002
posts:18903
votes: 0


So to summarise, you should not "redirect to a 404 page". Doing that does not return a 404 response.

Instead, you send a 404 header to set the status, then send a page of html code and content by 'including' it. All this happens at the originally requested URL.
6:45 pm on July 19, 2012 (gmt 0)

Junior Member

joined:June 16, 2011
posts: 79
votes: 0


Ya, it's making a LOT more sense now!
 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members