Masoud Javaheri asked
php
file-upload
upload
php
file-upload
upload
I copied the php upload script from w3schools and I did some changes to change the file name.
the only thing that I could do was to add a random name to the first of the file name but I need to remove its original name from the uploaded file.
for example I have a file named “abc.jpg”
After I upload this file, I can change it to a random name + original name like this “2716c3f3e9d6dd0a2b89f047b938750520aaa.jpg”
How can I delete the original name “aaa” from the end of uploaded file name in this code?
Thanks in advanced
$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.";
}
}
Answer
Replace this line:
$target_file = $target_dir . $rand . basename($_FILES['fileperson']["name"]);
With the following:
$extension = preg_replace('/.+?(.[^.]+)$/', '$1', $_FILES['fileperson']['name']);
$extension = $extension ? $extension : '.unknown';
$target_file = $target_dir . $rand . $extension;