我正在尝试更改当前的图片上传脚本,因此上传图片是可选的;我自己通过注释掉脚本的一部分来修改它,但遗憾的是脚本不断输出错误消息“错误的文件类型”。
如果有人可以帮助解决脚本的问题,那将非常感谢(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>
答案 0 :(得分:0)
我将第一个if语句更改为如此 -
if ( isset( $_FILES["image"] ) && !empty( $_FILES["image"]["name"] ) ) {
然后$ errors数组中不会记录任何错误,因为如果没有图像文件,当前脚本将进入文件扩展名检查。
答案 1 :(得分:0)
$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));
}
}
}