What are the potential security risks associated with PHP image uploads and how can they be mitigated?
Potential security risks associated with PHP image uploads include allowing malicious files to be uploaded (e.g. scripts disguised as images) and potential file inclusion vulnerabilities. To mitigate these risks, it is important to validate file types, restrict file sizes, and store uploaded files outside of the web root directory.
// Validate file type
$allowed_extensions = array('jpg', 'jpeg', 'png', 'gif');
$upload_extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if (!in_array($upload_extension, $allowed_extensions)) {
die('Invalid file type. Only JPG, JPEG, PNG, and GIF files are allowed.');
}
// Restrict file size
$max_file_size = 5 * 1024 * 1024; // 5MB
if ($_FILES['file']['size'] > $max_file_size) {
die('File size exceeds the limit of 5MB.');
}
// Store uploaded file outside of web root directory
$upload_dir = '/path/to/upload/directory/';
$upload_file = $upload_dir . basename($_FILES['file']['name']);
move_uploaded_file($_FILES['file']['tmp_name'], $upload_file);