【问题标题】:php if page doesn't exist display 404php如果页面不存在显示404
【发布时间】:2018-08-26 18:23:07
【问题描述】:

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

我想做的是:

在我的索引上,显示 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"; 
} 
?>

【问题讨论】:

  • if 条件中的逻辑没有意义
  • 永远不会到达else语句
  • 看,这就是我需要帮助的地方哈哈。在这方面我还是个年轻人。它怎么会不到达其他地方?我认为顺序应该是“if, elseif, else”
  • 变量不会神奇地检查文件的存在,你需要file_exists()。还有你在做什么insecure
  • 永远不要相信用户输入。您可以根据字符串对其进行检查,然后使用您指定的字符串对文件系统执行操作,但不要在未清理它们的情况下将用户提供的变量用于大部分内容。您的代码将允许用户通过为“page”传递正确的值来在文件系统中包含任何文件(如果您还使用$_GET['page'] 正确访问超全局值)

标签: php html variables include


【解决方案1】:

我不太明白你的问题。 但我会这样做:

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

编辑: 在将 mysqli_real_escape_string 传递给 $_GET 之前使用它。

【讨论】:

    【解决方案2】:

    尝试使用 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";
    }
    ?>
    

    【讨论】:

    • 我试过了,但出现错误。 “致命错误:函数名称必须是第 79 行 /home/****/public_html/news/index.php 中的字符串”第 79 行是 $is_file_existing = $file_exists($project_path . $page . ".php"); 行谷歌搜索显示存在错误 $,将其从 @987654324 中删除@ 删除了错误,但它就像我的原始代码一样工作
    猜你喜欢
    • 2011-04-24
    • 2021-08-13
    • 1970-01-01
    • 2019-03-27
    • 1970-01-01
    • 1970-01-01
    • 2015-07-22
    • 2010-10-19
    • 1970-01-01
    相关资源
    最近更新 更多