在PHP中为图像提供随机名称

时间:2013-03-05 17:23:28

标签: php random

这样我用php加载图片:

header("Content-type: image/jpeg");
$image=imagecreatefromjpeg("http://i.imgur.com/zWaQJNCb.jpg");
imagejpeg($image);

但问题是,如果我想手动将图像从我的网络浏览器保存到我的桌面,那么所有图像都有相同的名称,如ix.jpeg [这里的文件名是:ix.php],但我不明白是什么是配置header的方式,以便图像具有随机名称..如25xc.jpeg, 36s5a2f.jpeg...,同时将其保存在桌面上..任何想法?

5 个答案:

答案 0 :(得分:3)

这将完成这项工作!

$dt = date(time());
header("Content-type: image/jpeg");
header('Content-Disposition: inline; filename="'. $dt .'.jpg"');
$image=imagecreatefromjpeg("http://i.imgur.com/knNxDFnb.jpg");
imagejpeg($image);

答案 1 :(得分:2)

使用filename来电中的header值。 See Example 1

<?php
// We'll be outputting a PDF
header('Content-type: application/pdf');

// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');

// The PDF source is in original.pdf
readfile('original.pdf');
?>

我会留下“生成随机字符串”部分给你。我建议将它基于文件的校验和,但那只是我。

答案 2 :(得分:1)

有几十种甚至数百种方法可以做到这一点。

  1. 在文件名后附加time()。这样所有文件名都会 有一个(唯一的)号码。
  2. 使用散列函数,例如md5()
  3. 使用此代码 -

    function generateRandomName(len) {
            $out = '';
            for($i=0; $i<len; $i++) {
                $out.=chr(rand(65,122));
            }
            return $out;
        }
    
  4. 只需在文件名后添加rand函数(但文件名的长度不一样)。

  5. Google是您的朋友。

答案 3 :(得分:1)

如果您想为用户生成唯一的名称,则需要执行此操作,您只需使用实际时间戳并在标题中使用filename参数,您可以执行以下操作(如果您使用随机生成的情况很少会有两次相同的名称):

$dt = date(time());

header("Content-type: image/jpeg");
header('Content-Disposition: attachment; filename="'. $dt .'.jpg"');

以上将生成如下所示的独特图像名称:

  

1362504465.jpg

我希望这会有所帮助。

答案 4 :(得分:0)

这会产生8个字符长的字母a-z,但你可以做一些魔术和/或使用http://www.asciitable.com/

function randChar() {
    return char(rand(97, 122); 

    // Then you could either do a random number from 97 to 122 for a-z or just make an array of all the characters you would like in the filename. 
}

$filename = '';
$amountOfChars = 8;

for($i = 0; $i < $amountOfChars; $i++; ) $filename .= randChar();

希望这有帮助