What are the best practices for handling file uploads and image resizing in PHP scripts?
When handling file uploads and image resizing in PHP scripts, it is important to validate the uploaded file, check for errors, and move the file to a secure location on the server. Additionally, resizing images can help optimize file size and improve loading times on web pages. Using libraries like GD or Imagick can simplify the resizing process.
// Check if file was uploaded without errors
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
// Validate file type and size
$allowed_types = ['image/jpeg', 'image/png'];
$max_size = 5 * 1024 * 1024; // 5MB
if (in_array($_FILES['file']['type'], $allowed_types) && $_FILES['file']['size'] <= $max_size) {
// Move uploaded file to secure location
$upload_dir = 'uploads/';
$upload_file = $upload_dir . basename($_FILES['file']['name']);
move_uploaded_file($_FILES['file']['tmp_name'], $upload_file);
// Resize image using GD library
$image = imagecreatefromjpeg($upload_file);
$resized_image = imagescale($image, 200, 200);
imagejpeg($resized_image, $upload_dir . 'resized_' . $_FILES['file']['name']);
// Free up memory
imagedestroy($image);
imagedestroy($resized_image);
} else {
echo 'Invalid file type or size';
}
} else {
echo 'Error uploading file';
}