Including files in php

Hi
I try to run the file through the terminal, but I get an error, for example, "include path is not correct"
for example, I have "test.php" in the following folder

/home/sekar/test/file.php 

in the php file, I included the file "head.php", which is located in

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

Thes head.php includes the cls.php class file, which is located in the class folder,

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

I tried this in the terminal,

 php /home/sekar/test/file.php 

for a clear view, just look at the contents of @ these 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 someone help me solve this problem? Thanks!

+6
source share
3 answers

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

In addition, I would investigate the relative paths a bit, since you are referring to the /home/sekar/test/ directory, and not the file 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"; ?> 
+1
source

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

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

 chdir(dirname(__FILE__)); 

Or you can add this directory to the include path:

 set_include_path(dirname(__FILE__) . PATH_SEPARATOR . get_include_path()); 
+1
source

just turn it on as follows

file.php

since both file.php and include are 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, head.php and cls.php, presented in different directories, you have the file as follows.

head.php

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

when you use ../ , it will exit the current directory, and now both the classes and those included in the same directory can include the classes/cls.php .

+1
source

Source: https://habr.com/ru/post/886360/


All Articles