如果URL变量无效,我该如何检查?就像我在我的网站上输入无效的网址一样:“../index.php?page=skillsa
”。为此,我收到一个错误:
警告:include_once(views / skillsa.php):无法打开流:第22行/opt/lampp/htdocs/tut01/index.php中没有此类文件或目录
如何在以下代码中处理此类错误?
<?php
//error reporting
error_reporting(E_ALL);
ini_set("display_errors", 1);
//class for variables
include_once "classes/Page_Data.php";
$pageData = new Page_Data();
//
$pageData->title = "Portfolio site";
$pageData->content = include_once "views/navigation.php";
$pageData->css = "<link href='css/layout.css' rel='stylesheet'/>";
//url variables
$navigationIsClicked = isset($_GET['page']);
if($navigationIsClicked) {
$fileToLoad = $_GET['page'];
} else {
$fileToLoad = "home";
}
$pageData->content .= include_once "views/$fileToLoad.php";
//embedded style
$pageData->embeddedStyle = "
<style>
nav a[href *= '?page=$fileToLoad'] {
background-color: white;
}
</style>";
$page = include_once "templates/page.php";
echo $page;
修改 或者我可以只使用一个数组来存储所有的URL变量吗?
更新代码:
<?php
//error reporting
error_reporting(E_ALL);
ini_set("display_errors", 1);
$page_files=array( 'home', 'skills', 'projects', '404');
//class for variables
include_once "classes/Page_Data.php";
$pageData = new Page_Data();
//
$pageData->title = "Portfolio site";
$pageData->content = include_once "views/navigation.php";
$pageData->css = "<link href='css/layout.css' rel='stylesheet'/>";
//url variables
if(isset($_GET['page'])) {
if (in_array($_GET['page'], $page_files)) {
$fileToLoad = $_GET['page'];
} else {
$fileToLoad = '404';
}
} else {
$fileToLoad = 'home';
}
$pageData->content .= include_once "views/$fileToLoad.php";
//embedded style
$pageData->embeddedStyle = "
<style>
nav a[href *= '?page=$fileToLoad'] {
background-color: white;
}
</style>";
$page = include_once "templates/page.php";
echo $page;
答案 0 :(得分:0)
我不确定这是你想要的,但这就是我认为你想要的。
//url variables
if(isset($_GET['page'])) {
if (in_array($_GET['page'], $page_files)) {
//basename returns only the filename part of a path ~ might have to check this
// when using just text such as "somepage", it's used for things like "../../somepage"
// and returns just "somepage"
$fileToLoad = "views/".basename( $_GET['page'] ) .".php";
//echo $fileToLoad;
if(!file_exists( $fileToLoad ) ){
$fileToLoad = "views/404.php";
}
} else {
$fileToLoad = "views/404.php";
}
} else {
$fileToLoad = "views/home.php";
}
$pageData->content .= include_once $fileToLoad;