chdir() : Change directory
PHP Directory
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.
To change from current directory to one step up directory
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 ";
}
Example 1: Changing to Parent Directory
<?php
echo getcwd();
chdir('..');
echo "<br> New Directory: " . getcwd();
?>
Example 2: Handling Non-Existent Directory
<?php
if (!chdir('invalid_dir')) {
echo "Directory does not exist.";
}
?>
← Directory Functions
getcwd() : Get current directory →
scandir(): List files and directories →
← Subscribe to our YouTube Channel here
This article is written by plus2net.com team.
https://www.plus2net.com
plus2net.com