Are there any potential pitfalls to consider when using PHP for file uploads?

One potential pitfall when using PHP for file uploads is the risk of allowing malicious files to be uploaded to your server. To prevent this, always validate file types and sizes before allowing them to be uploaded. Additionally, consider storing uploaded files outside of the web root to prevent direct access.

// Check file type before allowing upload
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($_FILES['file']['type'], $allowedTypes)) {
    die('Invalid file type. Please upload a JPEG, PNG, or GIF file.');
}

// Check file size before allowing upload
$maxFileSize = 5242880; // 5MB
if ($_FILES['file']['size'] > $maxFileSize) {
    die('File is too large. Please upload a file smaller than 5MB.');
}

// Store uploaded file outside of web root
$uploadDir = '/path/to/uploads/';
$uploadFile = $uploadDir . basename($_FILES['file']['name']);
move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile);