What are the best practices for integrating image uploads in a PHP guestbook script to prevent security vulnerabilities?
To prevent security vulnerabilities when integrating image uploads in a PHP guestbook script, it is important to validate and sanitize user input, check file types and sizes, store uploaded images outside of the web root directory, and generate unique filenames to prevent overwriting existing files.
// Validate and sanitize user input
$allowed_extensions = array('jpg', 'jpeg', 'png', 'gif');
$max_file_size = 5 * 1024 * 1024; // 5MB
if ($_FILES['image']['error'] === UPLOAD_ERR_OK) {
$file_extension = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
if (!in_array($file_extension, $allowed_extensions)) {
die('Invalid file type.');
}
if ($_FILES['image']['size'] > $max_file_size) {
die('File size exceeds limit.');
}
// Store uploaded images outside of the web root directory
$upload_dir = '/path/to/uploads/';
$filename = uniqid() . '.' . $file_extension;
$upload_path = $upload_dir . $filename;
if (move_uploaded_file($_FILES['image']['tmp_name'], $upload_path)) {
// Image uploaded successfully
} else {
die('Failed to upload image.');
}
}