chdir

chdir($directory)

Changes the working folder of the script. Relative paths (without / at the start) are then calculated from the new folder. It returns true, or a warning and false on error.

Parameters

  • $directory – the new working folder.

Examples

$original = getcwd();
$folder = sys_get_temp_dir() . "/garth-example";
mkdir($folder);
file_put_contents($folder . "/a.txt", "x");
var_dump(chdir($folder)); // bool(true)
echo basename(getcwd()); // garth-example
// relative paths are calculated from the new folder
var_dump(file_exists("a.txt")); // bool(true)
// going back
chdir($original);
var_dump(getcwd() === $original); // bool(true)
// a missing folder (@ suppresses the warning)
var_dump(@chdir($folder . "/none")); // bool(false)
unlink($folder . "/a.txt");
rmdir($folder);

Things to watch out for

  • It changes the working folder for the whole rest of the script, including include and require with a relative path. Absolute paths with __DIR__ are more reliable.
  • On the web the default working folder is usually the folder of the running script, on the command line the folder the script was run from.
  • A missing folder or a path to a file prints a warning and returns false.

Related functions:
getcwd()
dirname()
realpath()
mkdir()