通过PHP使用唯一的文件名上传图像


upload images through php using unique file names

我目前正在借助phonegap编写一个移动应用程序。我希望这个应用程序具有的少数功能之一是能够捕获图像并将其上传到远程服务器…

我目前有图像捕获和上传/电子邮件部分工作良好与编译的apk…但在我的php,我目前命名的图像"图像[插入随机数从10到20]…这里的问题是数字可以重复,图像可以被覆盖……我已经阅读并考虑过仅使用rand()并选择从0到getrandmax()的随机数,但我觉得我可能有相同的文件覆盖机会…我需要的图像上传到服务器与唯一的名称每次,无论什么…因此,PHP脚本将检查服务器已经拥有的内容,并使用唯一名称写入/上传图像…

除了"rand()"还有什么想法吗?

我也在考虑也许命名每个图像…Img +日期+时间+随机5个字符,其中包括字母和数字…所以如果一张图片是在2013年3月20日凌晨4点37分使用应用程序拍摄的,那么当图片上传到服务器时,它将被命名为"img_03-20-13_4-37am_e4r29.jpg"。我想这可能行得通……(除非有更好的方法),但我对PHP相当陌生,不明白如何写这样的东西…

我的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);

任何帮助都是感激的…提前感谢!另外,如果还有什么我可能遗漏的信息,请告诉我……

您可能需要考虑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);

还要记住,服务器的随机函数并不是真正随机的。如果你需要一些真正随机的东西,试试random.org。随机随机随机

UPD:为了在你的代码中使用random.org,你必须对他们的服务器做一些API请求。有关的文档可以在这里找到:www.random.org/clients/http/.

调用的示例是:random.org/integers/?num=1&min=1&max=1000000000&col=1&base=10&format=plain&rnd=new。请注意,您可以更改min, max和其他参数,如文档中所述。

在PHP中,您可以使用file_get_contents()函数,cURL库甚至套接字向远程服务器执行GET请求。如果您使用的是共享主机,那么您的帐户应该可以使用并启用传出连接。

$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);

您应该使用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);

新文件的扩展名应该在移动上传的文件后完成,即:

// 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
}

您考虑过使用md5_file吗?这样,您的所有文件将有唯一的名称,您就不必担心重复的名称。但请注意,如果内容相同,这将返回相同的字符串。

这里还有另一个方法:

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

函数将在上传图像之前创建一个唯一的名称。

// 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
}