dongtangu8403 2013-08-18 04:50
浏览 68

上传时重命名图像?

this is an example I picked from W3School. Im just trying to modify this to suit my requirement.

What I need is when an image is uploaded, the image to be renamed in a sequence to so duplication is avoided. With this code if two users has two different images but if by chance if the name of the two different images are the same, one user will get a prompt saying 'already exists' preventing uploading.

I've tried replacing

echo $_FILES["file"]["name"] . " already exists. ";

with

move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["tmp_name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["tmp_name"];

but doesn't seems to be giving me a solution.

Can some one suggest me a way out to rename the images uploading in a sequence? Thanks.

The code:

<?php
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 2000000)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    }
  else
    {
    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";
  }
?>
  • 写回答

3条回答 默认 最新

  • douyan1882 2013-08-18 04:55
    关注

    just change this line : move_uploaded_file($_FILES["file"]["tmp_name"],"upload/" . $your_file_name) and for your image name, you can use md5 of the file and timestamps to create an unique sequence

    评论

报告相同问题?

悬赏问题

  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据