What best practices should be followed when handling image uploads and displaying them using PHP?

When handling image uploads and displaying them using PHP, it is important to validate the uploaded file to ensure it is an actual image file and not a malicious script. Additionally, it is recommended to store the uploaded images in a secure directory outside the web root to prevent direct access. When displaying the images, use proper image headers and content-type to prevent any vulnerabilities.

// Handle image upload
if(isset($_FILES['image'])){
    $file_name = $_FILES['image']['name'];
    $file_tmp = $_FILES['image']['tmp_name'];
    
    // Validate file type
    $file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
    $allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
    
    if(in_array($file_ext, $allowed_ext)){
        // Move uploaded file to secure directory
        move_uploaded_file($file_tmp, 'uploads/'.$file_name);
    }
}

// Display uploaded image
$image_path = 'uploads/'.$file_name;
header('Content-Type: image/jpeg');
readfile($image_path);