dougai3418 2014-10-23 14:52
浏览 84
已采纳

在上传到服务器之前重命名文件

I'm trying to create some sort of "selfie" uploader on mobile phones. Now it's working great it's just that when i test the upload file on my iPhone all the photo's will be named image.jpeg so they keep overwriting each other. Now what i want to do is rename the file to let's say image1.jpeg and the next image2.jpeg before it gets uploaded to the server.

My current code:

<?php
if (isset($_FILES['myFile'])) {
move_uploaded_file($_FILES['myFile']['tmp_name'], "uploads/" . $_FILES['myFile']    ['name']);
echo 'successful';
}
?>

I tried this code to give my image a filename value of image plus a random number between 1 and 99999 but this wasn't a succes.

<?php
if (isset($_FILES['myFile'])) {

$temp = explode(".",$_FILES["myFile"]["name"]);
$newfilename = rand(1,99999) . '.' .end($temp);
move_uploaded_file($_FILES["myFile"]["tmp_name"], "uploads/" . $newfilename;
echo 'successful';
}
?>

Any pointers will be appreciated.

  • 写回答

2条回答 默认 最新

  • doufu8127 2014-10-23 15:03
    关注

    this wasn't a succes.

    Not a descriptive way to describe your error. Please include PHP errors or investigate them yourself so you (or we) can figure out what problems you're having with your code. Some editors will even tell you where your parsing errors are. You can also use a PHP linter.

    The error lies in this line:

    move_uploaded_file($_FILES["myFile"]["tmp_name"], "uploads/" . $newfilename;
    

    The move_uploaded_file function is missing a closing bracket, so you must put it back in:

    move_uploaded_file($_FILES["myFile"]["tmp_name"], "uploads/" . $newfilename);
    

    I'd also recommend a better random filename generator. Try something like this instead:

    $newfilename = sha1(uniqid(mt_rand(), true)) . '.' .end($temp);
    

    It will create a hash that has a much lower likelihood of collisions (read: 1 in 2160.)

    Best of luck!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,