繁体   English   中英

用id和title重写url(php)

[英]Rewrite url with id and title (php)

如何重写url(怎么办),以便改为: http : //www.example.com/article.php?id= 123它表示: http : //www.example.com/articles/123/article_title_read_from_database使用php和mysql谢谢。

当使用id = 123的GET访问示例article.php孔页面时,用于检索数字的php代码为

$my_id = $_GET['id']

,在这种情况下,将产生123。

然后,您可以使用

header('Location: http://example.com/articles/$id/other stuff');

我将把MySQL的东西留给别人,但是一个简单的教程将为您提供很多信息。

要处理请求并重定向到新网址:

// get id of record from URL
$id = (int) $_GET['id'];
// suppose connection to database is established already
$result = mysql_query("SELECT `title` FROM `articles` WHERE `id` = $id");
if (!$result) {
    // there is no such an article
    // you can redirect to some other page, or show some error message
} else {
    $row = mysql_fetch_assoc($result);
    $title = $row['title'];
    $urlPart = generateURL($title);
    header('location:/articles/$id/$urlPart');
    exit;
}

您将需要generateURL函数,该函数接受字符串输入并将所有不可用的字符替换为_ (例如,如果您的标题为“ What's现状?”,它将把'?和空格替换为诸如“ what_s_going_on”之类的东西)。 您可以使用str_replacepreg_replace来实现。

如果要在多个位置生成新的URL,可以将title的URL形式作为另一列title_url直接插入数据库中,然后选择它并使用它代替title

SELECT `title_url` FROM `articles` WHERE `id` = $id

由于无法从此文件连接到数据库服务器,因此无法在.htaccess进行这种重写。 (或者至少我不知道这样的解决方案)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM