Content · Programming · PHP

PHP chdir() Function: Usage and Examples

Learn how PHP chdir works with practical examples, important behavior, relevant alternatives and common mistakes.

1 views Published Oct 16, 2026 Updated Oct 16, 2026

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

FunctionPurpose
chdir()Changes the current working directory of the running PHP process.
getcwd()getcwd() reads the process working directory; chdir() changes it.

Common Beginner Mistakes

MistakeCorrect Approach
Ignoring this behavior: Changing the working directory affects later relative paths in the same processChanging 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.

Share this resourceSend this page to someone who may find it useful.