开发者

Better/safer way to use php include?

this works for me, but is there a better/safer way to use an include:

开发者_JAVA技巧
<?php include "http://www.myserver.com/somefile.php" ; ?>

I tried:

<?php include "somefile.php" ; ?>

but it did not work.


I use this format so I can use relative paths from the root level. It makes it easier to read than a bunch of ..\..\ in a path.

include $_SERVER["DOCUMENT_ROOT"] . '/root folder/file.php'


There are several things wrong here:

  • If you want to include a PHP source file for processing, including a URL won't work, unless the server does not process the PHP files and returns it verbatim.
  • Including URLs is not safe; this being your server it's probably not so serious, but it's a performance hit anyway since reading the file directly from disk is faster.
  • If the file you're including doesn't have PHP code, use readfile or file_get_contents.

The reason your second include doesn't work is because the file somefile.php is not in the "working directory" (likely the directory of the file in where you have the include).

Do one of these:

  • Use a full path: /path/to/somefile.php (on Unix-like systems).
  • Use a relative path: ../relative/path/to/somefile.php.


For the best portability & maintence, I would have some kind of constant defined to the base path, and use that when looking for files. This way if something in the file system changes you only have to change one variable to keep everything working.

example:

define('INCLUDE_DIR','/www/whatever/');
include(INCLUDE_DIR . 'somefile.php');


I would highly suggest setting an include_path and then using PHP's autoload:

http://us3.php.net/autoload

My autoloader looks like this:

function __autoload( $class_name ) {
    $fullclasspath="";

    // get separated directories
    $pathchunks=explode("_",$class_name);

    //re-build path without last item
    $count = count( $pathchunks ) -1;
    for($i=0;$i<$count;$i++) {
        $fullclasspath.=$pathchunks[$i].'/';
    }
    $last = count( $pathchunks ) - 1;
    $path_to_file = $fullclasspath.$pathchunks[$last].'.php';
    if ( file_exists( $path_to_file ) ) {
        require_once $path_to_file;    
    }
}


I use this :

$filename = "file.php";
if (file_exists($filename)) {
include($filename);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜