首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >图片上传脚本可选上传

图片上传脚本可选上传
EN

Stack Overflow用户
提问于 2015-02-17 02:32:27
回答 2查看 326关注 0票数 0

我试图更改当前的图像上传脚本,因此上传图像是可选的;我自己修改了它,将部分脚本注释掉,但不幸的是,该脚本一直输出错误消息,以显示“不正确的文件类型”。

如果有人能帮忙写剧本,那就太好了,谢谢(Y)

代码语言:javascript
复制
$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>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-02-17 02:46:43

我会把第一个if声明改为这样-

代码语言:javascript
复制
if ( isset( $_FILES["image"] ) && !empty( $_FILES["image"]["name"] ) ) {

然后,在$errors数组中将不会注册错误,因为如果不存在图像文件,当前脚本将落入文件扩展名检查中。

票数 1
EN

Stack Overflow用户

发布于 2016-07-11 07:53:33

代码语言:javascript
复制
$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));
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28553757

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档