How can the PHP function "pathinfo()" be utilized to determine the file extension of a given file, and how can this information be used to selectively delete files based on their extension?
To determine the file extension of a given file using the PHP function "pathinfo()", you can extract the extension by accessing the 'extension' key in the array returned by the function. To selectively delete files based on their extension, you can compare the extracted extension with the desired extension(s) and delete the file if it matches.
$directory = '/path/to/directory/';
$files = scandir($directory);
foreach($files as $file) {
if($file != '.' && $file != '..') {
$fileInfo = pathinfo($directory . $file);
$fileExtension = $fileInfo['extension'];
if($fileExtension == 'txt') { // Change 'txt' to the desired file extension
unlink($directory . $file);
echo "Deleted file: " . $file . "\n";
}
}
}
Related Questions
- What are the potential pitfalls of using the mysql extension in PHP for database connectivity?
- What is the correct usage of the implode function in PHP when dealing with arrays?
- What are the recommended steps for handling user authentication and session management in PHP for beginners to avoid common errors and security risks?