What are the best practices for handling image files in PHP scripts?

When handling image files in PHP scripts, it is important to validate and sanitize user input to prevent security vulnerabilities such as file upload attacks. It is also recommended to store images outside of the web root directory to prevent direct access. Additionally, resizing and optimizing images can improve performance and reduce load times on web pages.

// Example of validating and handling image file upload
if(isset($_FILES['image'])){
    $file_name = $_FILES['image']['name'];
    $file_tmp = $_FILES['image']['tmp_name'];
    
    // Validate file type
    $allowed_extensions = array('jpg', 'jpeg', 'png', 'gif');
    $file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
    
    if(in_array($file_extension, $allowed_extensions)){
        // Move file to secure directory
        $upload_path = 'uploads/';
        $new_file_name = uniqid() . '.' . $file_extension;
        
        if(move_uploaded_file($file_tmp, $upload_path . $new_file_name)){
            echo 'File uploaded successfully!';
        } else {
            echo 'Error uploading file.';
        }
    } else {
        echo 'Invalid file type. Only JPG, JPEG, PNG, GIF files are allowed.';
    }
}