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 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等