PHP图像上传-重命名而不会丢失扩展名? [英] PHP image upload - rename without losing extension?

查看:59
本文介绍了PHP图像上传-重命名而不会丢失扩展名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有:

$file_name = $HTTP_POST_FILES['uid']['name'];
$random_digit=rand(0000,9999);
$new_file_name=$random_digit.$file_name;
$path= "uploads/images/users/".$new_file_name;
if($ufile !=none)
{
    if(copy($HTTP_POST_FILES['uid']['tmp_name'], $path))
    {
        echo "Successful<BR/>"; 
        echo "File Name :".$new_file_name."<BR/>"; 
        echo "File Size :".$HTTP_POST_FILES['uid']['size']."<BR/>"; 
        echo "File Type :".$HTTP_POST_FILES['uid']['type']."<BR/>"; 
    }
    else
    {
        echo "Error";
    }
}

这会在当前文件名之前生成一个随机数,即4593example.jpg 但我只想将整个文件名重写为4593.jpg,删除当前名称(示例).当我尝试这样做时,我失去了扩展名(.jpg) 任何帮助表示赞赏.

this generates a random number before the current file name ie 4593example.jpg but i would just like it to rewrite the whole filename to 4593.jpg removing the ucrrent name (example). When i have tried doing this i lose the extension (.jpg) any help is appreciated.

推荐答案

$ext = pathinfo($filename, PATHINFO_EXTENSION);

$newFilename = $random_digit . '.' . $ext;

顺便说一句,如果随机数发生冲突(可能在下一个或十年内发生),将会发生什么?

BTW, what will happen if the random number clashes (which may happen next or in 10 years)?

有很多更好的命名方式-例如,文件名的散列和time()从理论上讲不应发生冲突(尽管在实践中确实会发生散列冲突).

There are many better ways to name them - for example, hash of the filename and time() should theoretically never clash (though in practice hash collisions do occur).

这篇关于PHP图像上传-重命名而不会丢失扩展名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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