What are some potential pitfalls when using PHP for file uploads?
One potential pitfall when using PHP for file uploads is not properly validating the file type before allowing it to be uploaded. This can lead to security vulnerabilities such as allowing malicious files to be uploaded and executed on the server. To solve this, always validate the file type using the `$_FILES['file']['type']` property and only allow specific file types to be uploaded.
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($_FILES['file']['type'], $allowedTypes)) {
die('Invalid file type. Only JPEG, PNG, and GIF files are allowed.');
}
```
Another potential pitfall is not setting a maximum file size limit for uploads. This can result in users uploading large files that consume server resources and slow down the application. To solve this, set a maximum file size limit using the `upload_max_filesize` and `post_max_size` directives in the php.ini file.
```php
if ($_FILES['file']['size'] > 1048576) { // 1MB
die('File size is too large. Maximum file size allowed is 1MB.');
}