忽略空白文件上传字段

时间:2013-06-14 20:51:15

标签: php forms file-upload

我有一个带上传字段的表单,它运行正常。它上传并且一切都很好,除了当上传字段为空时。数据库表中的字段也是空白的,没有任何内容,甚至没有旧的图像条目!

我的表格:

<form enctype="multipart/form-data" action="add.php" method="POST"> 
Name: <input type="text" name="name"><br> 
E-mail: <input type="text" name = "email"><br> 
Phone: <input type="text" name = "phone"><br> 
Photo: <input type="file" name="site_logo"><br> 
<input type="submit" value="Add"> 
</form>

PHP代码:

<?php
    $target = "../upload/";
    $target = $target . basename($_FILES['site_logo']['name']);?>

<?php
  move_uploaded_file($_FILES['site_logo']['tmp_name'], $target);
  // output a list of the fields that had errors
     if (!empty($errors)) {
       echo "<p class=\"errors\">";
       echo "Please review the following fields:<br />";

          foreach($errors as $error) {
       echo " - " . $error . "<br />";
   }
       echo "</p>";
       }
?>

查询:

$site_logo=($_FILES['site_logo']['name']);


                $query = "UPDATE ss_settings SET 
                            site_logo = '{$site_logo}'
                        WHERE id = 1 ";
                $result = mysql_query($query, $connection);

我已经设置了数据库连接和更新查询以及所有内容。刚刚发布了流程代码,所以你们很清楚。我只是希望它在字段为空时什么都不做。

5 个答案:

答案 0 :(得分:1)

查看解释http://www.php.net/manual/en/features.file-upload.errors.php

的错误消息

检查文件是否未上传:

if ($_FILES['site_logo']['error'] === UPLOAD_ERR_NO_FILE)

更好的方法是检查是否没有错误。

if ($_FILES['site_logo']['error'] === UPLOAD_ERR_OK)

答案 1 :(得分:0)

如果您的查询是UPDATE语句,则不应更改它,也可以尝试使用

<?php
// ...
if($_FILES['site_logo']['name'] == NULL){
   // do stuff when no file field is set
}else{
   // do stuff when file is set
}
// ...
?>

答案 2 :(得分:0)

就个人而言,我不会对文件使用未经过清理的名称,但在您的情况下,您需要做的就是在进行查询之前检查有效的文件上传。

所以(PDO中的mysql_*函数已被弃用):

// first line borrowed from @DaveChen, +1 for that
if ($_FILES['site_logo']['error'] === UPLOAD_ERR_OK)
{
  $stmt = $db->prepare("UPDATE `ss_settings` SET 
                            `site_logo` = :site_logo
                        WHERE `id` = :id ";

  // bind variables
  $stmt->bindValue(':site_logo', $_FILES['site_logo']['name'], PDO::PARAM_STR);
  $stmt->bindValue(':id', $the_ID, PDO::PARAM_INT);

  // execute query
  $stmt->execute();
}

答案 3 :(得分:-1)

也许尝试这样的事情来防止处理空白上传:

if($_FILES['site_logo']['error']==0) { 
  // process 
} else { 
  // handle the error 
}

http://php.net/manual/en/features.file-upload.errors.php

答案 4 :(得分:-1)

您的问题是,您只是假设已成功上传。 从不假设成功。总是检查失败。由于某种原因,PHP在$ _FILES中提供['error']参数。使用它:

if ($_FILES['site_logo']['error'] == UPLOAD_ERR_OK) {
   ... upload was successful
} else { 
   die("Upload failed with error code: " . $_FILES['site_logo']['error']);
}

错误代码在此处定义:http://www.php.net/manual/en/features.file-upload.errors.php

您将要检查代码4(UPLOAD_ERR_NO_FILE),这意味着用户根本没有上传任何内容。