php如果文件存在则包含文件,如果不包含另一个文件

时间:2013-08-08 23:22:23

标签: php include file-exists

我试图包含一个文件,如果它存在,如果该文件不存在,我希望它包含另一个文件。

我有以下代码似乎工作正常,我的代码唯一的问题是如果文件确实存在,那么它会同时显示它们。

我想只包括

  

包括/ article.php

如果

  

包括/'.$未来。。PHP

不存在。

如果

  

包括/'.$未来。。PHP

存在我不想包含

  

包括/ article.php

<?php
$page = $_GET['include'];
if (file_exists('include/'.$future.'.php')){
   include('include/'.$future.'.php');
}
else{
  include('include/article.php');
 } 
?>

2 个答案:

答案 0 :(得分:2)

您的变量$ future甚至从未被定义过,那么它是如何被包含的?我认为你的意思是$ page和$ future是同一个变量。还包括用户在get请求中指定的文件开头没有多大意义,但也可能存在安全风险。

答案 1 :(得分:0)

  

也许这就是你需要的?

     

确保在之前定义您要使用的任何变量   使用变量...

<?php
$page = ''; // show emptyness is there is nothing dome below 
$page = isset($_GET['include']); // Do you have a variable in your URL that IS called "include" and is the include variable set? for example: http://www.example.com/index.php?include=.......  you might want to check for empty value and write a default value  as well but I didn't here ;)
// REMEMBER: $future must be defined BEFORE this line!
if (file_exists('include/' . $future . '.php') && is_file('include/' . $future . '.php')){ // file exists on server: true/false and is it a file or a directory? If Directory it will NOT be included as I used is_file()!
   include('include/' . $future . '.php');
   }elseif{
       (file_exists('include/article.php') && is_file('include/article.php')){
           include 'include/article.php';
       }else{
           echo 'WOW, No article found! You just found a error...<br />We will repair all errors ASAP! Thank you for visiting us...';
       }
?>