2

I know this has been covered extensively, but I can't seem to find an answer to what I want to do. I've read all the stack articles and looked at different methods that google shows with the infinite number of search strings I've tried.

I've seen articles talking about making the PHP readable URL go to pretty but nothing (I can understand) on making the pretty go to PHP readable.

I've seen articles talking about making an htaccess entry for each "user" (in the case below), but no few-line solution that formats the way I need (again, in the case below).

Can someone provide a template for:

1) Sending a pretty URL that looks like https://mysite.com/users/sampleUserName to https://mysite.com/users.php?username=sampleUserName

2) Have users.php handle the pretty url if that's even necessary.

I'm not even totally sure what I'm asking (because I have no idea how this works hence the question), so if anyone can more precisely read my mind, it would be much appreciated. LOL

Bottom line: I want people to be able to type in a pretty URL and have PHP be able to handle it.

Many thanks in advance!

  • 1
    Take a look at [This answer](http://stackoverflow.com/a/13421100/1824205) – fimas Nov 18 '12 at 20:30
  • 1
    This is usually done by using the Apache module `mod_rewrite`. But you are better off using a framework for it, for example this: http://silex.sensiolabs.org/ (see the first code example on the page). – Botond Balázs Nov 18 '12 at 20:30

2 Answers2

2

You need to use Apache's mod_rewrite.

You will need to add the following lines in your .htaccess file:

RewriteEngine On
RewriteRule   ^[a-zA-Z0-9]/?$    users.php?username=$1    [NC,L]

If you want to read more about it, here is a nice article about URL Rewriting for Beginners.

mbinette
  • 5,094
  • 3
  • 24
  • 32
  • Thank-you for your answer! I want to have a fake directory. Does your answer do that? I'd like to have /users/ point to users.php and /articles/ to articles.php etc –  Nov 18 '12 at 20:34
  • 1
    Sure! Just change the first part of the rewrite rule to `^users/[a-zA-Z0-9]/?$` and do the same for articles! – mbinette Nov 18 '12 at 20:35
  • Wow. Perfect! you wouldn't believe all the hoops the TONS of articles I've read wants me to go through. –  Nov 18 '12 at 20:36
1

Why reinvent the weel and write your own URL rewriting solution? Use a framework (you don't have to use the rest of it, only the routing library). Here is an example using the very lightweight Silex micro-framework:

require_once __DIR__.'/../vendor/autoload.php'; 

$app = new Silex\Application(); 

$app->get('/hello/{name}', function($name) use($app) { 
    return 'Hello '.$app->escape($name); 
}); 

$app->run(); 

Source: http://silex.sensiolabs.org/

Botond Balázs
  • 2,512
  • 1
  • 24
  • 34