Are there any common pitfalls or security risks to be aware of when working with file uploads in PHP?

One common pitfall when working with file uploads in PHP is not properly validating and sanitizing user input. This can lead to security risks such as file injection attacks or allowing malicious files to be uploaded to the server. To mitigate these risks, always validate file types, limit file sizes, and store uploaded files in a secure directory outside of the web root.

// Validate file type
$allowed_file_types = array('jpg', 'jpeg', 'png', 'gif');
$uploaded_file_type = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if (!in_array($uploaded_file_type, $allowed_file_types)) {
    die('Invalid file type. Only JPG, JPEG, PNG, and GIF files are allowed.');
}

// Limit file size
$max_file_size = 5 * 1024 * 1024; // 5 MB
if ($_FILES['file']['size'] > $max_file_size) {
    die('File size exceeds the limit of 5 MB.');
}

// Store uploaded file in a secure directory
$upload_dir = '/path/to/secure/directory/';
$upload_file = $upload_dir . basename($_FILES['file']['name']);
if (!move_uploaded_file($_FILES['file']['tmp_name'], $upload_file)) {
    die('Failed to upload file.');
}