Rename an uploaded file with PHP but keep the extension
You need to first find out what the original extension was ;-)
To do that, the pathinfo
function can do wonders ;-)
Quoting the example that's given in the manual :
$path_parts = pathinfo('/www/htdocs/index.html');
echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n"; // since PHP 5.2.0
Will give you :
/www/htdocs
index.html
html
index
As a sidenote, don't forget about security :
- In your case, you should escape
$_POST[lastname]
, to make sure it only contains valid characters- And, BTW, you should use
$_POST['lastname']
-- see Why is$foo[bar]
wrong?
- And, BTW, you should use
- You should also check that the file is an image
- See
mime_content_type
for PHP < 5.3 - And/or
finfo_file
for PHP >= 5.3
- See
How to change name of uploaded file without changing extension
$filename = basename($_FILES['file']['name']);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new = md5($filename).'.'.$extension;
if (move_uploaded_file($_FILES['file']['tmp_name'], "/path/{$new}"))
{
// other code
}
PHP file upload change file name keep extension
Since you said you already tried (and it looks like you really have), here is an explanation:
When you upload a file in PHP, the original filename goes to $_FILES['image']['name']
. In your code you set this value to the variable $file_name
.
You already have the extension of the file in $file_ext
, so you can use it.
If you have a specific string in the $custom_name
variable, you can use:
$file_name = $custom_name . $file_ext;
The second parameter of move_uploaded_file
is the path of the new file that you want to create (which in your example is "images/quads/".$file_name
). If the variable $file_name
will contain the $custom_name
and the $file_ext
- you will get what you want.
How to rename uploaded file before saving it into a directory?
You can simply change the name of the file by changing the name of the file in the second parameter of move_uploaded_file
.
Instead of
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $_FILES["file"]["name"]);
Use
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);
Changed to reflect your question, will product a random number based on the current time and append the extension from the originally uploaded file.
php rename the uploaded file with extension
Hello if i understand you correctly you are having problem extracting extension information. you can always use pathinfo
Example
$extention = pathinfo("first.jpeg ",PATHINFO_EXTENSION);
$newName = "secound." . $extention ;
var_dump($newName);
Output
string 'secound.jpg' (length=11)
Rename file on upload PHP
Well, this is where you set the name of the file being saved:
$target_path = "upload/";
$target_path = $target_path . basename( $_FILES['picture']['name']);
In this case, you're building the file name in the variable $target_path
. Just change that to something else. What you change it to is up to you. For example, if you don't care about the name of the file and just want it to always be unique, you could create a GUID or a Unique ID and use that as the file name. Something like:
$target_path = "upload/";
$target_path = $target_path . uniqid();
Note that this would essentially throw away the existing name of the file and replace it entirely. If you want to keep the original name, such as for display purposes on the web page, you can store that in the database as well.
PHP image upload - rename without losing extension?
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$newFilename = $random_digit . '.' . $ext;
BTW, what will happen if the random number clashes (which may happen next or in 10 years)?
There are many better ways to name them - for example, hash of the filename and time()
should theoretically never clash (though in practice hash collisions do occur).
Rename file Which is already uploaded
You might want to take a different approach here: Maybe upload the files and rename them to something convenient after upload, for example: id of table's row, and store the name of the file in your MySQL table (add a filename column), which the user can change.
Then when the user downloads the file, send the name stored in the database with the Content-disposition
header.
On upload:
$filename = mysqli_real_escape_string($db, basename($_FILES["pdf"]["name"]));
if (mysqli_query($db, "INSERT INTO tables (pdf) VALUES ('$filename')")) {
$id = mysqli_insert_id($db);
$folder = "files/" . $id;
move_uploaded_file($_FILES["pdf"]["tmp_name"], $folder);
}
When updating the filename, you will do something like this:
UPDATE tables SET pdf = '$newName' WHERE id = $id
(Don't forget to escape the input and sanitize the filename)
When serving the file to the user (user downloads the file)
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="' . $row["filename"] . '"');
readfile('files/' . $row["id"]);
rename file to specific name before upload php
$targetfolder = $targetfolder . basename( $_FILES['file']['name']) ;
When you are creating the $targetfolder
variable, you are adding the base name to it for some reason. Thus if the file was called something.jpg
and the target folder was /a/b/c/
you'll get /a/b/c/something.jpg
as the value of $targetfolder
.
Later in your code you add your own file name again:
if(move_uploaded_file($_FILES['file']['tmp_name'], $targetfolder .$filename))
So I think you'll be happy if you remove $targetfolder = $targetfolder . basename( $_FILES['file']['name']) ;
all together.
Related Topics
How to Detect and Handle MySQL Warnings with PHP
Shuffles Random Numbers with No Repetition in JavaScript/Php
How to Set an Absolute Include Path in PHP
Can't Find the File Created by Outfile in MySQL
Checking If an Instance's Class Implements an Interface
How to Send JSON Response in Symfony2 Controller
Is This the Correct Way to Send Email with PHP
Fatal Error: Call to Undefined Function: Ldap_Connect()
How to Expire PHP Session If User Is Inactive for 15 Mins
Remove Duplicated Elements of Associative Array in PHP
Permission Denied Despite Appropriate Permissions Using PHP
This Is the .Htaccess Code in Wordpress. Can Someone Explain How It Works
In Laravel How to Add Values to a Request Array
What Are the Differences of System(), Exec() and Shell_Exec() in PHP