PHP如何重命名上传的文件?

时间:2011-11-17 00:12:35

标签: php mysql

我想重命名文件并将其上传到服务器以及数据库中。我有一个代码:

$file = $_FILES['file'];
list(,$type) = explode('/', $file['type']);
move_uploaded_file($file['tmp_name'], 'images/'.time().'.'.$type);
$a = time();
$b = ($a.'.'.$type);

它正在运作,但我不确定它是如何工作的。如何将此'images/'.time().'.'.$type更改为我想要的名称,例如:'images/'myname.time().'.'.$type)所有这些点和引号都会杀了我!

6 个答案:

答案 0 :(得分:5)

如果点击你,请将它们改为加号(+)。他们有时也会找到我,因为当我试图访问对象/类的成员或字符串附加操作时,我很难理解这是否是点符号。在这里你的第三行重新想象:

$newName = 'aDifferentFileName';
$finalFilePath = 'images/' + $newName + time() + '.' + $type;
move_uploaded_file( $file['tmp_name'], $finalFilePath );

很多时候,我会远离连接使用这段时间以便于阅读。

答案 1 :(得分:2)

是的,你可以

http://php.net/manual/en/function.move-uploaded-file.php

$new_name = 'yournewname'.time().'.'.$type;
move_uploaded_file($file['tmp_name'], 'images/'.$new_name);

然后使用$ new_name进行数据库查询。

答案 2 :(得分:1)

move_uploaded_file()接受两个参数 - 旧名称和新名称。第二个是新名称,因此您可以指定任何内容。

dot是PHP中的连接运算符。

'图像/' 时间()$型)。 '';

表示“取静态字符串'images /',将time()的返回值放在最后,然后是句点,然后是变量$ type的内容。

例如,如果time()返回“1”且$ type包含“example”,则结果为“images / 1.example”

这将有效地将您上传的文件重命名为目录images /

中的1.example

答案 3 :(得分:1)

点是PHP字符串连接运算符。请参阅此处:http://www.phpf1.com/tutorial/php-string-concatenation.html以快速了解其工作原理。

如果它让您更舒服,可以使用sprintf将名称生成转换为字符串格式化操作:http://php.net/manual/en/function.sprintf.php

基本上,你的文件的新名称将是move_uploaded_file的第二个参数,所以你可以在那里放任何你想要的东西。

答案 4 :(得分:1)

move_uploaded_file($file['tmp_name'], 'images/'.$yourName.time().'.'.$type);

如果您想要名称和时间之间的分隔符:

move_uploaded_file($file['tmp_name'], 'images/'.$yourName.'-'.time().'.'.$type);

答案 5 :(得分:1)

点是连接操作(将字符串连接在一起)。

移动上传文件如下所示:move_uploaded_file ( string $filename , string $destination )

$file name是上传到临时目录的临时名称,$string是您要将其移动到的目标路径。

在你的情况下,你可以这样做:

$myname = 'thisismyname';
$filename = 'images/' . $myname . time() . '.' . $type;
move_uploaded_file($file['tmp_name'], $filename); //Move the file 
//Save $filename to the database here