我从w3schools复制了php上传脚本,我做了一些更改来更改文件名。
我唯一可以做的就是在文件名的第一个中添加一个随机名称,但我需要从上传的文件中删除其原始名称。
例如我有一个名为" abc.jpg"
的文件上传此文件后,我可以将其更改为随机名称+此类原始名称" 2716c3f3e9d6dd0a2b89f047b938750520aaa.jpg"
如何删除原始名称" aaa"从此代码中上传的文件名末尾开始?
先谢谢
$rand = md5(md5(time()).md5(microtime())).rand(10,25);
$target_dir = "images/futsal/";
$file = $rand . basename($_FILES['fileperson']["name"]);
$target_file = $target_dir . $rand . basename($_FILES['fileperson']["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES['fileperson']["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES['fileperson']["size"] > 50000000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES['fileperson']["tmp_name"], $target_file)) {
echo "file ". $file . " uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
答案 0 :(得分:0)
您要在$target_file
变量的末尾添加上传的文件名。
更新代码以移除$_FILES['fileperson']["name"]
中的$target_file
。
$rand = md5(md5(time()).md5(microtime())).rand(10,25);
$target_dir = "images/futsal/";
$imageFileType = pathinfo($_FILES['fileperson']["name"],PATHINFO_EXTENSION);
$file = $rand . $imageFileType;
$target_file = $target_dir . $file;
答案 1 :(得分:0)
替换此行:
$target_file = $target_dir . $rand . basename($_FILES['fileperson']["name"]);
以下内容:
$extension = preg_replace('/.+?(\.[^.]+)$/', '$1', $_FILES['fileperson']['name']);
$extension = $extension ? $extension : '.unknown';
$target_file = $target_dir . $rand . $extension;