For most file operations, absolute paths based on __DIR__ are easier to reason about. If a script really needs to change the current working directory, validate the target first and restore the previous directory when the temporary work is complete.
<?php
$target = __DIR__ . '/test_dir';
$previous = getcwd();
if (!is_dir($target)) {
throw new RuntimeException('Target directory does not exist.');
}
if ($previous === false || !chdir($target)) {
throw new RuntimeException('Unable to change directory.');
}
try {
echo htmlspecialchars((string) getcwd(), ENT_QUOTES, 'UTF-8');
} finally {
chdir($previous);
}
?>
Avoid suppressing errors with @chdir(). Test the path and handle a failed return value explicitly.
echo getcwd();
chdir('test_dir');
echo "<br>";
echo getcwd();
Output of above code is here
J:\php_files\t\dir
J:\php_files\t\dir\test_dir
chdir() to change the directory to a different one. This function returns true on success and false on Failure. We have used getcwd() function to get the current directory location.
echo getcwd();
chdir('..');
echo "<br>";
echo getcwd();
As chdir() returns TRUE or FALSE we can use if condition to post message.
echo getcwd();
echo "<br>";
if(chdir('test_dir2')){
echo getcwd();
}else{
echo " Wrong Directory ";
}
<?php
echo getcwd();
chdir('..');
echo "<br> New Directory: " . getcwd();
?>
<?php
if (!chdir('invalid_dir')) {
echo "Directory does not exist.";
}
?>
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.