PHP 如果页面不存在,则显示 404



我有一个代码,我正在尝试工作。请原谅我的无知,我正在努力学习,但我找不到任何特别帮助我的东西。

我想做的是:

在我的索引上,显示show_news.php

使用index.php?page=blank时,显示blank.php的内容

如果所选页面不存在,我想显示自定义 404 页面。假设blank2.php被使用并且不存在,它包括404.php

404页面是我正在努力解决的问题。

<?php
$number = 4;
if(!$_GET[page]){ 
    include "show_news.php"; 
} elseif ($_GET[page]) { 
    include $_GET[page].".php"; 
} else { 
    include "404.php"; 
} 
?>

尝试使用file_exists((函数http://php.net/manual/ru/function.file-exists.php

<?php
$number = 4;
define('ROOTPATH', __DIR__);
$project_path = ROOTPATH . "/path/to/page/files/";
$page = $_GET["page"];
$is_file_existing = $file_exists($project_path . $page . ".php");
if(!$page){
    include "show_news.php";
} elseif ($is_file_existing) {
    include $page . ".php";
} else {
    include "404.php";
}
?>

我不太明白你的问题。但这是我的做法:

if (isset($_GET['page']))
    include_once(dirname(__FILE__) . '/' . $_GET['page'] . '.php');
else
    include_once(dirname(__FILE__) . '/show_news.php');

然后在您的 .htaccess 文件中:

RewriteEngine On
RewriteBase /
ErrorDocument 404 /404.php

编辑:在将其转入 _GET 美元之前,请使用mysqli_real_escape_string

最新更新