简体   繁体   English

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

[英]How to rename an uploaded file in PHP?

I'm uploading a file to the server in PHP.我正在用 PHP 将文件上传到服务器。 Now I want to rename the file to the new name, but I couldn't get it done.现在我想将文件重命名为新名称,但无法完成。 The proposed new name of file will be composed of the value from one associative array and a variable name.建议的文件新名称将由一个关联数组中的值和一个变量名称组成。 For achieving that I did following code but not able to get the newly named file.为了实现这一点,我做了以下代码,但无法获得新命名的文件。 My code is as follows:我的代码如下:

$test_pack_id  = md5(uniqid($this->hash_secret));


    if(!empty($test_pack_id )){
                  $package_image_file = $form_image_data['test_pack_image']['name'];

                  $nwName = rename($package_image_file,$form_data['test_pack_name'].$test_pack_id);  
                  echo $nwName; die;
                }

Can anyone help me on how to rename a file in PHP?任何人都可以帮助我如何在 PHP 中重命名文件? Thanks in Advance.提前致谢。

bool rename ( string $oldname , string $newname [, resource $context ] ) bool 重命名(字符串 $oldname ,字符串 $newname [, 资源 $context ] )

Note: The old name.注:旧称。 The wrapper used in oldname must match the wrapper used in newname. oldname 中使用的包装器必须与 newname 中使用的包装器匹配。

Returns TRUE on success or FALSE on failure.成功时返回 TRUE,失败时返回 FALSE。

<?php
rename("old", "new");
?>

Check this link too http://www.codersmount.com/2011/07/smart-way-for-renaming-uploaded-files-using-php/也检查这个链接http://www.codersmount.com/2011/07/smart-way-for-renaming-uploaded-files-using-php/

You should do a print_r or var_dump on $form_data because I suspect that the data being passed to 'test_pack_name' is incorrect and causing the rename to fail.您应该对 $form_data 执行 print_r 或 var_dump,因为我怀疑传递给“test_pack_name”的数据不正确并导致重命名失败。 I would also included swapnesh's suggestion to put in a conditional if to report on the success or failure of the rename to provide you additional debugging information.我还将包括 swapnesh 的建议,即加入一个条件if来报告重命名的成功或失败,以便为您提供额外的调试信息。

PHP rename(); PHP rename(); function功能

rename ("123", "abc");
rename ("oldname", "newname");

PHP rename() returns true or false PHP rename()返回truefalse

so u can check if via if statement所以你可以通过if语句检查

if(rename())
echo "Success";
else
echo "failure";

you can use rename as others have suggested.您可以按照其他人的建议使用rename OR just simply rename the file using the time at which it was uploaded.或者只是简单地使用文件上传的时间重命名文件。 This is what i usually do.这是我通常做的。 Take a look:看一看:

//First separate the original file name from its extension
list($txt, $ext) = explode(".", $name);
//rename it with its timestamp.
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;

Hope this helps.希望这可以帮助。

simple and easy way简单易行的方法

if( !rename($filePath, $newFileName) ) {

echo "File can't be renamed!";

}

else {

echo "File has been renamed!";

}

Reference参考

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

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