Relative Paths in PHP
As you already know, the parameter of the function file_get_contents
should contain the filename. However, this only works
if the file being read is located
in the same folder where our script is running.
If the file is located elsewhere, then the parameter of the function must contain the path to that file.
Let's look at an example.
Example
Suppose we have the following file structure:
- index.php
- /directory/
- test.txt
Let's read the contents of the text file. To do this, besides the filename, we will need to specify the folder where it is located:
<?php
echo file_get_contents('directory/test.txt');
?>
Example
Suppose we have the following file structure:
- /script/
- index.php
- test.txt
In this case, an attempt to read our file by specifying its name as the path will end with an error:
<?php
echo file_get_contents('test.txt'); // will output an error
?>
Why is an error issued? The fact is that we wrote the filename in the function parameter. This means that the file being read should be located in the same folder as the executable one.
However, our file to be read is one level higher, that is, in the folder that contains the folder with the script.
In this case, we must explicitly indicate in the path
to the file that this file should be searched for one level
higher. To do this, write ../ before the filename. Let's do this:
<?php
echo file_get_contents('../test.txt'); // the file will be read
?>
Example
Suppose we have the following file structure:
- /script/
- index.php
- /directory/
- test.txt
In this case, when reading the file, we will first go up one level, and then specify the path to our file relative to that level:
<?php
echo file_get_contents('../directory/test.txt');
?>
Example
Suppose we have the following file structure:
- /script/
- /test/
- index.php
- /test/
- /directory/
- test.txt
In this case, we will need to go up two times:
<?php
echo file_get_contents('../../directory/test.txt');
?>
Practical Tasks
Write code that will read the contents of a text file:
- index.php
- /dir1/
- /dir2/
- test.txt
- /dir2/
Write code that will read the contents of a text file:
- /script/
- index.php
- /dir1/
- /dir2/
- test.txt
- /dir2/
Write code that will read the contents of a text file:
- /script1/
- /script2/
- index.php
- /script2/
- /dir/
- test.txt
Write code that will read the contents of a text file:
- /script1/
- /script2/
- /script3/
- index.php
- /script3/
- /script2/
- /dir1/
- /dir2/
- /dir3/
- test.txt
- /dir3/
- /dir2/