views:

142

answers:

4

I've got a number of users, each with the website page like http://www.mysite.com/folder/artist%5Fid.php?id=33

The users need to be able to set their own easy URL such as http://www.mysite.com/userguy that would redirect to the above page.

I know how to write these out manually in .htaccess with RewriteRule but, for example, users have a whole control panel created with php and javascript and it's become necessary to allow them to choose the name themselves and have code automatically put in. But I don't have a clue if there's already an easy method of setting that up or adding to the .htaccess file via code or if I should just do some sort of file open, rewrite thing, or what's safe.

BTW, I'm not worried about issues such as them naming themselves the same as an existing folder or php file in my site. The users are limited and subject to approval so that shouldn't be a problem.

A: 

Use the RewriteMap directive to call a script that transforms the URL appropriately.

Ignacio Vazquez-Abrams
+1  A: 

You could set up one rewrite rule to send all requests like http://www.mysite.com/userguy to a single php script that then will do the "translation". Doesn't necessarily have to be done via a rewrite rule, could also be an ErrorDocument handler. In this case the original request path can be found in $_SERVER['REQUEST_URI'].

VolkerK
+1  A: 

A proper solution that doesn't involve opening, modifying, and saving the .htaccess file using PHP would use a "router" of sorts. Consider the following:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

What this does is rewrite something like /userguy to /index.php?q=userguy, but only if /userguy isn't a directory or file that exists in the file system. This happens transparently to the user. index.php would then be responsible for do something like:

$path = $_GET['q'];
// Get router information using the $path variable.
$callback = get_callback_by_path($path);
// Assuming $callback is a function name. The function would print
// the page HTML or call into a theme layer or do whatever it needs to do.
call_user_func($callback);

The function get_callback_by_path would be custom logic that does whatever it needs to do to figure out what "userguy" needs to do. e.g. query a database mapping paths to function names and return the name of the function.

There is of course more to it, but that's the idea.

CalebD
The rewrite request works perfectly
Cyprus106
+2  A: 

Or, redesign your database to handle natural keys instead of numeric ones.
That'll save all your url de-mapping 33 = userguy etc, your urls will be more friendly, guessable and seo-friendly and browsing your database will be easier to boot.

username (PK)
Cups