【问题标题】:How can i store separate image in separate field with single php code如何使用单个 php 代码将单独的图像存储在单独的字段中
【发布时间】:2017-12-23 09:45:33
【问题描述】:

我的表格中有两个单独的图像字段和两个单独的单元格。我想在这些单元格中保存单独的图像。我可以重复以下程序,但我认为这不是明智的。我可以在这里做什么?

<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')";

【问题讨论】:

  • 你可以使用循环,foreach(['featuredImg','topImg'] AS $field)

标签: php mysql upload


【解决方案1】:

类似这样的:

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 的使用,我强烈建议不要保存完整路径。路径发生变化,您不应仅授予用户对文件路径的访问权限名称。如果您授予他们访问路径的权限,您就会对目录遍历攻击敞开心扉。

所以你有 2 个安全问题。

SQL Injection

Directory Traversal

【讨论】:

  • 感谢您的辛勤努力,我尝试了您的第一个代码。这仅存储第二张图像(顶部图像)。但我认为我们已经接近解决问题。现在我将尝试你的第二种方式......作为一个新手 php 学习者,我对 PDO 有点不舒服。所以我打算换个方式试试。
  • 兄弟你能在没有 PDO 的情况下重写程序吗?作为一个学习者,它在我脑海中滚动。
  • PDO 比 Mysqli 更简单,确实如此。它也有更多的方法来提取数据。除了这里,我已经有大约 4 年没有使用过其他任何东西了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-20
  • 1970-01-01
相关资源
最近更新 更多