How to change directory of the running PHP script

Photo from Unsplash

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:


// current directory
echo getcwd() . "\n";

// change directory

// current directory
echo getcwd() . "\n";


When you run the example above, the output should be similar as follows:


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.

Get 98 PHP Snippets Book for FREE 🔥

98 PHP snippets that you can use in various scenarios

Save 1000+ hours of research and 10x your productivity