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

One potential security risk associated with file uploads in PHP is the possibility of allowing users to upload malicious files that can harm the server or compromise sensitive data. To mitigate this risk, it is important to validate file types, limit file sizes, and store uploaded files in a secure directory outside of the web root.

// Example code to validate file uploads in PHP
$allowed_types = ['image/jpeg', 'image/png'];
$max_size = 1048576; // 1MB

if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $file_type = $_FILES['file']['type'];
    $file_size = $_FILES['file']['size'];

    if (in_array($file_type, $allowed_types) && $file_size <= $max_size) {
        $upload_dir = '/path/to/secure/directory/';
        $upload_file = $upload_dir . basename($_FILES['file']['name']);

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