首页 > 解决方案 > PHP - 动态链接问题

问题描述

我正在测试使用 php 动态显示页面链接,并且我能够使用 index.php 中的以下代码来实现它:

    <a href="index.php">Home</a>
<a href="index.php?page=about">About</a>
<a href="index.php?page=contact">Contact</a>
<a href="index.php?page=news">news</a>


<div class="content">
    <?php

        if( !empty($_GET['page']) ) {

            $allPages = scandir('pages', 0);
            unset($allPages[0], $allPages[1]);
            $page = $_GET['page'];

            if( in_array($page . '.inc.php', $allPages) ) {

                include('pages' . '/' . $page . '.inc.php');
            } else {
                echo "page not found";
            }
        } else {
            include('pages' . '/home.inc.php');
        }






    ?>
</div>

附上,您还将找到我的目录结构的图像。

我有两个问题:

  1. 由于 url 中的每个项目都显示为,?page=contact我可以使用 .htaccess 文件隐藏它吗?
  2. 如果您在 index.php 主页面上并尝试编写 index.php/anythingElse,我希望它恢复为简单的 index.php,但每次尝试包含(index.php)时,我都会生成一个无限循环并页面崩溃。我怎样才能避免这种情况?

在此处输入图像描述

标签: phphtmldynamic

解决方案


您不能在 url 中隐藏查询字符串,但可以添加 .htaccess 规则以将 url 重写为更漂亮的内容。例如,index.php?page=test 可以变成 index/test。

#redirect /index.php?page=test to /index/test
RewriteCond %{THE_REQUEST} /page.php\?query=([^\s]+) [NC]
RewriteRule ^.+$ /page/%1? [L,R]

#rewrite /index/test to /index.php?page=test
RewriteRule ^page/(.*)$ page.php?query=$1 [L]

推荐阅读