How To rewrite a url with PHP?

2019-08-25 02:02发布

Let' say for example one of my members is to http://www.example.com/members/893674.php. How do I let them customize there url so it can be for example, http://www.example.com/myname

I guess what I want is for my members to have there own customized url. Is there a better way to do this by reorganizing my files.

5条回答
再贱就再见
2楼-- · 2019-08-25 02:31

You could use a Front Controller, it's a common solution for making custom URLs and is used in all languages, not just PHP. Here's a guide: http://www.oreillynet.com/pub/a/php/2004/07/08/front_controller.html

Essentially you would create an index.php file that is called for every URL, its job is to parse the URL and determine which code to run base on the URL's contents. So, on your site your URLs would be something like: http://www.example.com/index.php/myname or http://www.example.com/index.php/about-us or http://www.example.com/index.php/contact-us and so on. index.php is called for ALL URLs.

You can remove index.php from the URL using mod_rewrite, see here: http://www.wil-linssen.com/expressionengine-removing-indexphp/

查看更多
叼着烟拽天下
3楼-- · 2019-08-25 02:46

Add a re-write rule to point everything to index.php. Then inside of your index.php, parse the url and grab myname. Lookup a path to myname in somekinda table and include that path

RewriteEngine on 
RewriteRule ^.*$ index.php [L,QSA]

index.php:

$myname = $_SERVER['REQUEST_URI'];
$myname = ltrim($myname, '/'); //strip leading slash if need be.
$realpath = LookupNameToPath($myname);

include($realpath);
查看更多
欢心
4楼-- · 2019-08-25 02:46

You must create a rewrite rule that point from http://www.example.com/myname to something like http://www.example.com/user.php?uname=myname.

In '.htaccess':

RewriteEngine on
RewriteRule     ^/(.*)$     /user.php?uname=$1
#               SourceURL   TargetURL

Then you create a 'user.php', that load user information from 'uname' GET variable.

See from your question, you may already have user page based on user id (i.e., '893674.php') so you make redirect it there.

But I do not suggest it as redirect will change the URL on the location bar.

Another way (if you already have '893674.php') is to include it.

The best way though, is to show the information of the user (or whatever you do with it) right in that page.

For example:

<?phg
vat $UName = $_GET['uname'];
var $User  = new User($UName);

$User->showInfo();
?>
查看更多
兄弟一词,经得起流年.
5楼-- · 2019-08-25 02:46

you need apache’s mod_rewrite for that. with php alone you won’t have any luck.

see: http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html

查看更多
家丑人穷心不美
6楼-- · 2019-08-25 02:52

create a new file and change it name to (.htaccess) and put this apache commands (just for example) into it :

Options +FollowSymLinks 
RewriteEngine on
RewriteRule ^profile/([0-9]*)$ members.php?id=$1
查看更多
登录 后发表回答