3

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.

rook
  • 66,304
  • 38
  • 162
  • 239
Barry
  • 63
  • 1
  • 5
  • Can you tell use there the file you're trying to include is relative to the file being executed? – NikiC Jul 16 '10 at 18:44
  • Make sure the file you are including is in the same directory as the file you are including it in (on the webserver). You can use relative paths if it isnt – Josh K Jul 16 '10 at 18:44
  • did you try a leading / if it's in your server's root directory? – TCCV Jul 16 '10 at 18:55

5 Answers5

3

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
  • 10,760
  • 5
  • 41
  • 59
1

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
  • 96,375
  • 17
  • 202
  • 225
1

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
  • 41,512
  • 37
  • 133
  • 184
1

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
  • 135
  • 1
  • 10
0

I use this :

$filename = "file.php";
if (file_exists($filename)) {
include($filename);
}
Amirouche Douda
  • 1,564
  • 1
  • 21
  • 30