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.

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.