Changing name of uploaded file in php - php

I am using the code bellow to upload a file using php and inserting file name into database. Actually I want to rename of file on uploading and want to insert new renamed name into database. I know how to insert name into database but I don't know how to rename uploaded file name. Please help.
I am using code bellow:
$target = "uploads/";
$target = $target . basename( $_FILES['uploaded']['name']);
move_uploaded_file($_FILES['uploaded']['tmp_name'], $target);
$add_file = $_FILES['uploaded']['name'];
Thank you so much..

Is this what you are looking for?
<?php
rename("/tmp/uploaded_file.txt", "/home/user/login/uploaded/67A7466B576.txt");
?>
So new code will be:
$target = "uploads/";
$target = $target . basename( $_FILES['uploaded']['name']);
rename($_FILES['uploaded']['tmp_name'], $target);
$add_file_to_db = $target;

This might be helpful for you:
$uploaded_file = time()."__".$_FILES['uploaded']['name'];
This simply adds time before the name of the file.
Example:
If I uploaded the AnalysisReport.doc file, then it simply becomes like 1354173106__AnalysisReport.doc

Related

php file uploading cannot retrieve the path

I am trying to upload photos in to folder uploads and its path to be recorded under photo in DB. This is my code:
$folder ="uploads";
$destFile = $folder . basename($_FILES["photo"]["name"]);
$sourdeFile = $_FILES["photo"]["tmp_name"];
if(move_uploaded_file($sourdeFile,$destFile)){
echo "File has been uploaded";
$photo = $destFile;
}else{
echo $_FILES['photo']['error'];
$photo = "images/default.png";
}
When I upload photos they successfully uploaded into folder but the problem is its path recorded as follow :
uploads42141402_1866830986743601_8538143552767524864_n.jpg
But to view photos in a page there should be \ next to uploads. So I tried to change my code as follow.
$folder = "uploads\";
But it generates this error
Can anyone say how to fix this ?
How about
$folder ="uploads/";
I've tried and it works. Maybe $folder ="uploads" . DIRECTORY_SEPARATOR; will better than "/".
For the error its looks uploads folder is not there or it not have permission
create a upload folder or try with absolute path
you can make use of dirname(__FILE__) or $_SERVER['DOCUMENT_ROOT'] for creating dynamic path

Rename file on upload PHP

I am trying to build a script to upload and rename an image to a folder and store the path in my sql db.
Here is where I am at: The file get uploaded both to the folder and the pathname to the db but I cannot figure out how to rename the filename. Ideally I would like to make the filename unique so I don't duplicates.
<?php
//preparing the patch to copy the uploaded file
$target_path = "upload/";
//adding the name of the file, finishing the path
$target_path = $target_path . basename( $_FILES['picture']['name']);
//moving the file to the folder
if(move_uploaded_file($_FILES['picture']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['picture']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
//getting input from the form
$name = $_POST['name'];
$description = $_POST['description'];
//preparing the query to insert the values
$query = "INSERT INTO complete_table (name, description, picture) VALUES ('$name', '$description', '". $target_path ."')";
//opening connection to db
$link = mysql_connect('localhost', 'root', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
//selecting a db
mysql_select_db("wcs_venues", $link) or die(mysql_error());
//running the query
$result = mysql_query($query) or die (mysql_error());
//closing the connection
mysql_close($link);
?>
I am new with all this and I am really trying but after looking at many tutorial and answered questions on Stack-overflow, I realized I needed help. Thank you in advance for helping this newbie.
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.
First get the file extension:
$file_extension = strrchr($uploaded_file_name, ".");
Then rename the uploaded file with a unique id + file extension
$uploaded_file_name = uniqid() . $file_extension;
Example:
TIP: Save the original file name and other information in a database.
First get the extension with pathinfo()
Then create your unique name:
$name = 'myname'.uniqid();
Then rename your file.
$target_path = $target_path . $name.$ext);
move_upload_file takes the second parameters $destination, its where you are inserting the target_path ( where your file is going to be saved with that given name ).

PHP upload to specific folder

I am trying to do a php upload that will upload into a specific folder.
One would choose the file they wish to upload next to a dropdown box which is a folder list. This is because it organises files.
<?php
session_start();
if(!isset($_SESSION["USER"]["Admin"])){
header("Location: index.html?unath");
}
$folder = mysql_real_escape_string($_POST['loc']);
$target_path = "../../shared/docs/$folder";
$upload2 = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $upload2)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
Currently the code uploads the file into the "docs" folder and not docs/folder. Instead it puts the folder name in front of the file. For example- if the folder is called "abc" and my file is called robs.docx it will upload it to the main Docs folder and call it abcrobs.docx
You have a missing slash
Replace this line:
$upload2 = $target_path . basename( $_FILES['uploadedfile']['name']);
with:
$upload2 = $target_path ."/". basename( $_FILES['uploadedfile']['name']);
OR:
Replace this line:
$target_path = "../../shared/docs/$folder";
with:
$target_path = "../../shared/docs/".$folder."/";
You do not need mysql_real_escape_string because there's no SQL involved here.
If no database connection is established, mysql_real_escape_string returns null. So you're probably throwing away the $_POST['loc'] value.
You should never ever use user supplied values for manipulating anything on the filesystem without really, really thorough inspection of what you're going to manipulate. See Security threats with uploads.
Use var_dump liberally to see what your values look like at various stages and do some debugging.
You are missing a slash after $target_path
Add a / on the end of your $target_path:
$target_path = "../../shared/docs/$folder/";
You should properly escape your variables:
$target_path = "../../shared/docs/". $folder ."/";

phpMailer sending attachment name, not attachment

Hi I have a file upload field with name="file1" and code in a phpmailer script:
if (isset($_FILES['file1']))
{
$file1_path = $_FILES['file1']['tmp_name'];
$file1_name = $_FILES['file1']['name'];
$file1_type = $_FILES['file1']['type'];
$file1_error = $_FILES['file1']['error'];
$mail->AddAttachment($file1_path);
}
And for some reason, it attached like php45we34 (each time diff, seems that its the temp name path, not the actual file)
Any help?
Strip spaces from your filename!
Blue hills.jpg should be Blue_hills.jpg
do
$fileName = str_replace(' ', '_', $fileName);
I suggest you to use function move_uploaded_file before adding attachment.
This is sample code that will move file from temporary location somewhere at your server
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
After that AddAttachment should work fine.
$mail->AddAttachment(basename($target_path . $_FILES['uploadedfile']['name']));
What you see is what should happen. You do not specify the attachment name, so phpMailer uses the name of the temporary file it's attaching.
If you want the file to have a different name, you have to specify it. The accepted answer works because it goes the other way round -- it changes the file name so that the file has the desired name.
The usual way to proceed would be to issue
$mail->AddAttachment($file1_path, $_FILES['file1']['name']);
to override the attachment name.

PHP zip Function issue

Hello I am usign the below code to zip a package on upload:
$nameFile = $_FILES['file']['name'];
$tmpName = $_FILES['file']['tmp_name'];
$download_folder = './CopyrightFiles/';
$zip = new ZipArchive();
$fileconpress = $download_folder.$nameFile.".zip";
$conpress = $zip->open($fileconpress, ZIPARCHIVE::CREATE);
if ($conpress === true)
{
$zip->addFile($tmpName);
$zip->close();
echo $fileconpress."<br/>";
echo "yess !! Success!!!! ";
}
else echo " Oh No! Error";
It seems to work ok.
But there are two issues.
First issue it saves the file also with the original extension, something like : image.JPG.zip
Also when I then move the zip package to my local computer (Mac) and I open the ZIP inside I can find only a tmp folder with a binary file inside and NOT the image or the file that should be there!
What the hell is going on?
Please advise
Thank you
That's because your "binary" file is just the temporary name that PHP used to temporarily stored the uploaded file as. That's why it's "tmp_name" in the $_FILES array.
Try this:
$zip->addFile($tmpName, $nameFile);
The second parameter lets you specify what the file's name should be within the zip.
To prevent 'file.jpg.zip', try:
$fileconpress = $download_folder . pathinfo($_FILES['file']['name'], PATHINFO_FILENAME) . ".zip";
Issue #1:
You need to manually remove the extension:
$filename = explode('.', $_FILES['file']['name']);
$filename = $filename[0];
Issue #2:
$tmpName does not contain the filename of the file. You need to pass the $localname parameter in addFile(). See http://php.net/manual/en/function.ziparchive-addfile.php.

Categories