In PHP, chdir() changes the current working directory to a folder you choose. After that, relative paths like 'data.txt' are looked up inside the new folder.
Every running PHP script has a current working directory, which is the folder PHP uses when you write a relative path. chdir() moves that starting point. It returns true on success and false (plus a warning) if the folder does not exist or cannot be entered.
Syntax
Call chdir() with the values you need. Start with this line.
PHP
chdir(__DIR__ . '/uploads');
Call
What it does
chdir(__DIR__ . '/uploads')
Moves into the uploads folder that sits next to the script.
chdir('..')
Moves up one level to the parent folder.
chdir(__DIR__)
Moves back to the folder that holds the current script.
chdir() only changes where relative paths start. It does not change __DIR__, which always points to the folder of the file being run. Use getcwd() to see where you are now.
Library declarations
PHP
chdir(string $directory): bool
Parameters
Parameter
Description
directory
Required. The path of the folder to move into. It can be absolute, like /var/www/data, or relative, like .. or uploads.
Return Value
Return Value
Description
bool
Returns true if the working directory was changed. Returns false on failure, for example when the folder does not exist, and PHP also raises an E_WARNING.
PHP Examples
Example 1 — Moving Into a Folder and Using a Relative Path
We create a small demo folder with one file, move into it with chdir(), and then open the file using only its name.
mkdir() with true as the third argument creates the outer and inner folders together.
chdir() moves into inner, and basename(getcwd()) prints just the folder name.
chdir('. .') moves up one level, back into demo-chdir-tree.
We return to __DIR__ first, because a folder cannot be removed while the script is standing inside it.
Frequently Asked Questions
It changes the current working directory of your script. After the change, any relative file path, such as 'data.txt' or 'images/logo.png', is resolved starting from the new folder.
No. __DIR__ is fixed to the folder of the file that contains it. chdir() only affects the working directory, which you can read with getcwd().
It returns false and raises an E_WARNING. The working directory does not change. Check the result, or test with is_dir() first, before relying on the new folder.
On Windows, a folder that is in use as the working directory is locked. Move out with chdir(__DIR__) or chdir('..') first, and then call rmdir().
Absolute paths built with __DIR__ are usually safer because they do not depend on a hidden global setting. Use chdir() when a script or library really needs relative paths to start from a certain folder.