如何检查成功包含的php文件?

时间:2012-12-06 07:43:38

标签: php include


我想检查'ad.php'中是否包含'dbas.php'。我写了代码 -

ad.php

<?php if(file_exists("dbas.php") && include("dbas.php")){
// some code will be here
}
else{echo"Database loading failed";}
?>

我成功测试了file_exists()部分,但不知道include()是否运行良好,因为我在localhost中尝试过,如果文件在目录中,那么它永远不会包含。因此,如果流量很大,我不知道这个代码在服务器中的行为方式。那么请告诉我我的代码是否正确?

-Thanks。

解决: 非常感谢您的回答。

6 个答案:

答案 0 :(得分:15)

如果您想要绝对确定包含该文件,则使用php require method更合适。 file_exists仅检查文件是否存在,而不是它是否实际可读。

如果包含失败,

require将产生错误(您可以catch错误,请参阅Cerbrus的回答)。

编辑:

但是,如果您不希望脚本在包含失败时暂停,请使用方法is_readablefile_exists,如:

if( file_exists("dbas.php") && is_readable("dbas.php") && include("dbas.php")) {
    /* do stuff */
}

答案 1 :(得分:8)

只需使用require

try {
    require 'filename.php';
} catch (Exception $e) {
    exit('Require failed! Error: '.$e);
    // Or handle $e some other way instead of `exit`-ing, if you wish.
}

尚未提及的内容:可以添加布尔值,例如:

$dbasIncluded = true;

dbas.php文件中,然后在代码中检查该布尔值。虽然通常情况下,如果文件没有正确包含,你需要php来制动,而不是渲染页面的其余部分。

答案 2 :(得分:0)

file_exists("dbas.php")正在进行检查。如果存在,则执行include。

if(file_exists("dbas.php"){
    include("dbas.php")
    //continue with you code here
}

答案 3 :(得分:0)

将您的功能放在一个函数中,并使用function_exists检查它是否存在。

include ("php_file_with_fcn.php");
if (function_exists("myFunc")) {
    myFunc();
    // run code
} else {
    echo "failed to load";
}

在您的情况下,incusion文件将是

function db_connect() {
     $user = "user";
     $pass = "pass";
     $host = "host";
     $database = "database";
     mysql_connect($host, $user, $pass);
     return mysql_select_db($database);
}

和主文件:

include("db_connect.php");
if (function_exists("db_connect")) {
    if (db_connect() === TRUE) {
        // continue
     } else {
        // failed to connect (this is a different error than the "can't include" one and 
        // actually **way** more important to handle gracefully under great load
     }
 } else {
     // couldn't load database code
 }

答案 4 :(得分:0)

使用此代码代替您的代码,因为在您的代码中,如果服务器中不存在文件,则会出现php错误,但这样做并不好,请使用此代码:

if(file_exists("dbas.php")) {
    include_once("dbas.php");
} else {
    echo"file is not found";
}

此代码表示如果服务器上存在文件,则找不到函数include else文件echo

答案 5 :(得分:-1)

echo "file is includ" 

在“dbas.php”的末尾