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条)

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)