What are common pitfalls when implementing a file upload form in PHP?

One common pitfall when implementing a file upload form in PHP is not properly securing the uploaded files. To prevent security vulnerabilities such as file injections and malicious uploads, 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 secure file uploads in PHP

// Specify allowed file types
$allowed_types = array('jpg', 'jpeg', 'png', 'gif');

// Specify maximum file size in bytes
$max_size = 5242880; // 5MB

// Specify upload directory outside of web root
$upload_dir = '/path/to/upload/directory/';

// Check if file type is allowed
if (!in_array(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION), $allowed_types)) {
    echo 'Invalid file type. Allowed types: jpg, jpeg, png, gif';
    exit;
}

// Check if file size is within limit
if ($_FILES['file']['size'] > $max_size) {
    echo 'File size exceeds limit (5MB)';
    exit;
}

// Move uploaded file to secure directory
if (move_uploaded_file($_FILES['file']['tmp_name'], $upload_dir . $_FILES['file']['name'])) {
    echo 'File uploaded successfully';
} else {
    echo 'Error uploading file';
}