I have a simple piece of code for uploading the files in php/mysql and it works well.
$target = "uploads/clients/";
$target = $target . basename( $_FILES['photo']['name']);
$pic=($_FILES['photo']['name']);
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
$insertSQL = sprintf("INSERT INTO clients (img, `cname`) VALUES (%s, %s)",
GetSQLValueString($pic, "text"),
GetSQLValueString($_POST['cname'], "text"));
mysql_select_db($database_thebest, $thebest);
$Result1 = mysql_query($insertSQL, $thebest) or die(mysql_error());
Now what I want is to rename the filename if that filename already exists and then insert the renamed filename to the database
Thanks for your reply
Try this...
$upload_dir = "uploads/clients/";
$target = $upload_dir . basename( $_FILES['photo']['name']);
while(file_exists($target)){
$new = time().rand();
$target = $upload_dir . '_' . $new . '_' . basename( $_FILES['photo']['name']);
}
// rest of the code now...
$pic= $new . ($_FILES['photo']['name']);
You can do it by many ways.
Method 1
Check file_exists() before save to the server :
if (file_exists("../img/imageDirectory/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $_FILES["file"]["name"]);
// Others insert statements here...
}
Method 2
Use microtime() to generate unique name for each file :
$temp = explode(".",$_FILES["file"]["name"]);
$newfilename = substr(microtime(), 2, 7) . '.' .end($temp);
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename;
mysql_* functions are deprecated. Do not use them any more.
Try to use PDO or mysqli.
Run a SELECT query checking to see if the name exists. If it does not, INSERT it. So, select all from your table where the name = your file name. If numrows > 0 you change the name.
Actually why don't you just use the auto increment value as the name and store whatever you want to call it in a separate column. Then you'll know each name will be different and you won't have crazy long urls or file names.
First you must check table, that filename already exists or not.
select * from client where cname="filename";
if filename exist, you can must change filename .
Related
I am trying to upload image files to a server and creating a random name when doing so. The issue I am having is that sometimes (far too often) it creates the same file name but for files with a different extension.
My code for the upload is below, what I want to do is add a check to make sure the name is not in use but with a different extension.
Example -
da4fb5c6e93e74d3df8527599fa62642.jpg & da4fb5c6e93e74d3df8527599fa62642.JPG
if ($_FILES['file']['name']) {if (!$_FILES['file']['error']){
$name = md5(mt_rand(100, 200));
$ext = explode('.', $_FILES['file']['name']);
$filename = $name . '.' . $ext[1];
$destination = $_SERVER['DOCUMENT_ROOT'] . '/images/infopages/' . $filename; //change this directory
$location = $_FILES["file"]["tmp_name"];
move_uploaded_file($location, $destination);
echo '/images/infopages/' . $filename;
}else{
echo $message = 'Ooops! Your upload triggered the following error: '.$_FILES['file']['error'];
}
}
Any help is appreciated.
You can use PHP uniqid & rand functions combinedly. In this way you will never get duplicate values.
$filename = uniqid (rand(1000000,9999999), true) '.' . $ext[1];
I am currently able to perform an upload of multiple images and then inserting the file paths into a row in the database. Ideally I need to find a way to upload these files paths as separate entries with their own ID. The reason why is because the image paths I am inserting are to be bound to a task which is inserted into a separate table.
function upload_file_new_task(){
global $db;
if(isset($_POST['create'])) {
$path = "../uploads/";
for ($i=0; $i<count($_FILES['files']['name']); $i++) {
$ext = explode('.', basename( $_FILES['files']['name'][$i]));
$path = $path . md5(uniqid()) . "." . $ext[count($ext)-1];
move_uploaded_file($_FILES['files']['tmp_name'][$i], $path);
}
$sql = "INSERT INTO upload_data (`image`) VALUES ('$path');";
$res = mysqli_query($db,$sql);
echo "<p>Post Created $date</p>";
}
}
So theimage is uploaded into the /uploads folder, the path is then loaded into the database as a single row with an id in the ID field and the path(s) are loaded into the image field.
Something like
function upload_file_new_task()
{
global $db;
if(isset($_POST['create']))
{
$path = "../uploads/";
for ($i=0; $i<count($_FILES['files']['name']); $i++)
{
$ext = pathinfo($_FILES['files']['name'][$i], PATHINFO_EXTENSION);
$path1 = $path . md5(uniqid()) . "." . $ext;
move_uploaded_file($_FILES['files']['tmp_name'][$i], $path1);
$sql = "INSERT INTO upload_data (`image`) VALUES ('$path1');";
$res = mysqli_query($db,$sql);
}
echo "<p>Post Created $date</p>";
}
}
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 ).
here is my problem i need to rename the images when someone upload it, i want to use date and time and to created the $datatime value and i dont know how to make it works can some tell me how to do it? any help much be appreciated... Much Thanks
<?php if(isset($_POST['action'])=='uploadfiles') {
$time = time();
$date = date('Y-m-d');
$datetime = "$time" . "$date";
$upload_directory ='uploads/';
$count_data =count($_FILES['data']) ;
$upload = $_FILES['data']['name'][$x].',';
for($x=0;$x<$count_data;$x++) {
$upload .= $_FILES['data']['name']["$x" . ""].',';
move_uploaded_file($_FILES['data']['tmp_name'][$x], $upload_directory . $_FILES['data']['name'][$x]); ##### upload into your directory }
//echo "upload successfully..";
$con="INSERT INTO inmuebles (foto1) values ('$upload')";
$query=mysql_query($con); } ?>
Change here:
move_uploaded_file(
$_FILES['data']['tmp_name'][$x],
$upload_directory . $datetime . $_FILES['data']['name'][$x]
); ##### upload into your directory
Here the $datetime should be the string containing the timestamp.
Try the following:
$ext = pathinfo($_FILES['data']['name'][$x], PATHINFO_EXTENSION);
$newname = $datetime . '.' . $ext;
move_uploaded_file($_FILES['data']['tmp_name'][$x],
$upload_directory . $newname);
This will replace the current filename, and maintain the extension of the originally uploaded file.
If you want to maintain the original filename and simply append the datetime to it, use the following:
$info = pathinfo($_FILES['data']['name'][$x]);
$ext = $info['extension'];
$name = $info['filename'];
$newname = $name . $datetime . '.' . $ext;
move_uploaded_file($_FILES['data']['tmp_name'][$x],
$upload_directory . $newname);
Using date and time is a poor way to uniquely label anything because the limit of your fidelity is 1 item per second and computers are WAY faster than that, along with the fact more than 1 person could be using the upload at the same time. Instead use something build for this such as UUID (aka GUIDs). You can just use the uniqid() function in PHP which is very basic or if you read the comments somebody has written a UUID function (use version 5).
http://php.net/manual/en/function.uniqid.php
I am trying to upload an image to the server (with a path in mysql table) twice through php with different names. One version of the image as "xxxx.png" and the other version of the image as "xxxxt.png".
My php is:
<?php
if ($_FILES['photo']) {
$target = "images/properties/";
$target = $target . basename( $_FILES['photo']['name']);
$pic = "images/properties/" .(mysql_real_escape_string($_FILES['photo']['name']));
if (move_uploaded_file($_FILES['photo']['tmp_name'], $target)) {
mysql_query("INSERT INTO `images` (`productcode`, `photo`) VALUES ('$productcode', '$pic' )");
echo "The new image has been added successfully";
} else {
echo "Error uploading new image - please check the format and size";
}
}
?>
The above code inserts the image into the mysql database and uploads the file to the server correctly.
I am however trying to upload the same image twice with a different naming convention on a "thumbnail" version. The slideshow script in my html only recognises the thumbnails if there are named with a "t" at the end of the filenames hence my problem.
I have been advised to look at the php copy() function to achieve this but am incredibly unclear as to how to incorporate such a function into my existing code.
Happy to provide the html or any other info if required.
Any help much appreciated. I did have another thread attempting to find out the same thing but I wasn't very clear!
Thanks
JD
If I correctly understand you, you do not need to upload this file twice. You already have this file on your server. So you should copy it (optionally do some transitions to make it more like a thumbnail) on your server's hard drive and update database.
Your code should like similar to this:
<?php
if($_FILES['photo'])
{
$target_dir = "images/properties/";
$upload_file_name = basename( $_FILES['photo']['name']);
$upload_file_ext = pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION);
$target_file = $target_dir . $upload_file_name . '.' . $upload_file_ext;
$target_file_sql = $target_dir . mysql_real_escape_string($upload_file_name . '.' . $upload_file_ext);
$target_thumb = $target_dir . $upload_file_name . 't.' . $upload_file_ext;
$target_thumb_sql = $target_dir . mysql_real_escape_string($upload_file_name . 't.' . $upload_file_ext);
if (move_uploaded_file($_FILES['photo']['tmp_name'], $target_file))
{
mysql_query("INSERT INTO `images` (`productcode`, `photo`) VALUES ('$productcode', '$target_file_sql' )");
echo "The new image has been added successfully";
if (copy($target_file, $target_thumb))
{
mysql_query("INSERT INTO `images` (`productcode`, `photo`) VALUES ('$productcode', '$target_thumb_sql' )");
echo "The new thumb image has been added successfully";
} else
{
echo "Error copying thumb file";
}
} else
{
echo "Error uploading new image - please check the format and size";
}
}
Again, the idea is that you do not need to upload file twice in a row. All you need to do is just copy it on server.
As you've been advised you should use copy(). I didn't fully test this but give it a try:
<?php
if ($_FILES['photo'])
{
$target = "images/properties/";
$ext = array_pop(explode('.', $_FILES['photo']['name']));
$copy = $target . basename($_FILES['photo']['name'], '.' . $ext) . 't.' . $ext;
$target = $target . basename($_FILES['photo']['name']);
$pic = "images/properties/" .(mysql_real_escape_string($_FILES['photo']['name']));
if (move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
copy($target, $copy);
mysql_query("INSERT INTO `images` (`productcode`, `photo`) VALUES ('$productcode', '$pic' )");
echo "The new image has been added successfully";
}
else
{
echo "Error uploading new image - please check the format and size";
}
}
?>