What best practices should be followed when handling file uploads and image manipulation in PHP?

When handling file uploads and image manipulation in PHP, it is important to validate the uploaded file to ensure it is safe and secure. This can be done by checking the file type, size, and ensuring it is not executable. Additionally, when manipulating images, always use libraries like GD or Imagick to prevent security vulnerabilities.

// Validate uploaded file
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $fileType = $_FILES['file']['type'];
    $fileSize = $_FILES['file']['size'];
    
    if (($fileType == 'image/jpeg' || $fileType == 'image/png') && $fileSize < 5000000) {
        // File is safe to upload
        move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
    } else {
        // Invalid file type or size
        echo 'Invalid file type or size.';
    }
}

// Image manipulation with GD
$image = imagecreatefromjpeg('uploads/image.jpg');
$newImage = imagescale($image, 200, 200);
imagejpeg($newImage, 'uploads/thumbnail.jpg');
imagedestroy($image);
imagedestroy($newImage);