【问题标题】:How to manage URLs of a website with different articles?如何管理包含不同文章的网站的 URL?
【发布时间】:2017-06-09 03:47:29
【问题描述】:

我制作了一个包含一些文章的示例网站。我希望 URL 的方式是:

www.example.com/news/first-article

但是,目前,我刚刚通过首先创建目录将所需的 first-article.html 文件放入目录中:home/news/

需要注意的是,我确实将文章的所有内容(如标题、正文、日期等)都保存在数据库中,所以我觉得可能有更好的方法,例如 URI 匹配器存在于 Android 中,而不仅仅是在每个目录中创建文件。

这里的动机是识别文章的类别(这里是'news')和文章的名称(这里是'first-article'),然后从数据库中检索详细信息并动态生成所需的页面。这在 PHP 中可行吗?

[示例代码 sn-p 会有所帮助]

【问题讨论】:

    标签: php database match blogs


    【解决方案1】:

    我建议使用单个 PHP 页面从数据库中读取,并根据 $_GET 参数显示内容:

    include('database_connection.php'); // Saved as $mysqli
    
    if (isset($_GET['id'])) {
        $news_id = $_GET['id'];
    
        // Grab the news information given the ID (in MySQLi)
        $stmt = $mysqli->prepare("SELECT id, news, date FROM news WHERE id = ?");
        $stmt->bind_param('i', $news_id);
        $stmt->execute();
        $stmt->store_result();
        $stmt->bind_result($id, $news, $date);
        $stmt->fetch();
    
        // Output results
        echo "<h1>" . $date . "</h1>";
        echo "<p"> . $news . "</p>";
    
        $stmt->close();
    }
    

    这将只需要一个 PHP 页面 (news.php),它会加载带有 news.php?id=1news.php?id=2 等的各种文章。

    然后您可以使用.htaccess 将新闻页面“变形”为“漂亮”页面,如下所示:

    Options +FollowSymLinks
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule (.*) news.php?id=$1&$2
    

    当您使用以下内容进行链接时:

    $article_title = 'First Article';
    echo '<a href="' . str_replace(" ", "-", $article_title).'">Read More</a>';
    

    这将根据脚本文件名“美化”您的页面 URL。

    希望这会有所帮助! :)

    【讨论】:

    • 用这个方法,我是不是要把最后的链接分享为example.com/news/first或者example.com?id=2
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    相关资源
    最近更新 更多