Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
783 views
in Technique[技术] by (71.8m points)

php - Including files by relative path

There must be something i don't understand about linking files -- but here's my problem.

Basically, i have three files.

  1. generalfunctions.php
  2. wordcount.php
  3. index.php

All three files are in different directories.

B relies on A as follows: ../../../phpfunctions/generalfucntions.php
And when I run B all is well.

But C relies on B as follows: ../wordcount.php

When I run C, I get an error saying that linked file A cannot be found.

The actual error is:

No such file or directory in /.../public_html/plaoul/text/statistics/wordcount.php on line 11

Any ideas what I'm doing wrong??

Thanks for your help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you use include to include a file, and you use a relative path as parameter, it will be relative to the current working path.

What is the current path? It is normally the path of the first called PHP script. The script where the whole execution started. You can get the current working dir with the function getcwd. For example: <?php echo getcwd(); ?> will show you the current working path. You can change the current working path using the chdir function. For example: <?php chdir( '/home/myself' ); ?> - with this command you just changed the current working path!

So, it is not always good to use relative paths in include, because the current path MAY change.

But with the usage of the __FILE__ magic constant you can use a sort of relative path as a parameter for an include, making it relative to the file where the include command is. This is good! Because no matter what the current working path is, the include will be always relative to the file which is including!

So... try the following:

In B you should include A as follows:

include( dirname( __FILE__ ) . '/../../../phpfunctions/generalfunctions.php' );

In C you should include B as follows:

include( dirname( __FILE__ ) . '/../wordcount.php' );

In short: using dirname( __FILE__ ) you can include the file using a path relative to the file where the "include" command is. Otherwise, the path will be relative to the current working path.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...