What security risks are associated with directly using user input in functions like unlink() without proper validation?
Directly using user input in functions like unlink() without proper validation can lead to security risks such as directory traversal attacks or unauthorized file deletions. To mitigate these risks, it is essential to validate and sanitize user input before passing it to functions that interact with the file system.
// Validate and sanitize user input before using it in unlink()
$user_input = $_POST['file_name']; // Assuming user input comes from a form field
// Validate user input to ensure it is a valid file name
if (preg_match('/^[a-zA-Z0-9-_\.]+$/', $user_input)) {
// Sanitize user input to prevent directory traversal attacks
$file_path = 'uploads/' . basename($user_input);
// Use the sanitized file path in the unlink() function
if (file_exists($file_path)) {
unlink($file_path);
echo 'File deleted successfully.';
} else {
echo 'File not found.';
}
} else {
echo 'Invalid file name.';
}