javascript - 表单尝试处理不存在的图像

标签 javascript php mysql

我正在建立一个博客。我的客户希望在必要时(但并非总是)可以选择上传图像。我编写了代码来执行此操作,但我认为我错过了一些东西。非常感谢任何愿意帮助我调试的人。

if (!in_array($file_ext,$allowed_ext)) {
  $errors[] = strtoupper($file_ext).'\'s is not an approved file extension. Please try again. Approved extensions are '.implode(',', $allowed_ext).'.';
}

上面的代码片段来自下面的页面,并且是不断触发的错误。

if (empty($_POST) === false) {

    $allowed_ext = array('jpg','jpeg','png');
    if (isset($_FILES['image']) && !empty($_FILES['image'])) {
        $file_name = $_FILES['image']['name']; 
        $file_ext = strtolower(end(explode('.', $file_name)));
        $file_size = $_FILES['image']['size'];
        $file_tmp = $_FILES['image']['tmp_name'];
        if (!in_array($file_ext,$allowed_ext)) {
            $errors[] = strtoupper($file_ext).'\'s is not an approved file extension. Please try again. Approved extensions are '.implode(',', $allowed_ext).'.';
        } else if ($file_size > 655360) {
            $errors[] = 'File Size to large. Please try a different image';
        }
    }

    if (empty($errors) === true) {
        if (isset($_FILES['image']) === true && empty($_FILES['image']) === false) {
        $file_name = md5($file_name).'.'.$file_ext;
        move_uploaded_file($file_tmp, '../assets/images/'.$file_name);
        $image_location = 'assets/images/'.$file_name;
        }
        $data = array(
            'title'         => $_POST['title'],
            'category_id'   => $_POST['category_id'],
            'author_id'     => $session_user_id,
            'author_name'   => $user_data['admin_name'],
            'summary'       => $_POST['summary'],
            'contents'      => nl2br($_POST['content']),
            'image'         => $image_location,
            'date'          => date("F j, Y"),
            'time'          => date("h:i a e")
        );
        echo 'Something Cool';
        insertPost($db, $data);
        header('Location: new.php?success');
    }
}
    echo '<div id="page-wrapper">';
        echo '<div class="row">';

?>
        <div class="col-lg-12">
                <h1>Write a new post <small></small></h1>
                <ol class="breadcrumb">
                  <li><a href="index.php" class="fa fa-dashboard"> Dashboard</a></li>
                  <li>Write A New Post</li>
                </ol>           
            </div>
        </div>
        <?php 
        if (isset($_GET['success']) === true && empty($_GET['success']) === true) {
            $success = '
            <div class="alert alert-success">
                <h4>Blog Post Successively Submitted</h4>
                <p>Your blog post was successfully submitted to the database. Go check it out on the <a href="../index.php">homepage</a>!
            </div>
            ';
            echo $success;
        } else {
            if (empty($errors) === false) {
                echo '<div class="alert alert-danger"><srong>After trying to process your request, the following errors occured:</strong>';
                echo output_errors($errors);
                echo '</div>';
            }
        ?>
        <form action="" method="post" enctype="multipart/form-data">
        <div class="col-lg-6 col-sm-12">
            <div class="form-group">
                <label for="title">Title</label><br>
                <input name="title" type="text" class="form-control" placeholder="Title of Post" required/>
            </div>

            <div class="form-group">
                <label for="category_id">Category</label><br>

                        <select name="category_id" class="form-control">
                            <option value=""> --Select a Category-- </option>
                            <?php
                            $query = $db->prepare("SELECT category_id, category_name FROM catagories");
                            $query->execute();
                            while ($result = $query->fetch(PDO::FETCH_ASSOC)) {
                                echo '<option value="'.$result['category_id'].'">'.$result['category_name'].'</option>';
                            }
                            ?>
                        </select>

            </div>
            <div class="form-group">
                <label for="summary">Summary</label><br>

                        <textarea name="summary" class="form-control" rows="3" placeholder="Summary of your post. Keep it short and simple as this is what will be displayed on the homepage"></textarea>

            </div>
            <div class="form-group">
                <label for="content">Content</label><br>
                <textarea id="wysihtml5-textarea" class="textarea-wysiwyg form-control" rows="10" name="content" placeholder="Article Contents Go Here"></textarea> 

            </div>
            <div class="form-group">
                <label for="image">Image</label><br>
                <input type="file" name="image" class="form-control" /> 
            </div>
            <div class="form-group">
                <button class="btn btn-primary" type="submit">Submit Post</button>&nbsp;&nbsp;&nbsp;<button class="btn btn-danger" type="reset">Reset Form</button>
            </div>
            <?php } ?>
        </form>
        </div>
        <div class="col-lg-6 col-sm-12">
            <h3>Posting Guidelines and Restrictions</h3>:
                <strong>Restrictions</strong>
                <ul>
                    <li>Images extensions are restricted to JPG's, JPEG's, & PNG's</li>
                    <li>Image file sizes are limited to 5mb</li>
                </ul>
                <strong>Guidelines</strong>
                <ul>
                    <li>All the fields are required. Submiting the form with any of the fields left empty will result in errors.</li>
                    <li>The summary should be kept to less then a single paragraph. It is what is displayed on the homepage.</li>
                    <li>I'm not really sure what else to put here. Email me if you have any questions.</li>
                </ul>
    </div><!-- /#page-wrapper -->

<?php 

include 'includes/footer.php'; ?>

最佳答案

如果条件错误。您错误地验证了图像是否上传。

改变

if (isset($_FILES['image']) && !empty($_FILES['image']))

if (isset($_FILES['image']) && $_FILES['image']['error'] == 0 && $_FILES['image']['size'] > 0)

还可以以类似的方式更改条件,即移动/保存图像的位置。

关于javascript - 表单尝试处理不存在的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20591322/

相关文章:

php - 是否需要更改 select 语句的变量名称?

javascript - 如何创建动态对象 HTML 并分配给定的基于属性的数据

php - 与 ID 数组相比,检测数据库中要删除的字段的最佳方法

PHP - 没有提交按钮的单选按钮

javascript - 从下拉列表中选择多个值

mysql - 查找总和大于预定义值的所有可能组

javascript - Dojo:获取对 dijit.form.Select 中单击项的访问权限?

javascript - 通过 setTimeOut 再次调用 setState 来响应更改状态

javascript - Nodejs Express 中的异步操作

php - Mysqli 不显示所有行