重写URL,用查询字符串中的标题替换ID [英] Rewrite URL, replacing ID with title in query string

查看:134
本文介绍了重写URL,用查询字符串中的标题替换ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对mod_rewrite还是很陌生,但是我已经进行了一些搜索,但是找不到这个问题的答案.我有一个网站,该网站只有一个PHP页面,该页面根据查询字符串中传递给它的ID可以提供数十个页面的内容.我想重写URL,以便此ID 消失,并替换为从数据库中提取的页面标题.例如

I'm pretty new to mod_rewrite, but I've done some searching around and can't find an answer to this question. I've got a site which has only one PHP page serving up dozens of pages of content depending on the ID passed to it in the query string. I'd like to rewrite the URL so that this ID disappears and is replaced by the page's title as drawn from the database. For example

www.example.com/index.php?id=19

被替换为

www.example.com/my-page-title

其中"my-page-title"是存储在数据库中索引为19的页面的标题.

where "my-page-title" is the title of a page stored in the database at index 19.

有人有这种重写的经验吗,或者甚至有可能吗?

Does anyone have any experience of this kind of rewrite, or is it even possible?

谢谢

HR

推荐答案

对于PHP脚本,您的.htaccess可能看起来像这样:

Sure its possible, for a PHP script your .htaccess might look something like this:

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

这会将目录或文件名以外的所有URL重写为"index.php?url = THE-TYPED-ADDRESS".

This will rewrite all URLs except for directory or file names to "index.php?url=THE-TYPED-ADDRESS".

然后在index.php中,您可以使用$ _GET ['url']的值来确定ID:

In your index.php you could then use the value of $_GET['url'] to determine the ID:

// init DB layer
if (isset($_GET['url']) && !empty($_GET['url'])) {
  $url = my_filter_function($_GET['url']); // filter input
  $pdo = my_get_pdo_function(); // get configured PDO objected
  $query = "SELECT id FROM my_router_table WHERE url = ? LIMIT 1"; // use prepared statements for security/performance reasons

  $stmt = $pdo->prepare($query);
  $stmt->bindValue(1, $url, PDO::PARAM_STR); // bind the value as a string

  // ternary operator expanded for readability
  if ($stmt->execute()) {
    $id = $stmt->fetch(PDO::FETCH_ASSOC);
  } else {
    $id = -1; // 404 page
  }

  // fetch content/render page according to ID
}

这显然是一个过于简化的示例,您应该确保自己正确地转义了输入并使用准备好的语句以避免安全风险.另外,如果您使用MySQLi或其他数据库访问层,则您的准备/执行/获取代码将略有不同.

This is obviously an overly simplified example and you should really make sure you properly escape your input and use prepared statements to avoid security risks. Also, if you use MySQLi or another database access layer your prepare/execute/fetch code will vary slightly.

这篇关于重写URL,用查询字符串中的标题替换ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆