I am trying to make this code rename the file it is uploading with a unique file
ID: 3546768 • Letter: I
Question
I am trying to make this code rename the file it is uploading with a unique file name and keep its extension. Please help! I will rate high!
<?php
$allowedExts = array("txt", "dxf","DXF", "pdf", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "text/plain")
|| ($_FILES["file"]["type"] == "application/octet-stream")
|| ($_FILES["file"]["type"] == "application/pdf")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 2000000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo ".tmpFiles: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists(".tmpFiles/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
".tmpFiles/" . $_FILES["file"]["name"]);
echo "Stored in: " . ".tmpFiles/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
include('list.php');
?>
Explanation / Answer
test this code (file_exists($uploadpath)){ //get filename without suffix $rootname = basename($_FILES['fileup']['name'], $type); //add $i to the file name between rootname and extension (suffix) $uploadpath = "upload/".$rootname."-$i.".$type; $i++; } Add it like this if($err == '') { $i = 1; while(file_exists($uploadpath)){ //get filename without suffix $rootname = basename($_FILES['fileup']['name'], $type); $uploadpath = "upload/".$rootname."-$i.".$type; $i++; } if(move_uploaded_file($_FILES['fileup']['tmp_name'], $uploadpath)) { echo 'Success!'; echo 'File: '. basename( $_FILES['fileup']['name']). ''; echo '
File type: '. $_FILES['fileup']['type'] .''; echo '
Size: '. number_format($_FILES['fileup']['size']/1024, 3, '.', '') .' KB'; echo '
File path: '; } else echo 'Unable to upload the file.'; }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.