php.chdir()
If you have used a terminal before, whether Windows or Linux, you are probably familiar with the cd
command.
This command allows us to change directory to any location within the filesystem. This enables us to quickly and efficiently switch to various locations in the filesystem without the need for a Graphical Interface.
In this tutorial, we will explore how we can use PHP to change between directories within a filesystem.
PHP chdir() Function
The chdir()
function in PHP allows us to change the directory in PHP. The function syntax is as shown:
chdir(string $directory): bool
The function accepts one parameter:
directory
- the path to the target directory as a string value.
The function returns a Boolean value with True
on success and False
failure.
Example Function Usage
The following example demonstrates how to use the chdir()
function to change the working directory.
<?php
// current directory
echo getcwd() . "\n";
chdir('/var/www');
// current directory
echo getcwd() . "\n";
?>
The above code should change the working directory from pwd
to /var/www
directory. Resulting output:
/home/debian
/var/www
Conclusion
In this post, you learned how you can use the chdir()
function to switch directories in PHP.
If you enjoyed these PHP tutorials, check out other resources down below.