简体   繁体   中英

Conflicts including files with relative path

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

use

dirname(__FILE__);

like this

include(dirname(__FILE__)."/bye.php");

Why not use getcwd() ?

Contents of index.php :

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

Contents of hello.php :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM