我有一个用户配置文件系统,其中一个动态页面(profile.php)随着用户id的变化而变化。。例如profile.php?id=2显示id=2的用户的配置文件。但是我希望地址为user/user_name.php。因此为每个用户提供一个唯一的配置文件页面地址。。是否可以不为每个用户创建单独的页面?Thnx
好的,让我们来谈谈apache的mod_rewrite。基本上,人们通常会设置一个php页面,例如index.php,并将所有请求重定向到那里(除了那些请求现有文件和目录的请求),然后index.php将这些请求路由到适当的文件/演示者/控制器等。
我将向你展示一个非常简单的例子,它是如何做到这一点的,只是让你了解它在基础上是如何工作的,还有更好的方法可以做到(例如,看看一些框架)。
因此,这里有一个非常简单的.htaccess文件,与index.php:放在同一目录中
<IfModule mod_rewrite.c>
RewriteEngine On
# prevents files starting with dot to be viewed by browser
RewriteRule /'.|^'. - [F]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) index.php?query=$1 [L]
</IfModule>
这是index.php:
<?php
$request = explode("/", $_GET["query"]);
// now you have your request in an array and you can do something with it
// like include proper files, passing it to your application class, whatever.
// for the sake of simplicity let me just show you the example of including a file
// based on the first query item
// first check it´s some file we want to be included
$pages = array("page1", "page2", "page3");
if(!in_array($request[0], $pages)) $request[0] = $pages[0];
include "pages/".$request[0];
但我强烈建议您不要重新发明轮子,而是查看一些现有的php框架。一旦你学会了如何使用ofc,你就会发现它为你节省了很多工作。提到一些-Zond框架、Symfony和我正在使用的一个-Nette框架。还有很多,所以选择适合你需要的。