What are the key considerations when uploading files in PHP, especially in terms of file size and file type validation?

When uploading files in PHP, it is important to consider the file size and file type to ensure security and prevent issues such as exceeding server limits or allowing potentially harmful files to be uploaded. To address these concerns, you can set maximum file size limits and validate file types before allowing the upload to proceed.

// Set maximum file size limit (in bytes)
$maxFileSize = 5242880; // 5MB

// Allowed file types
$allowedFileTypes = ['jpg', 'jpeg', 'png', 'gif'];

// Get uploaded file information
$fileName = $_FILES['file']['name'];
$fileSize = $_FILES['file']['size'];
$fileType = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

// Check file size
if ($fileSize > $maxFileSize) {
    echo "File size exceeds limit.";
    exit;
}

// Check file type
if (!in_array($fileType, $allowedFileTypes)) {
    echo "Invalid file type.";
    exit;
}

// Process file upload
// Add your file upload code here