PHP move_uploaded_file Rename file - php

I know that move_uploaded_file() sets the name of the uploaded file and sets the destination also. I have this:
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = $_SERVER['DOCUMENT_ROOT'] . '/img/profiles/'.$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file`
I have tried explode $_FILES['file']['tmp_name'] but I don't get to change the name of my uploaded file to my POST variable $newfile=$_POST["something"];
Thank you in advance

I am using
//File name
$file_name = $_FILES["file"]["name"];
$file_name = preg_replace('/\\.[^.\\s]{3,4}$/', '', $file_name);
// get extension
$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
// change name
$imagename = $file_name . time() . "." . $ext;

Set the entire upload path with the file name in $targetpath variable.
In you code
$sourcePath = $_FILES['file']['tmp_name'];
$newfile=$_POST["something"]; //any name sample.jpg
$targetPath = $_SERVER['DOCUMENT_ROOT'] . '/img/profiles/'.$newfile;
move_uploaded_file($sourcePath,$targetPath) ;
Now the uploaded file name is sample.jpg
I think this will helpful for you.

Related

rename file while uploading with php

I have a php script which uploads files:
for($index = 0;$index < count($_FILES['files']['name']); $index++){
// File name
$filename = $_FILES['files']['name'][$index];
// File path
$path = '../pdf/'.$filename;
// Upload file
if(!move_uploaded_file($_FILES['files']['tmp_name'][$index],$path)){
// ERROR
exit;
}
This works fine!
But I would like to modify the filename while uploading:
For example:
I uploading a "upload.pdf" file.
But I would like to get the name "upload_2021.pdf"
How can I realize it?
I found a solution !!
$path = '../pdf/'.$filename;
$extension = pathinfo($path, PATHINFO_EXTENSION);
$name = pathinfo($path, PATHINFO_FILENAME);
From what I can see, the only thing you need to do is change the $path variable.
Bare in mind, that what you are showing here is not a safe and secure upload script. You are not doing any file and mime-type validation what so ever. There is nothing preventing your users from uploading harmful files. Together with not checking for duplicate files and some other edge cases, think twice before putting this into production.
for($index = 0;$index < count($_FILES['files']['name']); $index++){
// File name
$filename = $_FILES['files']['name'][$index];
$parts = explode(".", $filename);
$year = date("Y");
// File path
$path = '../pdf/'.$parts[0] . '_' $year . '.' . $parts[count($parts)-1];
// Upload file
if(!move_uploaded_file($_FILES['files']['tmp_name'][$index],$path)){
// ERROR
exit;
}
}
a short example:
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);

How to change image name to current time stamp php?

I want to change image name with current time stamp in php.
My code are below :
$logo = basename($_FILES['file']['name']);
$logo = image1.jpg
move_uploaded_file($_FILES['file']['tmp_name'], '../timeTableImg/' . $_FILES['file']['name']);
i get image name in $logo. But Actually i want
$logo = 1484900616.jpg
move_uploaded_file($_FILES['file']['tmp_name'], '../timeTableImg/' . $_FILES['file']['name']);
file name may be dynamic. its may be jpg , png, jpeg. Also want to move file with new name.
Use move_uploaded_file function.
Example:
$file_path = "uploads/";
$newfile = date('m-d-Y_H:i:s')'.jpg';
$filename = $file_path.$newfile;
if(!file_exists($filename))
{
if(move_uploaded_file($_FILES['file']['tmp_name'],$filename))
{
// Other codes
}
}
else
{
echo 'file already exists';
}
Try this.
$path = $_FILES['file']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
$logo = time().'.'.$ext;
And to use the new name. put this.
move_uploaded_file($_FILES['file']['tmp_name'], '../timeTableImg/' . $logo);

How to save the full path of file upload in php?

I am using Laravel and I have a form that uploading a file. And I want to save the full path of that file in my database. Do you know how?
if($request->hasFile('alternate_add_file_path')) {
$file = $request->file('alternate_add_file_path');
$destination = 'files/';
$extension = $file->getClientOriginalExtension();
$file_name = $getCreateDate . '_' . str_replace('/','_',$M_USER_NAME) . '.' . $extension;
$file->move($destination, $file_name );
}
This below is for the save into database
$M_FILE_PATH = $file_name;
I do not have an error though, just only the filename which saved into my database, not the full path.
To convert a relative path to an absolute one (server side) you can use realpath. Eg.
$fullpath = realpath($file_name);

Echoing File Name using PHP

I am using Uploadify to upload a file. The filename is randomized by the PHP when uploaded. I need to echo the file name back to the JS. I don't know enough PHP to do this.
Here is my PHP Script:
<?php
$targetFolder = '/uploads';
$verifyToken = md5('unique_salt' . $_POST['timestamp']);
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$fileParts = pathinfo($_FILES['Filedata']['name']);
$targetFile = sprintf('%s/%s.%s', $targetPath, uniqid(), $fileParts['extension']);
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png','doc','docx','pdf','xlsx','pptx','tiff','tif','odt','flv','mpg','mp4','avi','mp3','wav','html','htm','psd','bmp','ai','pns','eps'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
echo '1';
} else {
echo 'Invalid file type.';
}
}
?>
If I understand the script correctly where the echo '1' at the bottom of the script is where the file name should be. How do I insert the changed or randomized file name there?
Your $targetFile variable contains the full path to your uploaded file (once moved). If you just want the filename part, use basename(), eg
echo basename($targetFile);
See http://php.net/basename

Having trouble with explode() in uploadify.php

I have this snippet from my uploadify.php:
if (!empty($_FILES)) {
$name = $_FILES['Filedata']['name'];
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
$path = pathinfo($targetFile);
// this portion here will be true if and only if the file name of the uploaded file does not contain '.', except of course the dot(.) before the file extension
$count = 1;
list( $filename, $ext) = explode( '.', $name, );
$newTargetFile = $targetFolder . $filename . '.' . $ext;
while( file_exists( $newTargetFile)) {
$newTargetFile = $targetFolder . $filename . '(' . ++$count . ')' . '.' . $ext;
}
// Validate the file type
$fileTypes = array('pdf'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$newTargetFile);
echo $newTargetFile;
} else {
echo 'Invalid file type.';
}
return $newTargetFile;
}
Basically this is quite working. Uploading the file and getting the path of the file which will then be inserted on the database and so on. But, I tried uploading a file which file name looks like this,
filename.1.5.3.pdf
and when succesfully uploaded, the file name then became filename alone, without having the file extension and not to mention the file name is not complete. From what I understood, the problem lies on my explode(). It exploded the string having the delimiter '.' and then assigns it to the variables. What will I do to make the explode() cut the string into two where the first half is the filename and the second is the file extension? PLease help.
Don't use explode, use a function designed for the job: pathinfo()
$ext = pathinfo($_FILES['Filedata']['name'], PATHINFO_EXTENSION);

Categories