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
Related
My upload form for images is working good. Save name and path to database. I want to save full url to image along whit name instead just a name. What I mean is now in DB is saved file_name.jpg I want to save http://example.com/images/file_name.jpg. Here is the upload.php
define('MAX_FILE_SIZE', 20000000430);
$uploadDir = "../../img/";
$permitted = array('image/jpeg', 'image/jpeg', 'image/png', 'image/gif');
$fileName = $_FILES['image']['name'];
$tmpName = $_FILES['image']['tmp_name'];
$fileSize = $_FILES['image']['size'];
$fileType = $_FILES['image']['type'];
// make a new image name
$ext = substr(strrchr($fileName, "."), 1);
// generate the random file name
$randName = md5(rand() * time());
// image name with extension
$myFile = $randName . '.' . $ext;
// save image path
$path = $uploadDir . $myFile;
if (in_array($fileType, $permitted))
{
$result = move_uploaded_file($tmpName, $path);
if (!$result)
{
echo "Error uploading image file";
exit;
}
else
{
// keep track post values
$name = $_POST['name'];
$description = $_POST['description'];
// update data
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE food set name = ?, image = ?, path = ?, description = ?
WHERE id = ?";
$q = $pdo->prepare($sql);
$q->execute(array($name,$myFile,$path,$description,$id));
Database::disconnect();
echo "<code>Information updated!!</code>";
}
}
What I try is to put the URL in $uploadDir.
$uploadDir = "http://example.com/img/";
But I get this error.
Warning: move_uploaded_file(http://example.com/img/75a13564a8f3305fb0a30ab95487b8de.jpg): failed to open stream: HTTP wrapper does not support writeable connections
Also tried something like this and got same error
define('domainURL', 'http://'.$_SERVER['HTTP_HOST']);
$path = domainURL . $uploadDir . $myFile;
The move_uploaded_file function does not accept file url.
It accepts image actual path.
Because, your file is getting moved physically.
e.g. $path = $_SERVER['DOCUMENT_ROOT'] . 'img/'
You may use relative or absolute path.
Relative path is "../../img/";
Absolute path should be like "/www/htdocs/img/"; (you can see absolute path in FTP client)
And you cannot use URL.
For store in DB use another one variable with URL
assign the upload path in a php variable and use $path to store it in database..
$path = "www.sitename.com/uploads/".$filename ;
I have been trying to change the name of a file after an upload with my script.
I want every file to be named as "testing". Later I am going to change "testing" to a
variable that gets a unique name. Now I just want to change the name to "testing".
Also the script always says error although the file are uploaded.
Can I get some help here please?
Here is my code:
<?php
$uploadDir = 'images/'; //Image Upload Folder
if(isset($_POST['Submit']))
{
$fileName = $_FILES['Photo']['name'];
$tmpName = $_FILES['Photo']['tmp_name'];
$fileSize = $_FILES['Photo']['size'];
$fileType = $_FILES['Photo']['type'];
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$query = "INSERT INTO $db_table ( Image ) VALUES ('$filePath')";
mysql_query($query) or die('Error, query failed');
}
?>
I think you need
$fileName = "testing"; //maybe add extension
instead of getting original filename from $_FILES. Although after the file is moved you may end up with a situation of overwriting existing files as they all has the same name. To prevent that (for testing purposes) you may add something to $fileName, maybe a short random string.
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 ).
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
Dear friends, this is a script which simply upload file and insert filename into database, why is this not working ? It's just upload the file and send filename to db even after validation . Please help
<?php
//file validation starts
//split filename into array and substract full stop from the last part
$tmp = explode('.', $_FILES['photo']['name']);
$fileext= $tmp[count($tmp)-1];
//read the extension of the file that was uploaded
$allowedexts = array("png");
if(in_array($fileext, $allowedexts)){
return true;
}else{
$form_error= "Upload file was not supported<br />";
header('Location: apply.php?form_error=' .urlencode($form_error));
}
//file validation ends
//upload dir for pics
$uploaddir = './uploads/';
//upload file in folder
$uploadfile = $uploaddir. basename($_FILES['photo']['name']);
//insert filename in mysql db
$upload_filename = basename($_FILES['photo']['name']);
//upload the file now
move_uploaded_file($_FILES['photo']['tmp_name'], $uploadfile);
// $photo value is goin to db
$photo = $upload_filename;
function send_error($error = 'Unknown error accured')
{
header('Location: apply.php?form_error=' .urlencode($error));
exit; //!!!!!!
}
//file validation starts
//split filename into array and substract full stop from the last part
$fileext = end(explode('.', $_FILES['photo']['name'])); //Ricky Dang | end()
//read the extension of the file that was uploaded
$allowedexts = array("png");
if(!in_array($fileext, $allowedexts))
{
}
//upload dir for pics
$uploaddir = './uploads/';
if(!is_dir($uploaddir))
{
send_error("Upload Directory Error");
}
//upload file in folder
$uploadfile = $uploaddir. basename($_FILES['photo']['name']);
if(!file_exists($uploadfile ))
{
send_error("File already exists!");
}
//insert filename in mysql db
$upload_filename = basename($_FILES['photo']['name']);
//upload the file now
if(move_uploaded_file($_FILES['photo']['tmp_name'], $uploadfile))
{
send_error('Upload Failed, cannot move file!');
}
// $photo value is goin to db
$photo = $upload_filename;
This is a cleared up version to yours, give that a go and see if you get any errors
You can find the extension of file by using this code also.
$tmp = end(explode('.', $_FILES['photo']['name']));
now $tmp got the extension of file.
Why not use PHP's built-in functions to extract the extension from the filename?
$fileext = pathinfo($_FILES['photo']['name'],PATHINFO_EXTENSION);
And if the file extension is valid, you're returning from the function without doing anything further, if it's invalid you're setting the header, but the code logic will continue to your file processing
You blindly assume the file upload succeeded, but there's many reasons for it to fail, which is why PHP provides ['error'] in the $_FILES array:
if ($_FILES['photo']['error'] === UPLOAD_ERR_OK) {
// uploaded properly, handle it here...
} else {
die("File upload error, code #" . $_FILES['photo']['error']);
}
The error codes are defined here.