I made a uload sistem using php and html, and java, but i am worried about the duplipicate files. How can I made it to save with a random name and add its extension?
<?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>
How can I made it to save it with a random name?
There are some functions in which you can generate random strings in several languages. In PHP, you can use md5()
and uniqid()
, for example.
Your code is uploading the file with the name of the original file. So, if you want to avoid duplicating filenames, just generate a unique code and include to the filename. In addition, you can use the time()
function to add a timestamp to the filename which will prevent duplicated filenames though.
$file_name = time() . "-" . $_FILES['image']['name'];
// output: "1615273926-filename.jpg"
If you want to invert the order of filename and the timestamp in the example above, you can use pathinfo()
function. See:
$file_name_pathinfo = pathinfo($_FILES['image']['name']);
$file_name = $file_name_pathinfo['basename'] . "-" . time() . "." . $file_name_pathinfo['extension'];
// output: "filename-1615273926.jpg"
This should prevent files with duplicated names.
LEARN MORE:
Try with some random numbers
$file_name = ['image']['name'];
$random = rand(000,999);
$random = str_pad($random, 3, '0', STR_PAD_LEFT);
$imgname = $random.$file_name;
In move upload
move_uploaded_file($_FILES["userImage"]["tmp_name"], "uploaddirectory/" . $imgname);
Put above line in condition check if you want for file exists
if (file_exists("uploaddirectory/" . $imgname)
{
echo $imgname . " already exists. ";
die;
}
else
{
//do something
}
Add timestamp to the end of the file name which makes it unique.
$fileName = time() .' '. $_FILES['image']['name'];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.