In PHP, directories are managed using functions provided by the files system-related extensions. Here are some key functions and concepts related to working with directores in PHP:
Function | Uses |
chdir() | Changes current directory |
chroot() | Change the root directory |
dir() | instance of the Directory class |
closedir() | |
getcwd() | Gets the current working directory |
opendir() | Opens the current working directory |
rewinddir() | Rewind directory handle |
scandir() | List files and directories inside the specified path |
These are some of the basic functions and concepts related to working with directories in PHP. They allow you to perform various operations such as listing files, creating directories, checking if a path is a directory, and more.
The chdir() function changes the current directory.
chdir($directory)
<?php
echo getcwd() . "\n";
// change to php directory
chdir('php');
echo getcwd() . "\n";
?>
The chroot() function changes the root directory to the passed directory.
Before using this function on our machine we need to configure –enable-chroot-func.
<?php
chroot(directory);
?>
<?php
chroot('/learncoding/dev/php');
?>
The dir() function is used to open a directory handle. This function returns a Directory class object that provides methods for working with the contents of the directory.
<?php
dirhandle bool dir(string $directory )
?>
<?php
$d = dir("/learncoding/dev/php");
echo "Handle: " . $d->handle . "\n";
echo "Path: " . $d->path . "\n";
while (false !== ($entry = $d->read())) {
echo $entry."\n";
}
$d->close();
?>
The getcwd() function gives the current working directory in PHP.
<?php
getcwd();
?>
<?php
echo getcwd();
?>
The opendir() function opens a directory handle in PHP.
<?php
opendir(path, context)
?>
<?php
$dir = opendir("/lerncoding/dev/dev");
while (($file = readdir($dir)) !== false) {
echo "filename: " . $file . "<br />";
}
closedir($dir);
?>
The readdir() function returns the name of the best entry in a directory in php.
<?php
readdir(directory)
?>
<?php
$dir = opendir("/lerncoding/dev/dev");
while (($file = readdir($dir)) !== false) {
echo "filename: " . $file . "<br />";
}
closedir($dir);
?>
In PHP, the rewinddir() function is used to reset the directory stream represented by the given directory handle (obtained using opendir()) back to the beginning.
<?php
rewinddir(directory)
?>
<?php
$direc = opendir("/learncoding/dev/php");
while (($file =rewinddir($direc)) !== false) {
echo "filename: " . $file . "<br />";
}
rewinddir($direc);
while (($file =rewinddir($direc)) !== false) {
echo "filename: " . $file . "<br />";
}
closedir($direc);
?>
The scandir() function is used to return an array of files and directories in a given directory in PHP.
<?php
scandir(directory, order, context):
?>
<?php
$dir = '/learnCoding';
// acesding order - default
$store1 = scandir($dir);
// Sort in decending order
$store2 = scandir($dir, 1);
print_r($file1);
print_r($file2);
?>