0

Let's say I have a web-page called www.mysite.com


How can I make it so whenever a page is loaded like www.mysite.com/58640 (or any random number) it redirects to www.mysite.com/myPHPpage.php?id=58640.


I'm very new to website development so I don't even really know if I asked this question right or what languages to tag in it...



If it helps I use a UNIX server for my web hosting with NetWorkSolutions

Albert Renshaw
  • 17,282
  • 18
  • 107
  • 195

1 Answers1

3

Add this to your .htaccess file in the main directory of your website.

RewriteEngine on
RewriteBase /
RewriteRule ^([0-9]+)$ myPHPpage.php?id=$1 [L]

Brief explanation: it says to match:

  • ^ from start of query/page
  • [0-9] match numbers
  • + any matches of 1 or more
  • $ end of page requested

The parentheses part say to look for that bit and store it. I can then refer to these replacement variables in the new url. If I had more than one parentheses group then I would use $2, $3 and so on.

If you experience issues with the .htaccess file please refer to this as permissions can cause problems.

If you needed to capture something else such as alphanumeric characters you'd probably want to explore regex a bit. You can do things such as:

RewriteRule ^(.+)$ myPHPpage.php?id=$1 [NC, L]

which match anything or get more specific with things like [a-zA-Z0-9], etc..

Edit: and @Jonathon has a point. In your php file wherever you handle the $_GET['id'] be sure to sanitize it if used in anything resembling an sql query or mail. Since you are using only numbers that makes it easy:

$id = (int)$_GET['id']; // cast as integer - any weird strings will give 0

Keep in mind that if you are not going to just use numbers then you will have to look for some sanitizing function (which abound on google - search for 'php sanitize') to ensure you don't fall to an sql injection attack.

cyberwombat
  • 38,105
  • 35
  • 175
  • 251
  • 1
    And then, for the love of $DEITY don't use `$_GET['id']` in your SQL queries without sanitization. – Jonathon Reinhart Dec 19 '13 at 01:22
  • @JonathonReinhart when you say sanitization you mean like backslashing and stuff? Also... THANKYOU Yashua!?!??!?! Is that [0-9] thing RegEx btw? What if I want alphanumerics instead of just numerals? Thanks! – Albert Renshaw Dec 19 '13 at 01:41
  • I added the code to my .htaccess and then added a dummy php page title myPHPpage.php and then navigated to www.mysite.com/230498 but I got a 404 error. – Albert Renshaw Dec 19 '13 at 01:45
  • Great, I've updated my answer accordingly and yes that is RegEx – cyberwombat Dec 19 '13 at 03:22