How can PHP be used to ensure that only authorized users have the ability to delete files from the server?
To ensure that only authorized users have the ability to delete files from the server, you can implement a user authentication system in PHP. This system would require users to log in with their credentials before being able to delete files. Once a user is authenticated, their permissions can be checked before allowing them to delete files.
<?php
session_start();
// Check if user is logged in
if(!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
header("Location: login.php");
exit;
}
// Check if user has delete permissions
if($_SESSION['role'] !== 'admin') {
echo "You do not have permission to delete files.";
exit;
}
// Code to delete file
$fileToDelete = "example.txt";
if(file_exists($fileToDelete)) {
unlink($fileToDelete);
echo "File deleted successfully.";
} else {
echo "File not found.";
}
?>