friendly urls for users profile?

限于喜欢 提交于 2020-01-03 05:05:11

问题


hello i wanted to create a format for users url, for example for the user ninja123, he would get a profile link of example.com/ninja123, im using php mysql on apache. this is the normal link!

viewprofile.php?userid=2

how could i appraoch this problem? and im a bad .htaccesss newbie :)) thanks


回答1:


Instead of doing $_GET['userid'] and looking for ID... switch it by looking for name so it's like: viewprofile.php?userid=Ninja123

Try this Mod Rewrite generator: http://www.generateit.net/mod-rewrite/




回答2:


Create a .htaccess file:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php?url=$1 [QSA,L]
</IfModule>

If a site visitor requests http://example.com/Ninja123, the folder won't be found so it will run index.php and fill $_GET['url'] with /Ninja123

In index.php, grab the path component from $_GET['url']:

$username = trim(parse_url($_GET['url'], PHP_URL_PATH), '/');

Now $username will contain Ninja123. You can use that to do a database search to retrieve the user id. If you want this to work with requests that contain sub-directories (example.com/Ninja123/photos/party) you'll want to strip out those sub-directories before performing the query.




回答3:


You can't use a .htaccess RewriteRule only for this. If the forum exposes database internal IDs, you have mostly to rewrite parts of the SQL query. Basically you need to accept $_GET["username"] instead of "userid" first, and then rewrite the lookup. As example:

db_query("SELECT * FROM users WHERE id=?", (int)$_GET["userid"]);

to

db_query("SELECT * FROM users WHERE username=?", encode($_GET["username"]));

Depends on the application, the actual SQL table structure, and the DB interface (your forum probably uses mysql_query and mysql_real_escape_string instead of encode).

After that you can deploy a simple RewriteCond !-f {%..} and RewriteRule (.+) /viewprofile?username=$1 to get short URLs.



来源:https://stackoverflow.com/questions/3601937/friendly-urls-for-users-profile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!