What potential security risks are associated with handling file uploads in PHP?

One potential security risk associated with handling file uploads in PHP is the possibility of allowing malicious files to be uploaded to the server, which can then be executed to compromise the system. To mitigate this risk, it is important to validate file types, limit file sizes, and store uploaded files in a secure location outside the web root directory.

// Validate file type and limit file size before uploading
$allowedFileTypes = ['jpg', 'jpeg', 'png', 'gif'];
$maxFileSize = 1048576; // 1MB

if (in_array(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION), $allowedFileTypes) && $_FILES['file']['size'] <= $maxFileSize) {
    $uploadDir = 'uploads/';
    $uploadFile = $uploadDir . basename($_FILES['file']['name']);

    if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
        echo "File uploaded successfully.";
    } else {
        echo "Error uploading file.";
    }
} else {
    echo "Invalid file type or file size too large.";
}