如何使用单个PHP代码在单独的字段中存储单独的图像

时间:2017-12-23 09:45:33

标签: php mysql upload

我的桌子中有两个单独的图像区域和两个单独的单元格。我想在这些单元格中保存单独的图像。我可以重复以下计划,但我认为这不是明智之举。我能在这做什么?

<input type="file" id="exampleInputFile" name="featuredImg">
<input type="file" id="topImg" name="topImg">

$permitted  = array('jpg', 'jpeg', 'png', 'gif');
$file_name  = $file['featuredImg']['name'];
$file_size  = $file['featuredImg']['size'];
$file_temp  = $file['featuredImg']['tmp_name'];

$div             = explode('.', $file_name);
$file_ext        = strtolower(end($div));
$unique_image    = substr(md5(time()), 0, 10).'.'.$file_ext;
$uploaded_image = "../images/uploads/".$unique_image;

move_uploaded_file($file_temp, $uploaded_image);
$query = "INSERT INTO aboutafc(featuredimage, topimage) VALUES ('$uploaded_image', '$topImage')";

1 个答案:

答案 0 :(得分:0)

这样的事情:

foreach(['featuredImg','topImg'] AS $field){
    $permitted  = array('jpg', 'jpeg', 'png', 'gif');
    $file_name  = $file[$field]['name'];
    $file_size  = $file[$field]['size'];
    $file_temp  = $file[$field]['tmp_name'];

    $div             = explode('.', $file_name);
    $file_ext        = strtolower(end($div));
    $unique_image    = substr(md5(time()), 0, 10).'.'.$file_ext;
    $uploaded_image = "../images/uploads/".$unique_image;

    move_uploaded_file($file_temp, $uploaded_image); 
}

//-Note- this wont work as it is, logically it's incompatible.
$query = "INSERT INTO aboutafc(featuredimage, topimage) VALUES ('$uploaded_image', '$topImage')";

就个人而言,我会将图像存储在一个具有“多对多”关系的单独表格中,以及一些其他数据,如图像类型(来自哪个字段)。

这将解决必须将它们保存到循环外的数据库的问题。我完全不喜欢这个想法(当它们被保存在循环之外时,有很大的错误空间)

要解决这个问题,你必须做这样的事情

$images = [];
foreach(['featuredImg','topImg'] AS $field){
  //...
  $unique_image = substr(md5(time()), 0, 10).'.'.$file_ext;
  $images[] =  $unique_image;
  move_uploaded_file($file_temp, $uploaded_image);
}

if( count($images) != 2 ){
     //Error checking before saving files in the DB
}

$query = "INSERT INTO aboutafc(featuredimage, topimage) VALUES (:image1, :image2)";

$stmt = $PDO->prepare($query);
$stmt->execute([':image1'=>$images[0],':image2'=>$images[1]]);

请注意我修复了SQL注入问题..

另请注意我对$unique_image的使用我强烈建议不要保存完整路径。路径更改,您不应该只授予用户访问文件路径的名称。如果您允许他们访问路径,您就可以打开Directory Traversal攻击。

所以你有2个安全问题。

SQL Injection

Directory Traversal