简体   繁体   中英

php includes that include another php file

I'm getting really muddled up now and my brain hurts! :( lol

Root:

  • index.php

Includes:

  • cat.php
  • dog.php

index includes dog: include("includes/dog.php");

dog includes cat: include("cat.php");

When I run index, for cat it says:

  1. A link to the server could not be established
  2. Access denied for user ...

However, if I run dog, I get no problems...

I'm guessing its the path, but i've tried ./includes/cat.php to no joy...

This is because when you include a relative path, it's relative to the entry point (the first PHP file, called by the webserver).

In dog, do

include(dirname(__FILE__) . '/cat.php'); // __FILE__ is always the name of the php file it's in

It depends on where the script you are executing lies. When you execute /index.php the path of the script set to / , so all includes start from there. This means that you can find /includes/dog.php , but it's not possible to find /cats.php . Mind that, even if you are including cats.php from your /includes/dog.php script, this doesn't change the original execuption path.

When, on the other hand, you are executing /includes/dog.php , your path is set to /includes/ , which is why PHP can also find cats.php .

Read Bart's comment on how to solve this.

Another way to solve this is to set the include path of files, take a look at this.

http://ve2.php.net/manual/en/function.set-include-path.php

Thanks for this nice thread.

I used bart's answer to solve this issue. But I still have one question here.

I was surprised that it worked in my mate's system even without using dirname(__FILE__) so I did little research and compared both php.ini files. I noticed there is little difference at include_path parameter in php.ini.

In my php.ini it is set to Pear directory. So I commented out just to test and to my wonder it worked. This is when I realized we need to include some folder which I dont know or comment it out so that it takes default value.

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