homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

header redirect question using 404 status code

 3:36 pm on Jul 19, 2012 (gmt 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 Jul 19, 2012 (gmt 0)


header("Location: /404.php, true, 404);
echo file_get_contents('/404.php');


 4:15 pm on Jul 19, 2012 (gmt 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:


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


Adjust the path to
404.php as necessary.


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


 4:18 pm on Jul 19, 2012 (gmt 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 Jul 19, 2012 (gmt 0)

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 Jul 19, 2012 (gmt 0)

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

Works great :) Thanks you both for the help!


 5:59 pm on Jul 19, 2012 (gmt 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 Jul 19, 2012 (gmt 0)

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

Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved