rename upload file, post new name to database - php

I'm using the following code to upload and rename files. That part works awesome, however it also posts some data to a db table.
The problem is the old name is getting posted to the db, but the file is renaming to the ID...how can I get the new name into the db?
Thanks in advance here is my code:
<?php
//This is the directory where images will be saved
$allowed_filetypes = array('.jpg','.pdf','.xlsx','.xls','.doc','.docx','.ppt','.pptx','.jpeg','.png','.gif','.pdf');
$max_filesize = 52428800; // max file size = 50MB
$target = $target . basename( $_FILES['document']['name']);
//This gets all the other information from the form
$billing_id=$_POST['billing_id'];
$shipping_id=$_POST['shipping_id'];
$file_name=$_POST['file_name'];
$file_type=$_POST['file_type'];
$file_description=$_POST['file_description'];
$file = $_FILES['document']['name']; // Get the name of the file (including file extension).
$ext = substr($file, strpos($file,'.'), strlen($file)-1);
if(!in_array($ext,$allowed_filetypes))//check if file type is allowed
die('The file extension you attempted to upload is not allowed.'); //not allowed
if(filesize($_FILES['document']['tmp_name']) > $max_filesize) //check that filesize is less than 50MB
die ('The file you attempted to upload is too large, compress it below 50MB.');
// Connects to your Database
mysql_connect("localhost", "root", "password") or die(mysql_error()) ;
mysql_select_db("table") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO customer_files (billing_id, shipping_id, file_name, file_type, file_description, file)
VALUES ('$billing_id', '$shipping_id', '$file_name', '$file_type', '$file_description', '$target')") ;
$target = "../../file_management/uploads/customers/" .mysql_insert_id() . $ext;
//Writes the file to the server
if(move_uploaded_file($_FILES['document']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>

You are inserting the values to the database before you are renaming the file. You have to make change in your code. First insert the billing and shipping id in the databse, then take the last inserted id, rename the file with the last insert id and update the new name in databse. Change your code to:
<?php
//This is the directory where images will be saved
$allowed_filetypes =array('.jpg','.pdf','.xlsx','.xls','.doc','.docx','.ppt','.pptx','.jpeg','.png','.gif','.pdf');
$max_filesize = 52428800; // max file size = 50MB
$target = $target . basename( $_FILES['document']['name']);
//This gets all the other information from the form
$billing_id=$_POST['billing_id'];
$shipping_id=$_POST['shipping_id'];
$file_name=$_POST['file_name'];
$file_type=$_POST['file_type'];
$file_description=$_POST['file_description'];
$file = $_FILES['document']['name']; // Get the name of the file (including file extension).
$ext = substr($file, strpos($file,'.'), strlen($file)-1);
if(!in_array($ext,$allowed_filetypes))//check if file type is allowed
die('The file extension you attempted to upload is not allowed.'); //not allowed
if(filesize($_FILES['document']['tmp_name']) > $max_filesize) //check that filesize is less than 50MB
die ('The file you attempted to upload is too large, compress it below 50MB.');
// Connects to your Database
mysql_connect("localhost", "root", "password") or die(mysql_error()) ;
mysql_select_db("table") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO customer_files (billing_id, shipping_id) VALUES ('$billing_id', '$shipping_id')") ;
$target = "../../file_management/uploads/customers/" .mysql_insert_id() . $ext;
$last_id = mysql_insert_id();
$new_file_name = mysql_insert_id() . $ext;
mysql_query("UPDATE customer_files SET file_name='$new_file_name',file_type='$file_type',file_description='$file_description',file='$target' WHERE id=$last_id");
//Writes the file to the server
if(move_uploaded_file($_FILES['document']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
Hope this helps

The new 'name' is already in the DB - it's the primary key of the record that was created when you inserted the upload data:
$target = "../../file_management/uploads/customers/" .mysql_insert_id() . $ext;
^^^^^^^^^^^^^^^^^ the new filename

Related

PHP Undefined index on file upload

I'm trying to upload a file but I always get an error:
Notice: Undefined index: file_pdf in C:\xampp\htdocs\FYP2\site_admin\pentadbiran\upload.php on line 10
The example of my code get data from a form and upload to my database for the information given, such as file_reference, file_name, file_location and file_pdf.
But the problem is, the code runs well but does not update on file_pdf column in table. But the file upload into target folder is working.
if (isset($_POST['submit'])) {
$file_reference = $_POST['file_reference'];
$file_name = $_POST['file_name'];
$file_location = $_POST['file_location'];
$file_pdf = $_POST['file_pdf'];
if ($_FILES['file_pdf']['error'] == UPLOAD_ERR_OK)
{
$ext = strtolower(pathinfo($_FILES['file_pdf']['name'],PATHINFO_EXTENSION));
switch ($ext)
{
case'pdf':
break;
default:
throw new InvalidFileTypeException($ext);
}
$targetfolder = "pdf/";
$targetfolder = $targetfolder . basename($_FILES['file_pdf']['name']);
if (move_uploaded_file($_FILES['file_pdf']['tmp_name'], $targetfolder)) {
echo "The file " . basename($_FILES['file_pdf']['name']) . " is uploaded";
} else {
echo "Problem uploading file";
}
$sql = "INSERT INTO file (file_reference,file_name,file_location,file_pdf)
VALUES ('$file_reference','$file_name','$file_location','$file_pdf')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
The code is run but on my database the file_pdf does not update.Why is this?
The global $_FILES will contain all the uploaded file information. Its contents from the example form is as follows. Note that this assumes the use of the file upload name userfile, as used in the example script above. This can be any name.
$_FILES['userfile']['name'] The original name of the file on the client machine.
$_FILES['userfile']['type'] The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.
$_FILES['userfile']['size'] The size, in bytes, of the uploaded file.
$_FILES['userfile']['tmp_name'] The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES['userfile']['error'] The error code associated with this file upload.
Change this...
$file_pdf = $_POST['file_pdf'];
to
$file_pdf = $_FILES['file_pdf']['name'];

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 Uploader, can't upload to specified path, getting error

I am fairly new to PHP coding, but I am trying to do something that is quite simple.
When someone on my website uploads a picture, the image will get renamed to random numbers and moved to my directory 'uploads/'
In my script below, Everything has been working up until :
// Upload the file to your specified path.
if(move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_path . $filename))
echo "Your file has been added. Redirecting in 3 seconds."; //it worked
else
echo "There was a problem uploading your file. Please try again later."; // It failed :(.
I have all of the variables defined.
not sure what the problem is here. Should I post my whole script for the uploader?
Here is the form:
<form enctype="multipart/form-data" action="uploader.php" method="POST">
<p>
<input type="hidden" name="MAX_FILE_SIZE" value="1048576" />
Choose a file to upload:
<br>(Only .jpg, .png, & .gif are allowed. Max file size = 1MB)</br></p>
<input name="uploadedfile" type="file" />
<input type="submit" value="Upload File" />
</form>
Here is my 'uploader.php'
<?php
header('Refresh: 3; URL=index.html');
$path = $_FILES['uploadedfile']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
//This line assigns a random number to a variable. You could also use a timestamp here if you prefer.
$ran = rand () ;
//This takes the random number (or timestamp) you generated and adds a . on the end, so it is ready of the file extension to be appended.
$ran2 = $ran.".";
//This assigns the subdirectory you want to save into... make sure it exists!
$target = "uploads/";
//This combines the directory, the random file name, and the extension
$target = $target . $ran2.$ext;
$ext = ".".$ext;
$upload_path = "uploads/";
$filename = $target;
$allowed_filetypes = array('.jpeg','.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
$max_filesize = 1048576; // Maximum filesize in BYTES (currently 0.5MB).
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
// Check if the filetype is allowed, if not DIE and inform the user.
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.'.$ext);
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
// Upload the file to your specified path.
if(move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_path . $filename))
echo "Your file has been added. Redirecting in 3 seconds."; //it worked
else
echo "There was a problem uploading your file. Please try again later."; // It failed :(.
?>
You're resetting $filename to the original name of the file, undoing all your random name generation:
$filename = $target;
$allowed_filetypes = array('.jpeg','.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
$max_filesize = 1048576; // Maximum filesize in BYTES (currently 0.5MB).
// this line circumvents the random filename generation
$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
Given that, I'd expect to see the above error if you upload a file with the same name twice.
Just get rid of that last $filename = .... line and see if your error goes away.
You try to move $_FILES['userfile']['tmp_name'] to another destination, but it seems your file is stored in $_FILES['uploadedfile']['tmp_name'] (as uploadedfile is the name of the file input in your form, and you correctly check it at the beggining of the script).
Also, I'd strongly recommend assigning all variables and using/modifying them in one place, otherwise you are vulenrable to such simple mistakes which are hard to track down.
Here's how I'd re-write your PHP code, it's a bit more clear I think:
<?php
header('Refresh: 3; URL=index.html');
//check if file uploaded correctly to server
if ($_FILES['uploadedfile']['error'] != UPLOAD_ERR_OK)
die('Some error occurred on file upload');
$filename = $_FILES['uploadedfile']['name'];
$uploadedFile = $_FILES['uploadedfile']['tmp_name'];
$ext = '.' . pathinfo($filename , PATHINFO_EXTENSION);
$upload_path = "uploads/";
//prepare random filename
do {
$newName = md5(rand().rand().rand().microtime()) . $ext;
} while (file_exists($upload_path . $newName));
$allowed_filetypes = array('.jpeg','.jpg','.gif','.bmp','.png'); // These will be the types of file that will pass the validation.
$max_filesize = 1048576; // Maximum filesize in BYTES (currently 0.5MB).
// Check if the filetype is allowed, if not DIE and inform the user.
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.'.$ext);
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($uploadedFile) > $max_filesize)
die('The file you attempted to upload is too large.');
// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
// Upload the file to your specified path.
if(move_uploaded_file($uploadedFile, $upload_path . $newName))
echo "Your file has been added. Redirecting in 3 seconds."; //it worked
else
echo "There was a problem uploading your file. Please try again later."; // It failed
?>

Upload file with PHP using a random temporary filename

I have a piece of code that uploads a file using it's current file name which is OK unless there is a file already on the server with that name and extension. How can I modify my code so that it uploads it with a random temporary file name before it renames it?
Here's my code:
if(!empty($_FILES['file']['name'])) {
copy($_FILES['file']['tmp_name'], WEB_UPLOAD."/pdf/".$_FILES['file']['name']) or die("Error uploading file.");
$ext = strtolower(substr($_FILES['file']['name'], strrpos($_FILES['file']['name'], ".")));
$filename = $url.$ext;
rename(WEB_UPLOAD."/pdf/".$_FILES['file']['name'], WEB_UPLOAD."/pdf/".$filename);
mysql_query ("UPDATE downloads SET file ='".$filename."' WHERE id = '".$insertid."'") or die (mysql_error());
}
Thank you for your continued help!
Pete
if(!empty($_FILES['file']['name'])) {
$targetFile = time().$_FILES['file']['name'];
copy($_FILES['file']['tmp_name'], WEB_UPLOAD."/pdf/".$targetFile) or die("Error uploading file.");
$ext = strtolower(substr($_FILES['file']['name'], strrpos($_FILES['file']['name'], ".")));
$filename = $url.$ext;
rename(WEB_UPLOAD."/pdf/".$targetFile , WEB_UPLOAD."/pdf/".$filename);
mysql_query ("UPDATE downloads SET file ='".$filename."' WHERE id = '".$insertid."'") or die (mysql_error());
}
With file name added current time stamp so file name will be unique.
//get the extension
$ext = strtolower(substr($_FILES['file']['name'], strrpos($_FILES['file']['name'], ".")));
//generate random name
$random_name = uniqid();
copy($_FILES['file']['tmp_name'], WEB_UPLOAD."/pdf/".$random_name . '.' . $ext) or die("Error uploading file.");
Now do whatever you want with it. The saved filename will be $random_name.'.'.$ext

Error while uploading file in PHP

While uploading the file in php i am not able to upload all types of file, if any space is there in between file name that is not able to download. Please can anyone correct this code
here is my upload code
<?php
$target_path = "../mt/sites/default/files/ourfiles/";
$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!";
}
$con = mysql_connect("localhost","mt","mt");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}else{
echo "Connected";
}
// Create table
mysql_select_db("mt", $con);
mysql_query("INSERT INTO mt_upload (FileName, FilePath)
VALUES ('".basename( $_FILES['uploadedfile']['name'])."', '".$target_path.basename( $_FILES['uploadedfile']['name'])."')");
// Execute query
mysql_query($sql,$con);
mysql_close($con);
?>
make some check and validation on the file u upload
the script below can help u :
// 5MB maximum file size
$MAXIMUM_FILESIZE = 5 * 1024 * 1024;
// Valid file extensions (images, word, excel, powerpoint)
$rEFileTypes =
"/^\.(jpg|jpeg|gif|png|doc|docx|txt|rtf|pdf|xls|xlsx|
ppt|pptx){1}$/i";
$dir_base = "/your/file/location/";
$isFile = is_uploaded_file($_FILES['Filedata']['tmp_name']);
if ($isFile) // do we have a file?
{// sanatize file name
// - remove extra spaces/convert to _,
// - remove non 0-9a-Z._- characters,
// - remove leading/trailing spaces
// check if under 5MB,
// check file extension for legal file types
$safe_filename = preg_replace(
array("/\s+/", "/[^-\.\w]+/"),
array("_", ""),
trim($_FILES['Filedata']['name']));
if ($_FILES['Filedata']['size'] <= $MAXIMUM_FILESIZE &&
preg_match($rEFileTypes, strrchr($safe_filename, '.')))
{$isMove = move_uploaded_file (
$_FILES['Filedata']['tmp_name'],
$dir_base.$safe_filename);}
}
}
Not sure if this works, but try to change line 2 to this:
$target_path = $target_path . basename( urldecode ( $_FILES['uploadedfile']['name'] ) );

Categories