使用PHP将图像上传到文件夹,同时将描述保存到数据库 [英] Using PHP to upload images to a folder while saving descriptions to a database

查看:71
本文介绍了使用PHP将图像上传到文件夹,同时将描述保存到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户决定上传多个图像作为其分类列表.我需要发生的事情是:

The user decides to upload multiple images for their classified listing. What I need to have happen is to:

  1. 上传包含每张图像描述的图像-已解决
  2. 将图像保存到指定的文件夹
  3. 使用说明将图像位置保存到我的MySQL数据库-已解决
  4. 能够通过图库设置调用分类列表中的图像和说明

我的表模式设置如下(简化):

My table schema is set up like this (simplified):

ad_id | member_id | category | subcategory | ... | photo_0_href | photo_0_desc ... | etc.

有人可以引导我完成整个过程吗?谢谢.

Could someone walk me through the process? Thanks.

<form action="upload.php" method="post" enctype="multipart/form-data">
<p>
<label for="file0">Filename: </label>
<input name="file[]" type="file" id="file0" size="20" />
</p>
<p>
<label for="file0desc">Description: </label>
<textarea rows="10" cols="30" id="file0desc" class="textarea"></textarea>
</p>
<p>
<label for="file1">Filename: </label>
<input name="file[]" type="file" id="file1" size="20" />
</p>
<p>
<label for="file1desc">Description: </label>
<textarea rows="10" cols="30" id="file1desc" class="textarea"></textarea>
</p>
<p>
<input id="submit" type="submit" name="submit" value="Continue to Step 4" />
</p>
</form>

upload.php

<?php

if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 1048600)) // less than 1MB
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    header("Location: step4.php");
/*
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

*/
    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

我知道我的upload.php尚未配置多个图像文件,但这只是一个开始.

I know my upload.php isn't configured for multiple image files yet, but it's a start.

我计算出使用$_SESSION['file_n_desc']将描述保存到数据库中.我只需要弄清楚如何将织补图像上传到文件夹,然后将位置保存到数据库中即可.

I worked out saving the descriptions to the database using $_SESSION['file_n_desc']. I just need to figure out how to upload the darn images to the folder and then save the locations into the database.

我还需要将图像重命名为随机字符串(以防止图像被覆盖).我知道我可以使用rand()函数来做到这一点.

I also need to have the image renamed to a random string (to prevent images being overwritten). I know I can do this with the rand() function.

推荐答案

1)上传文件

在将数组语法用于文件输入时,文件索引是最后一个键.例如,$_FILES["file"]["name"]是文件名的数组.要获取第i个文件的信息,您需要访问$_FILES["file"]["name"][$i]$_FILES["file"]["size"][$i]& c.

1) Uploading files

When using array syntax for file inputs, the file index is the last key. $_FILES["file"]["name"], for example, is an array of file names. To get the information for the i-th file, you'll need to access $_FILES["file"]["name"][$i], $_FILES["file"]["size"][$i] &c.

$_FILES中的某些数据(例如名称)来自客户端,因此是不可信的(即首先进行验证).对于文件名,您可以使用 basename pathinfo 来提取在组装目标路径名之前提供的名称.

Some of the data in $_FILES (such as the name) comes from the client, and thus is not to be trusted (that is, verify first). In the case of the file name, you could start by using realpath to verify the target file pathname is safe, or use basename or pathinfo to extract the last component of the supplied name before assembling the target pathname.

您提供的(不完整)数据库架构看起来像在同一张表中为每个图像提供了两列.在关系模型下,使用单独的表对多个关系进行建模:

The (incomplete) database schema you give looks like you give each image two columns in the same table. Under the relational model, to-many relationships are modeled with a separate table:

CREATE TABLE images (
    id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    `path` VARCHAR(256) NOT NULL,
    `description` TEXT,
    `member` INT UNSIGNED NOT NULL,
    FOREIGN KEY `member` REFERENCES members (`id`) ON DELETE CASCADE ON UPDATE CASCADE -- the image's owner
) Engine=InnoDB;

-- Note: this is a many-to-many relationship
CREATE TABLE ad_images (
    `ad` INT UNSIGNED NOT NULL,
    `image` INT UNSIGNED NOT NULL,
    FOREIGN KEY `ad` REFERENCES ads (`ad_id`) ON DELETE CASCADE ON UPDATE CASCADE,
    FOREIGN KEY `image` REFERENCES images (id) ON DELETE CASCADE ON UPDATE CASCADE,
    UNIQUE KEY (`ad`, `image`)
) Engine=InnoDB;

否则,您将违反零一无穷规则,并在浪费空间时图片少于最大数量.

Otherwise, you're breaking the zero-one-infinity rule and wasting space when there are fewer than the maximum number of images.

请注意,可以在文件描述字段中使用数组语法,以使其更易于使用.将它们命名为"filedesc []".

Note that you can use array syntax for the file description fields to make handling them easier. Name them "filedesc[]".

使用数组查找或模式匹配,而不是进行比较长的比较.

Rather than a long sequence of comparisons, use an array lookup or a pattern match.

function isImage($type) {
    static $imageTypes = array(
            'image/gif'=>1, 'image/jpeg'=>1, 'image/pjpeg'=>1, 'image/png'=>1,
        );
    return isset($imageTypes[$type]);
    /* OR */
    return preg_match('%^image/(?:p?jpeg|gif|png)%', $type);
    /* OR allow all images */
    return preg_match('%^image/%', $type);
}

if (isImage($_FILES["file"]["type"][$idx]) && ($_FILES["file"]["size"][$idx] < 1048600)) {

文件类型是这些客户端提供的值之一.比较安全的方法是使用 fileinfo 来获取图像类型.

The file type is one of those client-supplied values. Safer would be to use fileinfo to get the image type.

$finfo = finfo_open(FILEINFO_MIME_TYPE);

if (isImage(finfo_file($finfo, $path)) && ($_FILES["file"]["size"][$idx] < 1048600)) {

即使该文件具有有效的图像标头,但其余部分无效,也可以愚弄.您可以使用图像库(例如GD或ImageMagick ),以检查您是否可以成功打开该文件作为图片来验证该文件.

Even that can be fooled if the file has a valid image header but the rest isn't valid. You can use an image library (such as GD or ImageMagick) to validate the file by checking whether you can successfully open the file as an image.

这篇关于使用PHP将图像上传到文件夹,同时将描述保存到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆