php - 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>
附上,您还将找到我的目录结构的图像。
我有两个问题:
- 由于 url 中的每个项目都显示为,
?page=contact
我可以使用 .htaccess 文件隐藏它吗? - 如果您在 index.php 主页面上并尝试编写 index.php/anythingElse,我希望它恢复为简单的 index.php,但每次尝试包含(index.php)时,我都会生成一个无限循环并页面崩溃。我怎样才能避免这种情况?
解决方案
您不能在 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]
推荐阅读
- java - 如何检测无障碍服务何时停止工作?
- curl - 将 Bundle 中的患者导入 FHIR 服务器
- google-apps-script - 在单元格Google表格中反转单词而不是单个字符
- javascript - 测试导航器属性是否被 getter 函数覆盖的可靠方法
- actions-on-google - 如何在 Google 智能家居操作中对设备进行分组?
- ruby-on-rails - 在rails中,如何为具有重复值的行创建自关联?
- python - 打印异常的输出是什么,为什么它与输出的字符串不匹配
- javascript - 无法映射 API 数据以响应本机 Picker
- java - 有没有办法在 Java 中为数组定义添加条件?
- laravel - 有没有办法使用 JWT 和 Laravel 修复传递给 Tymon\\JWTAuth\\JWTGuard::__construct() 的参数 2?