views:

90

answers:

6

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

<?php include "http://www.myserver.com/somefile.php" ; ?>

I tried:

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

but it did not work.

+2  A: 

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'
spinon
+1  A: 

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.
Artefacto
+1  A: 

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');
GSto
A: 

I use this :

$filename = "file.php";
if (file_exists($filename)) {
include($filename);
}
Amirouche Douda
A: 

When PHP reads a file it does not care about where it's URI is, it's looking local to the file system (unix or windows) path where the file is located. http://en.wikipedia.org/wiki/Path_(computing)

Also, please I beg of you... Don't use includes everywhere as a means of executing the same code over and over again... I'm presently maintaining some code right now that is LITTERED withinclude('close.php'); :(

I hate that too. I once worked on a system that not only did that, it often called output buffering around the include so the output could be echoed at a later time :(
GSto
+1  A: 

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;    
    }
}
dorgan
The autoload is an excellent point.
Justin Dearing