我正在尝试通过以下代码找出如何重命名正在上传到我的服务器的照片。我能够正确上传照片,但我无法弄清楚如何更改名称。
例如,如何重命名照片以便将其命名为“renamed_image”?
谢谢!
<?php
$target_path = "./user_photos/";
$target_path = $target_path . basename( $_FILES['picture']['name']);
if(move_uploaded_file($_FILES['picture']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['picture']['name'])." has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
答案 0 :(得分:0)
$filename = basename($_FILES['file']['name']);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new = md5($filename).'.'.$extension;
if (move_uploaded_file($_FILES['file']['tmp_name'], "/path/{$new}"))
{
// other code
}
希望这有帮助
快乐编码
答案 1 :(得分:0)
$filename = $_FILES["file"]["name"];
$file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
$file_ext = substr($filename, strripos($filename, '.')); // get file name
$filesize = $_FILES["file"]["size"];
$allowed_file_types = array('.doc','.docx','.rtf','.pdf');
if (in_array($file_ext,$allowed_file_types) && ($filesize < 200000))
{
// Rename file
$newfilename = md5($file_basename) . $file_ext;
if (file_exists("upload/" . $newfilename))
{
// file already exists error
echo "You have already uploaded this file.";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $newfilename);
echo "File uploaded successfully.";
}
}
答案 2 :(得分:0)
只需使用:
$target_path = $target_path . $username . $extension;
move_uploaded_file($_FILES['picture']['tmp_name'], $target_path);
答案 3 :(得分:0)
修改你的代码
$ updated_name = str_replace('',' - ',str_basename($ _FILES ['picture'] ['name']); $ updated_name = rand(10,200)。$ updated_name;
这里我们在文件名中使用str_replace,可能会有一些额外的空间,当上传时抛出一个错误,所以str_replace会删除它,并在文件名中添加一个随机数将解决另一个问题,即。如果用户上传两次相同的文件名,那么当添加随机数字时,两个文件名将会不同