PHP页面重定向异常修复:侧边栏?page参数跳转问题解决
侧边栏页面跳转问题解决记录
初始实现尝试
为实现侧边栏通过?page=mypage参数完成页面跳转,首先在.htaccess中配置Rewrite规则:
RewriteRule ^(.*)$ index.php?page=$1 [QSA,L]
同时编写了控制?page参数的include_page()函数,并在index.php中调用该函数:
function include_page() { $allowedPages = array('error', 'dashboard', 'settings', 'users'); if (isset($_GET['page'])) { $page = $_GET['page']; // 验证并清理请求的页面参数 if (!in_array($page, $allowedPages)) { // 非法页面,重定向到错误页 header('Location: index.php?page=error'); exit; } $filePath = __DIR__ . '/pages/' . $page . '.php'; if (file_exists($filePath)) { include($filePath); return; } } // 处理页面不存在的情况 header('Location: index.php?page=error'); exit; }
遇到的问题
无论访问index.php还是其他指定页面,都会被强制重定向到index.php?page=error,尝试多种调整方案均无效。
最终解决方案
修改后的页面处理函数
function handlePageRequest($page) { if ($page === 'index' || $page === '') { // 仪表盘页面逻辑 include("index.php"); // 引入仪表盘文件 // 其他仪表盘专属逻辑 } elseif ($page === 'dashboard') { // 仪表盘页面逻辑 include("pages/dashboard.php"); // 引入仪表盘文件 // 其他仪表盘专属逻辑 } elseif ($page === 'settings') { // 设置页面逻辑 include("pages/settings.php"); // 引入设置文件 // 其他设置专属逻辑 } elseif ($page === 'users') { // 用户页面逻辑 include("pages/users.php"); // 引入用户文件 // 其他用户专属逻辑 } else { // 非法页面或404错误 include("error/404.php"); // 引入404错误页 } exit(); // 终止脚本后续执行 } $page = isset($_GET['page']) ? $_GET['page'] : ''; handlePageRequest($page);
修改后的侧边栏代码
<div class="col-md-3 col-lg-2 sidebar d-flex flex-column"> <div class="sidebar-logo"> <img src="path/to/your/logo.png" alt="Logo"> </div> <div class="sidebar-sticky"> <ul class="nav flex-column"> <li class="nav-item"> <a class="nav-link <?php if (strpos($_SERVER['REQUEST_URI'], 'dashboard') !== false) echo 'active'; ?>" href="index.php?page=dashboard"> <i class="fa fa-home"></i> Dashboard </a> </li> <li class="nav-item"> <a class="nav-link <?php if (strpos($_SERVER['REQUEST_URI'], 'settings') !== false) echo 'active'; ?>" href="index.php?page=settings"> <i class="fa fa-settings"></i> Settings </a> </li> <li class="nav-item"> <a class="nav-link <?php if (strpos($_SERVER['REQUEST_URI'], 'users') !== false) echo 'active'; ?>" href="index.php?page=users"> <i class="fa fa-shopping-users"></i> Users </a> </li> <!-- 根据需要添加更多侧边栏菜单项 --> </ul> </div> <div class="mt-auto"></div> <!-- 空div用于将侧边栏内容推至底部 --> </div>
内容的提问来源于stack exchange,提问作者Boughaliah
相关产品推荐
相关产品推荐

