使用PHP
重命名多个文件,它工作正常,但我需要将文件只保存为文件名的随机数
但在我的情况下,我得到随机数+文件名
当我删除文件名时,保存的图像没有extension
我只需要保存带有重命名名称的文件,我需要删除文件名并使用随机数保存我使用此方法生成随机数$newname = md5(rand() * time());
这里是重命名部分move_uploaded_file($file_tmp, "$desired_dir/" . $newname . $file_name);
当我删除$file_name
时,保存的输出文件没有扩展名
这里是我的代码
<?php
$db_username = 'sanoj';
$db_password = '123456';
if (isset($_FILES['files'])) {
$errors = array();
foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
$finfo = pathinfo($_FILES['files']['name'][$key]);
$extension = '';
if (!empty($finfo[PATHINFO_EXTENSION])) {
$extension = "." . $finfo[PATHINFO_EXTENSION];
}
$file_name = md5(rand() * time()) . "." . $extension;
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if ($file_size > 2097152000) {
$errors[] = 'File size must be less than 2 MB';
}
$desired_dir = "user_data/";
if (empty($errors) == true) {
if (is_dir($desired_dir) == false) {
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if (is_dir("$desired_dir/" . $file_name) == false) {
move_uploaded_file($file_tmp, "$desired_dir/" . $file_name);
} else { // rename the file if another one exist
$new_dir = "$desired_dir/" ;
rename($file_tmp, $new_dir);
}
} else {
print_r($errors);
}
}
重要以上代码适用于多张图片上传
答案 0 :(得分:0)
$extension = end(explode('.', $_FILES['image']['name']));
move_uploaded_file($file_tmp, "$desired_dir/" . $newname.".".$extension);
请尝试此而不是
move_uploaded_file($file_tmp, "$desired_dir/" . $newname . $file_name);
答案 1 :(得分:0)
获取文件的扩展名,检查,是否有扩展名,如果是,则附加到它,创建随机数,并将数字与扩展名合并:
$finfo = pathinfo($_FILES['files']['name'][$key]);
$extension = '';
if (!empty($finfo[PATHINFO_EXTENSION])) {
$extension = "." . $finfo[PATHINFO_EXTENSION];
}
$file_name = md5(rand() * time()) . "." . $extension;
答案 2 :(得分:0)
试试这个
$valid_formats = array("jpg", "png", "gif", "zip", "bmp");
$max_file_size = 1024*100; //100 kb
$path = "uploads/"; // Upload directory
$count = 0;
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to exeicute all files
foreach ($_FILES['files']['name'] as $f => $name) {
if ($_FILES['files']['error'][$f] == 4) {
continue; // Skip file if any error found
}
if ($_FILES['files']['error'][$f] == 0) {
if ($_FILES['files']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
continue; // Skip large files
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
continue; // Skip invalid file formats
}
else{ // No error found! Move uploaded files
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$name))
$count++; // Number of successfully uploaded file
}
}
}
}