How to change directory of the running PHP script
PHP allows you to change the current working directory by calling the chdir() function.
The chdir() function accepts a string parameter for the new directory you want to access:
chdir(string $directory): bool
PHP also has the getcwd() function that returns the current working directory. You can use this function to check whether the directory successfully changes or not
Here’s an example:
<?php
// current directory
echo getcwd() . "\n";
// change directory
chdir('Documents');
// current directory
echo getcwd() . "\n";
?>
When you run the example above, the output should be similar as follows:
/home/nsebhastian
/home/nsebhastian/Documents
Please note that chdir() function doesn’t create a new directory.
If the directory you specified doesn’t exist, then the function will produce a warning as shown below:
Warning: chdir(): No such file or directory (errno 2)
in ... on line ...
And that’s how you change directory using PHP.
More PHP tutorials
See allPHP
PHP form validation basic example
Dec 22, 2022
PHP
PHP validate email address (with code examples)
Dec 22, 2022
PHP
How to redirect using PHP with code examples
Dec 22, 2022
PHP
Handling form data using PHP (GET and POST)
Dec 21, 2022
PHP
How to fix Wordpress PHP error missing MySQL extension
Dec 21, 2022