Changes the current working directory of the running PHP process.
What Is chdir() in PHP?
Changes the current working directory of the running PHP process.
Its syntax is:
chdir(string $directory): bool
Parameters:
$directory— Accepted as string; required argument.
Return type: bool. Changing the working directory affects later relative paths in the same process. Restore it when necessary.
Availability: Filesystem permissions apply.
Example 1: Basic Usage
<?php
var_dump(chdir(sys_get_temp_dir()));
Result: Results and availability depend on the current PHP process, system permissions, cache, filesystem or installed locale. Changing the working directory affects later relative paths in the same process. Restore it when necessary.
Example 2: A Different Input
<?php
echo getcwd();
Result: Results and availability depend on the current PHP process, system permissions, cache, filesystem or installed locale. Changing the working directory affects later relative paths in the same process. Restore it when necessary.
Practical Example: Applying It in a Program
<?php
$originalDirectory = getcwd(); $temporaryDirectory = sys_get_temp_dir(); if (chdir($temporaryDirectory)) { echo basename(getcwd()); chdir($originalDirectory); }
Result: Results and availability depend on the current PHP process, system permissions, cache, filesystem or installed locale. Changing the working directory affects later relative paths in the same process. Restore it when necessary.
Important Behavior and Edge Cases
- Key behavior: Changing the working directory affects later relative paths in the same process. Restore it when necessary.
- Environment: Filesystem permissions apply.
Comparison With Related Functions
| Function | Purpose |
|---|---|
chdir() | Changes the current working directory of the running PHP process. |
getcwd() | getcwd() reads the process working directory; chdir() changes it. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring this behavior: Changing the working directory affects later relative paths in the same process | Changing the working directory affects later relative paths in the same process. Restore it when necessary. |
Key Takeaways
- Changes the current working directory of the running PHP process.
- Changing the working directory affects later relative paths in the same process. Restore it when necessary.
- Filesystem permissions apply.
Summary: Changing the working directory affects later relative paths in the same process. Restore it when necessary.