开发者

including files in php

HI,

I try to run a file thru terminal but am getting the error like "include path is not correct"

for example, i have a "test.php" in following folder

/home/sekar/test/file.php  

in file php i've included a f开发者_运维知识库ile "head.php" which is in ,

/home/sekar/test/includes/head.php

Thes head.php includes a class file called cls.php which is in class folder,

/home/sekar/test/classes/cls.php

i tried like this in terminal,

php /home/sekar/test/file.php

for a clear a view just have a look @ contents of the those three files,

file.php

<?php 
include_once "./test/includes/head.php";
?>

head.php

<?php 
include_once "./test/classes/cls.php";
?>

cls.php

<?php 
echo "this is from cls file";
?>

Can anyone help me to get around this issue? Thanks!


I think that include_once() basically inserts code into your file without evaluating it, so the path is relative to that of the including file (file.php, not head.php).

Also, I'd do a bit of research on relative paths, as you're referencing from the directory /home/sekar/test/, not the file's path.

This might work:

file.php

<?php 
include_once "./includes/head.php";
?>

head.php

<?php 
include_once "../classes/cls.php";
?>

cls.php

<?php 
echo "this is from cls file";
?>


PHP includes are relative to the set include_path, the first element of which is . or the current working directory. The current working directory does not have to be the same as the directory your PHP file is in, and it does not have to be the same as your home directory (which you seem to be assuming). There are two ways to solve your problem.

You can change the current working directory of your scripts by adding this to the top of file.php:

chdir(dirname(__FILE__));

Or, you can add that directory to the include path:

set_include_path(dirname(__FILE__) . PATH_SEPARATOR . get_include_path());


just include it as follows

file.php

as both file.php and includes directory is in the current(same) directory(test) you can include the head.php file as follows

<?php 
include_once "includes/head.php";
?>

here in head.php the head.php and cls.php both presented in different directories you have include the file as follows.

head.php

<?php 
include_once "../classes/cls.php";
?>

when you use ../ it will come out from current directory and now both the classess and includes presented under the same directory you can include the path classes/cls.php now.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜