What are the potential security risks associated with image hosting scripts in PHP?

Image hosting scripts in PHP can pose security risks such as allowing users to upload malicious files, potential server overload due to large file sizes, and vulnerabilities that can be exploited by hackers. To mitigate these risks, it is crucial to implement proper file type checking, file size limitations, and secure file storage practices.

// Example code snippet for secure file upload in PHP
<?php
$allowed_extensions = array('jpg', 'jpeg', 'png', 'gif');
$max_file_size = 5 * 1024 * 1024; // 5MB

if(isset($_FILES['image'])){
    $file_name = $_FILES['image']['name'];
    $file_size = $_FILES['image']['size'];
    $file_tmp = $_FILES['image']['tmp_name'];
    $file_type = $_FILES['image']['type'];
    
    $file_extension = strtolower(end(explode('.', $file_name)));
    
    if(!in_array($file_extension, $allowed_extensions)){
        die("Invalid file type. Allowed file types are jpg, jpeg, png, gif.");
    }
    
    if($file_size > $max_file_size){
        die("File size exceeds the limit of 5MB.");
    }
    
    move_uploaded_file($file_tmp, "uploads/" . $file_name);
    echo "File uploaded successfully.";
}
?>