php - htaccess - 使用 php 和 mysql 重写 url

标签 php mysql .htaccess mod-rewrite

我正在尝试重写 /example-friend-url 以显示 /posts.php?id=1 的内容。

友好的 url 值和 id 都存储在 mysql 表中。

这是我到目前为止所写的内容,但有些地方不对:

posts.php:

include('/functions.php');
$post = getPost($_GET['id']);
$param = getSlug($_GET['param']);

函数.php:

function getPost($id) {
    $id = (int) $id;
    $query = mysql_query("SELECT * FROM list WHERE id = '$id'") or die(mysql_error());
    return mysql_fetch_assoc($query);
}

function getSlug($param) {
    $query = mysql_query("SELECT id FROM list WHERE slug = '$param'") or die(mysql_error());
    return mysql_fetch_assoc($query);
}

.htaccess:

Options +FollowSymlinks
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/posts.php
RewriteCond %{REQUEST_URI} !^/$
RewriteRule ^/(.*)$ %{DOCUMENT_ROOT}/posts.php?param=$1 [NC,L]

任何帮助将不胜感激。

最佳答案

在 htaccess 文件中处理 mod_rewrite 规则时,前导斜杠将被删除,因此您不需要在正则表达式前面添加 ^/:

RewriteRule ^(.*)$ %{DOCUMENT_ROOT}/posts.php?param=$1 [NC,L]

您正在将“slug”作为 _GET['param'] 传递。没有“身份”。您需要在 posts.php 中将该 slug 转换为 ID:

include('/functions.php');

$post_id = getSlug($_GET['param']);
$post = getPost($post_id);

当然,请确保使用类似 mysql_real_escape_string 的内容对 $_GET['param'] 进行清理。 (已弃用,您确实想使用 mysqli )。

关于php - htaccess - 使用 php 和 mysql 重写 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17558209/

相关文章:

regex - .htaccess 删除 .php 但在末尾添加/

php - PHRETS GetObject() 返回数组,需要提取 URL

php - 重用数据库连接对象

html - .htaccess 这个网页有一个重定向循环 htaccess

mysql - 如何设置触发器以从另一个模式插入另一个表?

mysql - 使用 MySQL 事件到 "deactivate"帐户

PHP/Apache,htaccess 中的选项 +indexes 不适用于根目录

php - 从 PHP 切换到 Ruby - 这是性能的答案吗?

php - INSERT INTO TBL_payments undefined index 和父子外键

php - bootstrap 通常如何工作,尤其是在 Zend Framework 中?