user1382306
user1382306

Reputation:

set & read pretty URL

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!

Upvotes: 2

Views: 91

Answers (2)

Botond Balázs
Botond Balázs

Reputation: 2500

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/

Upvotes: 1

mbinette
mbinette

Reputation: 5094

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.

Upvotes: 2

Related Questions