I got this code from w3schools, and tweaked it based on this one: Rename an uploaded file with PHP but keep the extension
Please help, what do I do so that the file extension will not be .tmp When I upload it to a folder on the server.
<?php
$filename=$_FILES["file"]["tmp_name"];
$extension=end(explode(".", $filename));
$newfilename=$prod .".".$extension;
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 100000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_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("../img/user_uploaded/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($filename,
"../img/user_uploaded/" . $newfilename);
echo "Stored in: " . "../img/user_uploaded/" .$newfilename;
}
}
}
else
{
echo "Invalid file, File must be less than 100Kb in size with .jpg, .jpeg, or .gif file extension";
}
?>
You can simply change the name of the file by changing the name of the file in the second parameter of move_uploaded_file . $temp = explode(".", $_FILES["file"]["name"]); $newfilename = round(microtime(true)) . '.
Solution: We need to rename by appending increment number to the filename if file exists using PHP file_exists() function.
In PHP, we can access the actual name of the file which we are uploading by keyword $_FILES[“file”][“name”]. The $_FILES is the by default keyword in PHP to access the details of files that we uploaded.
Definition and Usage The move_uploaded_file() function moves an uploaded file to a new destination. Note: This function only works on files uploaded via PHP's HTTP POST upload mechanism. Note: If the destination file already exists, it will be overwritten.
$filename=$_FILES["file"]["tmp_name"];
$extension=end(explode(".", $filename));
$newfilename=$prod .".".$extension;
In the above code you are trying to get the temporary file's extension. Instead, you can take the extension of the original filename uploaded by the user.
$filename=$_FILES["file"]["name"];
$extension=end(explode(".", $filename));
$newfilename=$prod .".".$extension;
This will upload your file with the actual file extension.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With