PHP redirect without modifying URL

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
captainash
Forum Newbie
Posts: 1
Joined: Thu May 08, 2008 5:25 am

PHP redirect without modifying URL

Post by captainash »

This has taken me a long time to figure out, so I thought I'd pass it on, hopefully it'll save someone else the same problems.

I was after a way to create a custom 404 page, that would redirect the user without changing the URL address bar. For example, if someone entered www.mysite.com/articles/php_rocks, and I was using the header() function to redirect to index.php?id=1, the user would see the right page, but the URL address would be changed.

I wanted the same effect, but without the URL rewrite, so the user would still see the php_rocks URL, while the browser displayed the content from the index.php?id=1 page.

The first step is to edit the .htaccess file to include the line ErrorDocument 404 /not_found.php

You then need to write a not_found.php that looks through the supplied URL string to search for certain identifiers. In my case, the word /articles/. Having identified that, the rest of the string (eg 'php_rocks') is used to search the database for an article with the same name. If it finds it, the user can then be redirected.

Here's the problem I had ... you can't supply variables into include(), which means include("index.php?id=1") won't work. You can, however, do the following

Code: Select all

$_GET['id']=1;
include("index.php");
You then need to check that index.php identifies the value of $_GET['id'] and you're all set.

The next problem I found was that any calls to include() from index.php were being ignored, as the script was attempting to run them from the imaginary /articles/ directory. The way to solve this is to add the line <base href="http://www.mysite.com" /> into the meta data at the top of the page.

Job done, one "silent" redirect using PHP. I hope this makes sense. Any questions, please ask!
User avatar
Jade
Forum Regular
Posts: 908
Joined: Sun Dec 29, 2002 5:40 pm
Location: VA

Re: PHP redirect without modifying URL

Post by Jade »

This would probably be better off in the code snippets :)
Post Reply