How to handle incorrect URLs?

software development

#1

I don’t know what this is called, otherwise I might have been able to google how to do it.

Basically I want to be able to detect when someone hits a URL that doesnt actually exist. For example, if someone types in

http://www.mysite.com/some_folder_that_doesnt_even_exist/blahblahblah

EDIT: Stupid forum stripped out the actual url that I typed in. Its this:
mysite.com/some_folder_that_doesnt_even_exist/blahblahblah

Then I want to have a PHP script that can catch this and handle it. For example, I might want to direct the above request to a page that DOES exist, like http://www.mysite.com/custom_display.php?query=blahblahblah

Can someone tell me how this would be accomplished ?

Thanks!


#2

It depends greatly on how sophisticated you want to be and how good your programming skills are. You can do it very simply with an .htaccess file by simply checking whether a file exists or not (assuming a static site):

If you have a dynamic site, then you’ll need to add your code to that. If you are working with a framework, it should be quite easy to deal with 404 requests and log them. If you’ve hacked together a site with bits and pieces of PHP, then it will depend on how it all fits together.

It’s impossible to give you a complete answer without knowing much, much more about your current site and what you want to do. You could get some ideas here: http://wiki.dreamhost.com/Mod_rewrite


#3

There’s also the old standby, ErrorDocument.


#4

Thanks to both of you for the responses!

To answer some of the follow up questions:

My programming skills are quite good! My only issue is where to put the code.

RewriteCond %{REQUEST_FILENAME} !-f
What exactly does that do? I guess I need to learn .htaccess syntax because I dont know a thing about it.

FYI my site doesn’t use a framework, its basically my own creation of PHP and html and javascript. So I’m 100% flexible as to what I can do.

andrewf, if your code snippet does what I think it does, then thats perfect!

ErrorDocument 404 /notfound.php

I’m assuming that anytime someone hits a non-existant url, then it will call notfound.php instead? Would the page also receive any GET parameters passed to the URL? If so, thats perfect and exactly what I need! Although, the page wont exactly be an error page, because it will be intended that people will hit this page, but still it accomplishes what I want.

Thanks!


#5

Correct, that’s exactly what it’ll do. However, URL parameters are not passed through “normally” (in $_GET), and the resulting page will always have a 404 status, so search engines will generally treat it as an “error page” and not index it.

If what you’re trying to put together is, in fact, not an error page, mod_rewrite is probably the way to go.