【问题标题】:error in uploading multy files in the same table在同一个表中上传多个文件时出错
【发布时间】:2014-11-03 19:54:33
【问题描述】:

我在数据库中上传图片时遇到了这个问题。当我插入查询时,只需单击一下即可获得 3 行。这是 HTML 文件:

 <form action="my_parser.php" method="post" enctype="multipart/form-data"> 
 <input type="file" name="file_array[]">
 <input type="file" name="file_array[]">
 <input type="file" name="file_array[]">
  <input type="submit" value="Upload all files"> 
 </form> 

这是我的 PHP 代码:

<?
include "../include/config.php";

?>

<?
 if(isset($_FILES['file_array'])){
    $id = $_REQUEST['id'];
     $name_array = $_FILES['file_array']['name'];
     $tmp_name_array = $_FILES['file_array']['tmp_name'];
     $type_array = $_FILES['file_array']['type'];
     $size_array = $_FILES['file_array']['size'];
     $error_array = $_FILES['file_array']['error']; 
     $image1 = $name_array[0];

        for($i = 0; $i < count($tmp_name_array); $i++){
         if(move_uploaded_file($tmp_name_array[$i], 
            "test_uploads/".$name_array[$i])){ 
            echo $name_array[$i]." upload is complete<br>";

            $add = mysql_query("insert into nn values ('        ','$image1','','')");

             echo "<img src='test_uploads/$image1'>";
             } else
              { echo "move_uploaded_file function failed for ".$name_array[$i]."<br>"; 
            }
             } 
            } 
            ?>

在数据库中,表 nn 有此列。 id - image1 - image2 - image3。 谢谢你

【问题讨论】:

  • 这看起来非常不安全,因为您的用户参数不是properly escaped。您应该绝不$_POST 数据直接放入查询中。这会创建一个巨大的SQL injection bug。此外,mysql_query 是一个过时的接口,不应使用,它已从 PHP 中删除。像PDO is not hard to learn 这样的现代替代品。 PHP The Right Way 之类的指南解释了最佳实践。

标签: php mysql


【解决方案1】:

让我们稍微清理一下。

让我们设置数据库连接。对于此示例,我们将移至 mysqli。然后我们将处理移动文件,并将文件路径存储在数据库中。

$conn = new mysqli('host', 'user', 'pass', 'db');

if(isset($_FILES['file_array'])):
    $id = isset($_REQUEST['id']) ? $_REQUEST['id'] : false;
    if($id):
        $file_array = $_FILES['file_array'];
        for($i = 0; $i < count($file_array['tmp_name']); $i++):
            if(move_uploaded_file($file_array['tmp_name'][$i], 'test_uploads/'.$file_array['name'][$i])):
                $stmt = $conn->prepare("insert into nn values('', ?, '', '')");
                $stmt->bind_param('s', $file_array['name'][$i]);
                if($stmt->execute()):
                    echo $file_array['name'][$i].' has been uploaded successfully.';
                else:
                    echo 'Failed to upload '.$file_array['name'][$i].'. Please check the file and try again!';
                    return false;
                endif;
            endif;
        endfor;
    endif;
endif;

没有理由创建所有这些混乱的变量。我们已迁移到当前支持的 MySQLI,并且我们使用了准备好的语句来确保图像的名称不是可能对我们的应用程序有害的恶意内容。

资源

【讨论】:

    猜你喜欢
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多