Reputation: 743
I am trying to change my current image upload script so uploading an image is optional; I have modified it myself by commenting out parts of the script but unfortunately the script keeps outputting the error message for 'incorrect file type'.
If Anyone could help with how the script should be that would be great thanks (Y)
$image = '';
if (isset($_FILES['image']) === true) {
$max_file_size = 2000000;
/*if (empty($_FILES['image']['name']) === true) {
$errors['image'] = "You have not chosen a image";
} */ if( $_FILES['image']['size'] > $max_file_size ) {
$errors['image'] = "File size too large";
} else {
$allowed = array('jpg', 'JPG', 'jpeg', 'gif', 'png', 'PNG',);
$file_name = $_FILES['image']['name'];
$file_extension = end((explode('.', $file_name)));
$file_temp = $_FILES['image']['tmp_name'];
if (in_array($file_extension, $allowed) === true) {
$new_file_name = substr(md5(time()), 0, 10) . '.' . $file_extension;
$image = $file_path = 'images/collections/' . $new_file_name;
move_uploaded_file($file_temp, $file_path);
} else {
$errors['image'] = 'Incorrect file type. Allowed: ' . (implode(', ', $allowed));
}
}
}
<?php if (isset($errors['image'])/* && !empty($errors['image'])*/):?>
<p class="c-img-error"><?php echo $errors['image']; ?></p>
<?php endif ;?>
<div class="browse"><input type="file" name="image" value="" /> <span></span></div>
Upvotes: 0
Views: 340
Reputation: 93
$image = '';
if (isset( $_FILES["image"] ) && !empty( $_FILES["image"]["name"] ) ) {
$max_file_size = 2000000;
/*if (empty($_FILES['image']['name']) === true) {
$errors['image'] = "You have not chosen a image";
} */ if( $_FILES['image']['size'] > $max_file_size ) {
$errors['image'] = "File size too large";
} else {
$allowed = array('jpg', 'JPG', 'jpeg', 'gif', 'png', 'PNG',);
$file_name = $_FILES['image']['name'];
$file_extension = end((explode('.', $file_name)));
$file_temp = $_FILES['image']['tmp_name'];
if (in_array($file_extension, $allowed) === true) {
$new_file_name = substr(md5(time()), 0, 10) . '.' . $file_extension;
$image = $file_path = 'images/collections/' . $new_file_name;
move_uploaded_file($file_temp, $file_path);
} else {
$errors['image'] = 'Incorrect file type. Allowed: ' . (implode(', ', $allowed));
}
}
}
Upvotes: 0
Reputation: 331
I'd change the first if statement to read as so -
if ( isset( $_FILES["image"] ) && !empty( $_FILES["image"]["name"] ) ) {
Then no errors will be registered in the $errors array, as the current script is falling into the file extension check if no image file exists.
Upvotes: 1