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 - How to rename the uploaded file?
first we're creating the new file name and appending it to $newFileName
variable and then we're going to move the uploaded file to the new file name variable that we just created
<?php
$target_dir = "uploads/";
$newFileName = $target_dir .'YourfileName'.'.'. pathinfo($_FILES["fileToUpload"]["name"] ,PATHINFO_EXTENSION); //get the file extension and append it to the new file name
$uploadOk = 1;
$imageFileType = pathinfo($_FILES["fileToUpload"]["name"] ,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["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["fileToUpload"]["size"] > 500000) {
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["fileToUpload"]["tmp_name"], $newFileName)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
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. 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"]);
How to change name of uploaded file in php?
The second argument in move_uploaded_file() is the new filename, so all you need to do is change it to what you want.
if(move_uploaded_file($pic['tmp_name'], $upload_dir.'newtexture.jpg')){
how to rename file before upload in php
Try this:
<?php
include("uploadId.php");
$temp = explode(".", $_FILES["uploaded_file"]["name"]);
$extension = end($temp);
$path="/var/www/tcpdf/pictures/";
$filename = basename($_FILES["uploaded_file"]["name"]);
$filename = $_SESSION['id'] . strrchr($filename, '.') . $extension;
if(move_uploaded_file($_FILES["uploaded_file"]["tmp_name"],$path . $filename))
{
echo "Uploaded";
}
?>
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.
Related Topics
Posting to a Facebook Page as the Page (Not a Person)
Check If SQL Row Exists with PHP
Php: Best Way to Iterate Two Parallel Arrays
Datetime Now PHP MySQL (+ Pdo Variant)
Force Logout Users If Users Are Inactive for a Certain Period of Time
Pass Array to Where in Codeigniter Active Record
Count How Often a Particular Value Appears in an Array
Get Folders with PHP Glob - Unlimited Levels Deep
Looping Through a Simplexml Object, or Turning the Whole Thing into an Array
Finding First Day of Week via PHP
Force Download via Ajax and PHP
Use MySQL_Fetch_Array() with Foreach() Instead of While()
Does Die() End Your Session in PHP
Extend Request Class in Laravel 5
What Sort Algorithm Does PHP Use
Get User Data Using Access Token in Laravel Passport Client App