Leading Zero - Return 404 Page

Hello all,

I looking for how to implement a redirect to 404 page if anyone manually will mistype URL. For example:

Correct URL

Wrong URL

      if ($articles['article_id'] = '0') {
        header("Location: /404.shtml");

Definately, I’m wrong. Please help me.

Why show a 404, why not redirect them to the correct page? Much more user frienly and easy to do.

You didn’t specify if you are using any rewriterules or something for your website, so I’ll assume /article-12 will cause $_GET[‘article_id’] to be 12.

if (ctype_digit($_GET['article_id']) && substr($_GET['article_id'], 0, 1) == '0') {
  header("Location: /article-".((int)$_GET['article_id']), true, 301);

If you try converting the string to an int, it will drop the leading zeros.

$article_id = (int)$articles['article_id'];

It will return a 0 if the string is not an int.

Thank You So MUCH!!!

I rewrote it a little bit, it works. Please check if here any coding mistakes

  if (ctype_digit($_GET['article_id']) && substr($_GET['article_id'], 0, 1) == '0') {  
	header("Location: /404.shtml", true, 301);

Why are you still redirecting to 404 if you know the article the visitor is looking for? (namely the article with the leading zero’s chopped off)

Now you’re doing a 301 redirect to a 404 page. That just sounds… wrong :shifty:

In case you didn’t know, if you do a 301 redirect from article-0012 to article-12

  1. The URL in the urlbar of the users browser will change to article-12
  2. Google will ignore article-0012 and give all the juice (in case some else linked to it by accident) to article-12

Yes, you are right that it will be better to redirect to the original page but it involves a lot of other variables in the URL link. I have to play with them.

If I won’t find a way how to do that, at least I got what will prevent a creation of a duplicate content if someone intentially will type those zeros in a middle of the long string.

I very appreciate you as well as the SitePoint. Thank you again!!! :slight_smile:

To send a 404 you do not redirect to a 404 page. You send a 404 HTTP Status. DO NOT USE “Location” WITH 404 HANDLING.

header( "HTTP/1.1 404 Not Found" );
header( "Status: 404 Not Found" );

// Put 404 content here.