PHP动态数据库页面重写URL

use*_*487 4 php url-rewriting dynamic-pages

我怎样才能制作www.mydomain.com/folder/?id=123 ---> www.mydomain.com/folder/xCkLbgGge

我希望我的数据库查询页面能够获得它自己的URL,就像我在twitter等上看到的那样.

chr*_*ris 7

这被称为"slug"wordpress使这个术语流行.无论如何.

最终你需要做的是拥有一个.htaccess文件来捕获你所有的传入流量,然后在服务器级别对其进行改造,以便在某种意义上与你的PHP一起使用,你仍然可以保持?id = 123逻辑,但是对于客户端side'/ folder/FHJKD /'将是可见结果.

这是一个.htaccess文件的例子,我在...上使用了类似的逻辑.(对于那个问题,wordpress也是如此).

RewriteEngine On
#strips the www out of the domain if there
RewriteCond %{HTTP_HOST} ^www\.domain\.com$

#applies logic that changes the domain from http://mydomain.com/post/my-article
#to resemble http://mydomain.com/?id=post/my-article
RewriteRule ^(.*)$ http://domain.com/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?id=$1 [QSA,L]
Run Code Online (Sandbox Code Playgroud)

这将做什么是在domain.com/之后将所有内容作为变量传递给index.php,此示例中的变量将是'id',因此您必须设置最适合您网站需求的逻辑.

<?php
 //the URL for the example here: http://mydomain.com/?id=post/my-article
 if($_GET['id'])
 {
   $myParams = explode('/', $_GET['id']);
   echo '<pre>';
   print_r($myParams);
   echo '</pre>';
 }
?>
Run Code Online (Sandbox Code Playgroud)

现在这个的逻辑必须更深入,这只是一个基本层面的纯粹例子,但总的来说,特别是因为我假设你使用数据库工作,你要确保$ myParams清除恶意代码,可以注入你的PHP或数据库.

上述$myParams通道的输出print_r()将是:

Array(
   [0] => post
   [1] => my-article
)
Run Code Online (Sandbox Code Playgroud)

要使用它,您至少需要做

echo $myParams[0].'<br />';
Run Code Online (Sandbox Code Playgroud)

或者你可以这样做,因为大多数浏览器会添加最终/

<?php
 //the URL for the example here: http://mydomain.com/?id=post/my-article
 if($_GET['id'])
 {
   //breaks the variable apart, removes any empty array values and reorders the index
   $myParams = array_values(array_filter(explode('/', $_GET['id'])));
   if(count($myParams > 1)
   {
       $sql = "SELECT * FROM post_table WHERE slug = '".mysql_real_escape_string($myParams[1])."'";
       $result = mysql_query($sql);
   }

 }
?>
Run Code Online (Sandbox Code Playgroud)

现在这是一个非常粗略的例子,你想在那里工作一些逻辑以防止mysql注入,然后你将应用查询,就像你现在如何使用id = 123拉出你的文章.

或者你也可以走一条完全不同的路线,探索MVC(模型视图控制)的奇迹.像CodeIgniter这样的东西是一个很好的简单的MVC框架,可以开始使用.但这取决于你.