What are some best practices for handling user-uploaded images in a PHP and MySQL environment?

When handling user-uploaded images in a PHP and MySQL environment, it is important to validate and sanitize the uploaded file to prevent security vulnerabilities such as SQL injection or file execution. Additionally, it is recommended to store the images outside of the web root directory to prevent direct access. Finally, consider resizing and optimizing the images for better performance.

// Example code snippet for handling user-uploaded images in PHP
if(isset($_FILES['image'])){
    $file_name = $_FILES['image']['name'];
    $file_tmp = $_FILES['image']['tmp_name'];
    
    // Validate file type
    $file_ext = strtolower(end(explode('.', $file_name)));
    $allowed_extensions = array('jpg', 'jpeg', 'png', 'gif');
    if(in_array($file_ext, $allowed_extensions)){
        // Sanitize file name
        $file_name = preg_replace("/[^a-zA-Z0-9.]/", "", $file_name);
        
        // Move file to secure directory
        $upload_dir = 'uploads/';
        move_uploaded_file($file_tmp, $upload_dir . $file_name);
        
        // Save file path to database
        $file_path = $upload_dir . $file_name;
        // Insert $file_path into MySQL database
    } else {
        echo 'Invalid file type. Only JPG, JPEG, PNG, GIF files are allowed.';
    }
}