How To rewrite a url with PHP?

2019-08-25 02:10发布

问题:

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.

回答1:

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/



回答2:

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);


回答3:

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


回答4:

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:

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