php 使用唯一的文件名通过php上传图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15519202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
upload images through php using unique file names
提问by JStormThaKid
I am currently in the process of writing a mobile app with the help of phonegap. One of the few features that I would like this app to have is the ability to capture an image and upload it to a remote server...
我目前正在借助 phonegap 编写移动应用程序。我希望这个应用程序具有的少数功能之一是能够捕获图像并将其上传到远程服务器......
I currently have the image capturing and uploading/emailing portion working fine with a compiled apk... but in my php, I am currently naming the images "image[insert random number from 10 to 20]... The problem here is that the numbers can be repeated and the images can be overwritten... I have read and thought about just using rand() and selecting a random number from 0 to getrandmax(), but i feel that I might have the same chance of a file overwriting... I need the image to be uploaded to the server with a unique name every-time, no matter what... so the php script would check to see what the server already has and write/upload the image with a unique name...
我目前的图像捕获和上传/发送电子邮件部分使用编译的 apk 工作正常......数字可以重复,图像可以被覆盖......我已经阅读并考虑过只使用 rand() 并选择一个从 0 到 getrandmax() 的随机数,但我觉得我可能有同样的机会获得一个文件覆盖...我需要每次都将图像以唯一的名称上传到服务器,无论如何...所以 php 脚本将检查服务器已经拥有的内容并使用唯一的名称写入/上传图像姓名...
any ideas other than "rand()"?
除了“rand()”之外还有其他想法吗?
I was also thinking about maybe naming each image... img + date + time + random 5 characters, which would include letters and numbers... so if an image were taken using the app at 4:37 am on March 20, 2013, the image would be named something like "img_03-20-13_4-37am_e4r29.jpg" when uploaded to the server... I think that might work... (unless theres a better way) but i am fairly new to php and wouldn't understand how to write something like that...
我也在考虑可能命名每个图像... img + 日期 + 时间 + 随机 5 个字符,其中包括字母和数字...所以如果图像是在 2013 年 3 月 20 日凌晨 4:37 使用该应用程序拍摄的,当上传到服务器时,图像将被命名为“img_03-20-13_4-37am_e4r29.jpg”......我认为这可能有效......(除非有更好的方法)但我对php和不明白怎么写这样的东西......
my php is as follows...
我的php如下...
print_r($_FILES);
$new_image_name = "image".rand(10, 20).".jpg";
move_uploaded_file($_FILES["file"]["tmp_name"], "/home/virtual/domain.com/public_html/upload/".$new_image_name);
Any help is appreciated... Thanks in advance! Also, Please let me know if there is any further info I may be leaving out...
任何帮助表示赞赏......提前致谢!另外,如果有任何我可能遗漏的信息,请告诉我......
回答by aexl
You may want to consider the PHP's uniqid()function.
This way the code you suggested would look like the following:
您可能需要考虑 PHP 的uniqid()功能。这样,您建议的代码将如下所示:
$new_image_name = 'image_' . date('Y-m-d-H-i-s') . '_' . uniqid() . '.jpg';
// do some checks to make sure the file you have is an image and if you can trust it
move_uploaded_file($_FILES["file"]["tmp_name"], "/home/virtual/domain.com/public_html/upload/".$new_image_name);
Also keep in mind that your server's random functions are not really random. Try random.orgif you need something indeed random. Random random random.
还要记住,您服务器的随机函数并不是真正随机的。如果您确实需要一些随机的东西,请尝试random.org。随机随机随机。
UPD: In order to use random.org from within your code, you'll have to do some API requests to their servers. The documentation on that is available here: www.random.org/clients/http/.
UPD:为了在您的代码中使用 random.org,您必须向他们的服务器发出一些 API 请求。相关文档可在此处获得:www.random.org/clients/http/。
The example of the call would be: random.org/integers/?num=1&min=1&max=1000000000&col=1&base=10&format=plain&rnd=new. Note that you can change the min, maxand the other parameters, as described in the documentation.
通话的例子是:random.org/integers/?num=1&min=1&max=1000000000&col=1&base=10&format=plain&rnd=new。请注意,您可以更改min,max而其他参数中所描述的文档。
In PHP you can do a GETrequest to a remote server using the file_get_contents()function, the cURLlibrary, or even sockets. If you're using a shared hosting, the outgoing connections should be available and enabled for your account.
在 PHP 中,您可以GET使用file_get_contents()函数、cURL库甚至套接字向远程服务器发出请求。如果您使用的是共享主机,则传出连接应该可用并为您的帐户启用。
$random_int = file_get_contents('http://www.random.org/integers/?num=1&min=1&max=1000000000&col=1&base=10&format=plain&rnd=new');
var_dump($random_int);
回答by Ja?ck
You should use tempnam()to generate a unique file name:
您应该使用tempnam()来生成唯一的文件名:
// $baseDirectory Defines where the uploaded file will go to
// $prefix The first part of your file name, e.g. "image"
$destinationFileName = tempnam($baseDirectory, $prefix);
The extension of your new file should be done after moving the uploaded file, i.e.:
新文件的扩展应该在移动上传的文件后完成,即:
// Assuming $_FILES['file']['error'] == 0 (no errors)
if (move_uploaded_file($_FILES['file']['tmp_name'], $destinationFileName)) {
// use extension from uploaded file
$fileExtension = '.' . pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
// or fix the extension yourself
// $fileExtension = ".jpg";
rename($destinationFileName, $destinationFileName . $fileExtension);
} else {
// tempnam() created a new file, but moving the uploaded file failed
unlink($destinationFileName); // remove temporary file
}
回答by Goran
Have you considered using md5_file? That way all of your files will have unique name and you would not have to worry about duplicate names. But please note that this will return same string if the contents are the same.
您是否考虑过使用md5_file?这样您的所有文件都将具有唯一名称,您不必担心重复名称。但请注意,如果内容相同,这将返回相同的字符串。
Also here is another method:
这里还有另一种方法:
do {
$filename = DIR_UPLOAD_PATH . '/' . make_string(10) . '-' . make_string(10) . '-' . make_string(10) . '-' . make_string(10);
} while(is_file($filename));
return $filename;
/**
* Make random string
*
* @param integer $length
* @param string $allowed_chars
* @return string
*/
function make_string($length = 10, $allowed_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890') {
$allowed_chars_len = strlen($allowed_chars);
if($allowed_chars_len == 1) {
return str_pad('', $length, $allowed_chars);
} else {
$result = '';
while(strlen($result) < $length) {
$result .= substr($allowed_chars, rand(0, $allowed_chars_len), 1);
} // while
return $result;
} // if
} // make_string
回答by Ayaz Shah
Function will create a unique name before uploading image.
函数将在上传图像之前创建一个唯一的名称。
// Upload file with unique name
if ( ! function_exists('getUniqueFilename'))
{
function getUniqueFilename($file)
{
if(is_array($file) and $file['name'] != '')
{
// getting file extension
$fnarr = explode(".", $file['name']);
$file_extension = strtolower($fnarr[count($fnarr)-1]);
// getting unique file name
$file_name = substr(md5($file['name'].time()), 5, 15).".".$file_extension;
return $file_name;
} // ends for is_array check
else
{
return '';
} // else ends
} // ends
}

