Question

I own a website with a simple user system at the moment and hate the ugly 'profile.php?id=$id' or '/users/$id/friends.php' url that people see when the visit a profile. That being said how would I change something like:

"/users/$id/friends.php"

To have a part replaced with the corresponding username, like:

"/$username/friends.php/"

How would this be possible? Could I get this done with editing the .htaccess, with preg_replace, or should I just have the directories named to $userid on creation? First time post sorry for possible mistakes.

Était-ce utile?

La solution

You have to write some routing rules in your htaccess file and code in your php file to handle this sort of thing. The htaccess rules are straight forward, they simply take a URL that looks like /$username/friends.php/ and sends it wholesale to a script:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/friends\.php/?$ /user_route.php?username=$1 [L]

The route can point to whatever script you want with whatever parameters you want. The /user_route.php?username=$1 is just an example, and "username" is where the $username in your example gets passed as.

Then in your user_route.php script, you'll need to take the $_GET['username'] variable, clean it up (if there are dashes or spaces or whatever), do a DB lookup to find the user's ID, then pass it to the profile script (or whatever script that you have handling the friends thing).

Then you'll need to make sure all of your links look like /$username/friends.php/.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top