What are common issues when uploading images in PHP, and how can they be resolved?
One common issue when uploading images in PHP is the file size limitation set by the server. This can be resolved by adjusting the PHP configuration settings to allow larger file uploads.
// Adjust PHP configuration settings to allow larger file uploads
ini_set('upload_max_filesize', '10M');
ini_set('post_max_size', '10M');
```
Another common issue is handling file type validation to ensure that only image files are uploaded. This can be resolved by checking the file type before processing the upload.
```php
// Check file type before processing the upload
$allowedExtensions = array('jpg', 'jpeg', 'png', 'gif');
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if (!in_array($extension, $allowedExtensions)) {
echo 'Invalid file type. Only JPG, JPEG, PNG, and GIF files are allowed.';
exit;
}
```
Additionally, preventing duplicate file names can be an issue when uploading images. This can be resolved by generating a unique file name for each uploaded image.
```php
// Generate a unique file name for each uploaded image
$fileName = uniqid() . '_' . $_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $fileName);