How can readdir() be used to find a specific file within a directory in PHP?
To find a specific file within a directory in PHP, you can use the readdir() function along with a loop to iterate through all the files in the directory. Within the loop, you can check each file name against the specific file you are looking for. Once you find the specific file, you can perform the desired actions on it.
$dir = "/path/to/directory";
$specificFile = "example.txt";
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if ($file == $specificFile) {
// Perform actions on the specific file
echo "Found the specific file: " . $file;
break;
}
}
closedir($dh);
}
}