3

I'm trying to make includes dynamically in my php script. This is my directory tree:

-index.php
-sources/
--hello.php
--bye.php

In my index.php I make an include of hello.php:

include("sources/hello.php");

In my hello.php I have another include of:

include("bye.php");

When I access the index.php it throws an error saying:

Message: require_once(bye.php) [function.require-once]: failed to open stream: No such file or directory

Is there a way to get it works but without absolutes paths? because the paths can be changeable from one directory to another but keeping the structure:

-index.php
-sources/
--hello.php
--bye.php
manix
  • 14,537
  • 11
  • 70
  • 107

3 Answers3

3

use

dirname(__FILE__);

like this

include(dirname(__FILE__)."/bye.php");
mbouzahir
  • 1,424
  • 13
  • 16
1

Why not use getcwd()?

Contents of index.php:

include(getcwd() . "/sources/hello.php");

Contents of hello.php:

include(getcwd() . "/sources/bye.php");
  • 2
    See this to know why dirname +__FILE__ is better than getcwd http://stackoverflow.com/questions/2184810/difference-between-getcwd-and-dirname-file-which-should-i-use – mbouzahir Oct 17 '12 at 04:17
0

Since "hello.php" is being included in "index.php", "bye.php" needs to be included in "hello.php" as if it were being included from "index.php". Like this:

include("sources/hello.php");

However, if you want to include "hello.php" all over the place and not only in the "index.php" directory, you could set a variable in "hello.php" that gives you the correct path every time. Like this:

$webroot = "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/";
include($webroot."sources/bye.php");

OUTPUT -->http://website.com/sources/bye.php
abbotto
  • 4,259
  • 2
  • 21
  • 20