[英]PHP - Random file name when upload a file into directory and add to the bottom the file extension?
我使用 php 和 html 和 java 制作了一個 uload 系統,但我擔心重復文件。 如何讓它以隨機名稱保存並添加其擴展名?
<?php
if(isset($_FILES['image'])){
$errors= array();
$test = uniqid()
$file_name = ['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
$extensions= array("jpeg","jpg","png","rbxl","mp4","mp3");
if(in_array($file_ext,$extensions)=== false){
$errors[]="extension not allowed";
}
if($file_size > 600000000){
$errors[]='File size must be excately 600 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"images/".$file_name);
echo "https://glotech.cf/images/";
print_r($file_name);
}else{
print_r($errors);
}
}
?>
window.addEventListener("paste", e => { if (e.clipboardData.files.length > 0) { const fileImput = document.querySelector("#myFile"); fileImput.files = e.clipboardData.files; } });
<form action="/test.php" method="post" enctype="multipart/form-data"> <input type="file" name="image" id="myFile"> <input type="submit" /> </form>
我怎樣才能讓它用隨機名稱保存?
有一些函數可以生成多種語言的隨機字符串。 例如,在 PHP 中,您可以使用md5()
和uniqid()
。
您的代碼正在使用原始文件的名稱上傳文件。 因此,如果您想避免重復文件名,只需生成一個唯一代碼並包含到文件名中。 此外,您可以使用time()
function 為文件名添加時間戳,這將防止文件名重復。
$file_name = time() . "-" . $_FILES['image']['name'];
// output: "1615273926-filename.jpg"
如果要顛倒上例中文件名和時間戳的順序,可以使用pathinfo()
function。 看:
$file_name_pathinfo = pathinfo($_FILES['image']['name']);
$file_name = $file_name_pathinfo['basename'] . "-" . time() . "." . $file_name_pathinfo['extension'];
// output: "filename-1615273926.jpg"
這應該可以防止名稱重復的文件。
學到更多:
pathinfo
://www.php.net/manual/pt_BR/function.pathinfo.phptime()
: https://www.php.net/manual/pt_BR/function.time.php嘗試一些隨機數
$file_name = ['image']['name'];
$random = rand(000,999);
$random = str_pad($random, 3, '0', STR_PAD_LEFT);
$imgname = $random.$file_name;
在移動上傳
move_uploaded_file($_FILES["userImage"]["tmp_name"], "uploaddirectory/" . $imgname);
將上面的行放在條件檢查中是否需要文件存在
if (file_exists("uploaddirectory/" . $imgname)
{
echo $imgname . " already exists. ";
die;
}
else
{
//do something
}
將時間戳添加到文件名的末尾,使其唯一。
$fileName = time() .' '. $_FILES['image']['name'];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.