我正在使用PHP将文件上传到服务器。现在我想将文件重命名为新名称,但我无法完成它。建议的文件新名称将由一个关联数组的值和一个变量名组成。为了实现这一点,我做了以下代码,但无法获得新命名的文件。我的代码如下:
$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;
}
有人可以帮我解决如何在PHP中重命名文件的问题吗?在此先感谢。
答案 0 :(得分:2)
bool rename(string $ oldname,string $ newname [,resource $ context])
注意: 旧名。 oldname中使用的包装器必须与newname中使用的包装器匹配。
成功时返回TRUE,失败时返回FALSE。
<?php
rename("old", "new");
?>
也检查此链接 http://www.codersmount.com/2011/07/smart-way-for-renaming-uploaded-files-using-php/
答案 1 :(得分:1)
您应该在$ form_data上执行print_r或var_dump,因为我怀疑数据是否传递给&#39; test_pack_name&#39;不正确并导致重命名失败。我还要包括swapnesh的建议,即在 if 中报告重命名的成功或失败,以便为您提供额外的调试信息。
答案 2 :(得分:0)
PHP rename();
函数
rename ("123", "abc");
rename ("oldname", "newname");
答案 3 :(得分:0)
PHP rename()
返回true
或false
所以你可以检查是否通过if
声明
if(rename())
echo "Success";
else
echo "failure";
答案 4 :(得分:0)
您可以像其他人建议的那样使用rename
。或者只是简单地使用上传时间重命名文件。这就是我通常做的事情。看看:
//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;
希望这有帮助。
答案 5 :(得分:0)
简单易用的方法
if( !rename($filePath, $newFileName) ) {
echo "File can't be renamed!";
}
else {
echo "File has been renamed!";
}