繁体   English   中英

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

[英]PHP how to rename uploaded file?

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

$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)为我想要的名称,例如: 'images/'myname.time().'.'.$type)所有这些点和引号杀死了我!

如果这些点杀死了您,请将其更改为加号(+)。 它们有时也会出现在我身上,因为在尝试访问对象/类的成员或字符串追加操作时,我很难理解这是否是点符号。 在这里,您的第三行被重新想象:

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

通常,为了便于阅读,我会尽量避免使用句号进行连接。

是的你可以

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

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

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

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

点是PHP中的串联运算符。

'images /'。time()。'。'。$ type);

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

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

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

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

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

基本上,文件的新名称将是move_uploaded_file的第二个参数,因此您可以在其中放置任何内容。

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

如果要在名称和时间之间使用分隔符:

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

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

移动上载文件如下所示: 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM