Storing the changed filename into mysql field - php

I have a form wherein users can upload images and these images are being saved on a particular folder in the server. At the same time the filename of the photo is being stored in a particular field in a MySQL table.
I tried changing the filename by adding a timestamp (and it works) however this new filename is not the filename being stored on the MySQL field meaning it stores the original photo filename from the user.
Is there a way that the new filename will be the one stored on MySQL table.
Below is the code I am using:
enter code here
//This is the directory where images will be saved
$target = "pics/";
$target = $target. basename( $_FILES['photo']['name']);
//This gets all the other information from the form
$name=$_POST['name'];
$email=$_POST['email'];
$phone=$_POST['phone'];
$pic=($_FILES['photo']['name']);
// Connects to your Database
mysql_connect("localhost", "username", "password") or die(mysql_error()) ;
mysql_select_db("test") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO `employees` VALUES ('$name', '$email', '$phone', '$pic')") ;
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['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.";
}
?>
I want the file to be renamed into something unique and I want that unique filename be stored on the photo field of my SQL table.

Before inserting, save the new filename into a variable, then change the name, and insert the new name into the database finally.
Or, If you want to change the name after you've done the insert, run an UPDATE query on the table, where you update the filename:
UPDATE table SET filename = 'new_filename' WHERE filename = 'old_filename"

Heres some code I just wrote which does a count on how many files are currently in the system and increments it by one thus making it a unique file_name, if every file is for example "user_1.jpg" and so on.
// Connects to your Database
mysql_connect("localhost", "username", "password") or die(mysql_error()) ;
mysql_select_db("database") or die(mysql_error()) ;
//handle the form information
$name=$_POST['name'];
$email=$_POST['email'];
$phone=$_POST['phone'];
//handle our file
$photo = $_FILES['photo']['tmp_name'];
//set where the file is ment to go
$target = "pics/";
//get the base name of the file
$filename = basename($photo);
//get the extension of the requested file
$extension = substr($filename, strrpos($filename, '.') + 1);
//count the length of items in the string
$stringLength = strlen(basename($photo));
//Get the file path of the photo minus the name of the photo
$filePath = substr($photo, 0, - $stringLength);
//set the inital name of the file
$PhotoName = "username.jpg";
//set the full path and name of the file to be uploaded
$checkThisFile = $target . $PhotoName;
//count how many files are in the folder and increment it by 1 in the while loop
$filecount = count(glob($target. "*.jpg"));
//while the file can be found in the system
while(file_exists($checkThisFile)){
//increment the count till the file is unquie
$filecount++;
//change the name of the file
$PhotoName = "username_$filecount.jpg";
//set the target and name of the file to be uploaded to keep testing it through our loop
$checkThisFile = $target . $PhotoName;
//if the file is not in the system then
if(!file_exists($checkThisFile)) {
//break the while loop
break;
} //end if condition
} //end while loop
//rename the photo file from the temporary name to the full name of the file
if($renamedFile = rename("$photo", "$checkThisFile")) {
//print a success tha our file was renamed
echo "<br/>the file was renamed";
//check if our renamed file exists
if(!empty($renamedFile)) {
//print a success that our file is there
echo "<br/>The renamed file exists!";
//move the uploaded file!
if(move_uploaded_file($renamedFile, $target)) {
//print there was an error with the transfer
echo "cannot move files!";
} //end he if condition
else {
//write to the database
$MyDatabaseQuery = "INSERT INTO employees VALUES ('','$name', '$email', '$phone', '$PhotoName')";
//run the query
#mysql_query($MyDatabaseQuery);
} //end else condition
} //end if condition
} //end if condition
The point of the code is too keep running through the loop till the file is not in the system and then rename the temporary file and upload it then store only the name of the file+extension in the database with any other records you want to store. I hope this helped.
Here is the MySQL Create TABLE Script too
CREATE TABLE IF NOT EXISTS `employees` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` text NOT NULL,
`email` text NOT NULL,
`phone` text NOT NULL,
`picture` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

You'd have to make a system for this, since the server can't decide to make a mysql-query each time you change the name of a file.
You'd have to have some kind of admin where you present all your files in a directory, and do a command which changes both the filename and the mysql-row.

Related

create unique folder of each user from input and save images inside that folder using php

I'm working on project for creating Online Exam for college Entrance. I am looking for solution to upload image and create folder using user serial id as which is as per mysql database primary increment idsave the images inside the folder.
Here is my solution where images are uploaded in already created folder called uploads. How to modify this for what I required.
<?php
session_start();
include('../connect.php');
$a = $_POST['name'];
// query
$file_name = strtolower($_FILES['file']['name']);
$file_ext = substr($file_name, strrpos($file_name, '.'));
$prefix = 'your_site_name_'.md5(time()*rand(1, 9999));
$file_name_new = $prefix.$file_ext;
$path = '../uploads/'.$file_name_new;
/* check if the file uploaded successfully */
if(#move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
//do your write to the database filename and other details
$sql = "INSERT INTO student (name,file) VALUES (:a,:h)";
$q = $db->prepare($sql);
$q->execute(array(':a'=>$a,':h'=>$file_name_new));
header("location: students.php");
}
?>
First: Be careful uploading files without correctly checking it's types;
Second: As Sean mentioned, this approach may get out of control.
--
The following example changed the steps that you tried.
First insert the user to get it's ID and then create the folder under '../uploads' with it.
This way you do not need to move the file two times (move the file to ../uploads, insert the user and then move the file again to ../uploads/userID)
<?php
...
$sql = "INSERT INTO student (name,file) VALUES (:a,:h)";
$q = $db->prepare($sql);
$q->execute(array(':a'=>$a,':h'=>$file_name_new));
// Get user id
$studentId = $db->lastInsertId();
// Create path with new userId just inserted
$path = "../uploads/$studentId/";
if(!file_exists($path)) { // maybe "&& !is_dir($path)" ?
// IMPORTANT NOTE: the second argument is the permission of the folder. 0777 is the default and may cause security flaws
mkdir($path, 0777, true);
}
// Move the uploaded file to new path with the userId
#move_uploaded_file($_FILES['file']['tmp_name'], $path.$file_name_new);
I think you need to check if the user already exists before inserting (but I don't know the details of your project)

delete an image file using php

I am building a forum with php and MySQL and I want to append current time to each image that users upload for their profile. I used time() function on each image file uploaded and it worked for the image file but I have trouble inserting the new filename into the database. I wanted to give each image a unique name to prevent override.
OK here is what I did: I stored the current time as $time and the filename in a variable, $photo and I tried to insert that variable’s value using $photo .= $time into the database so it has the filename as I did with each uploaded image. However the original filename is inserted into the database in every attempt.
Any workarounds?
$image = $_FILES['photo']['name'];
$time = time();
$image .= $time;
delete the existing photo
delete(image_dir/$row['current_photo.jpg']);
//does not work, but i want something like that
if(move_uploaded_file($_FILES['photo']['tmp_name'], 'image_dir/$image') {
$query = "INSERT INTO profile (user_id, profile_photo) VALUES($id, $image)";
mysqli_query($dbc, $query);
if(mysqli_affected_rows($dbc) == 1) {
echo "added to the database!";
}else {
echo "failed to add photo to the database";
}
}else {
echo "failed to upload photo";
}
how can i give the uploaded image unique the name since the original image name gets inserted in the database in every try i make?
i know the code looks funny :). just want to show the logic.
If you need a unique id, you can use the uniqid function
$name=uniqid();
you may need to use
$filename=uniqid();

Image rename and value insert into my mysql

What I would like is for an uploaded image to have a random name that would would be inserted into my data base so I can call it on user profiles. I have the php code that will upload files to the local disc but no values are being submitted into the mysql row for the user. Also, all the images are being named image.jpg and overwriting each other. Any help would be great. Thanks!
<?php
//This is the directory where images will be saved
$target = "images/uploaded/user_images/";
$target = $target . basename( $_FILES['photo']['name']);
//This gets all the other information from the form
$photo=($_FILES['photo']['name']);
// Connects to your Database
mysql_connect("server", "root", "pass") or die(mysql_error()) ;
mysql_select_db("db") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO `users` VALUES ('$photo')") ;
//Writes the information to the database
mysql_query("INSERT INTO photo ('name')
VALUES ('$photo')") ;
//Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['photo']['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.";
}
?>
For I start I would like to ask you how do you know which user has which picture? Becouse you just store images in table without any user ID. I suggest that you redesign your database.
Then I will use this for an image name instead of completely random string.
$_FILES['photo']['name'] = "image_" . round(microtime(true) * 1000) . ".jpg";
Or get the number of images in database and increase it by one. That way you cannot end up with multiple images with same name.

updating image in upload folder and image path in mysql

I am trying to update images in my upload folder and mysql database the file uploads giving the file name 0.jpg instead of the normal persons id 13.jpg and does not update in mysql database, here is my snippet below what am i doing wrong?
$pic = mysql_real_escape_string(htmlspecialchars($_FILES['photo']['name']));
//This gets all the other information from the form
$pic=($_FILES['photo']['name']);
$file = $_FILES['photo']['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['photo']['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", "") or die(mysql_error()) ;
mysql_select_db("office") or die(mysql_error()) ;
//Writes the information to the
$target = "images/" .mysql_insert_id() . $ext;
$staff_id = mysql_insert_id();
$new_file_name = mysql_insert_id() . $ext;
//I removed ,photo='$target' to display only id as picture name
mysql_query("UPDATE development SET photo='$new_file_name' WHERE staff_id=$staff_id");
//Writes the file to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename( $_FILES['photo']['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.";
}
?>
Instead of this
$staff_id = mysql_insert_id();
$new_file_name = mysql_insert_id() . $ext;
//I removed ,photo='$target' to display only id as picture name
mysql_query("UPDATE development SET photo='$new_file_name' WHERE staff_id=$staff_id");
do something like thus
mysql_query ("INSERT INTO development (photo) VALUES ( '".$new_file_name."' )");
//first insert
$staff_id = mysql_insert_id() ;
// then get the id of the record you've just inserted
Firstly, you're using the mysql_* functions, which are deprecated as of 5.5.
Secondly, you need to look at the manual page for mysql_insert_id. Quote:
Retrieves the ID generated for an AUTO_INCREMENT column by the
previous query (usually INSERT).
This means that you can only call mysql_insert_id() AFTER you've inserted data into or updated your users/persons table. In your case, however, it seems as though you already have the ID of the person stored in the variable $staff_id, so you probably don't even need to use mysql_insert_id. Would this not work instead?
$target = "images/" . $staff_id . $ext;

PHP upload file

i have been stressing for an hour at this stupid script i am trying to make it uploa an MP3
file to a folder it creates.
It is putting the information into mysql and making the folder bu when i ftp the folder is empty with no music file in there
here is the script thanks so so so much!
BTW $name is the POSTED name and full name is the posted name + ".mp3"
// BEGIN ENTERING INFORMATION TO MYSQL TABLE
$sql = mysql_query("INSERT INTO mattyc (name, date, length, size, link)
VALUES('$name','$date','$length','$size','$link')"
) or die (mysql_error());
mkdir("../music/albums/donjuma/$name", 0777);
$song = ("../music/albums/donjuma/$name/$fullname");
if (file_exists($song)) {
unlink($song);
}
$newname = "$fullname";
$newfile = rename(($_FILES['song']['tmp_name']),($newname));
$place_file = move_uploaded_file( $newfile, "../music/albums/donjuma/$name/"."$newname");
$success_msg = "<font color=\"#009900\">Your SONG has been updated, it may take a few minutes for the changes to show... please be patient.</font>";
echo $success_msg;
}
}
}
$newfile =
rename(($_FILES['song']['tmp_name']),($newname));
$place_file = move_uploaded_file(
$newfile,
"../music/albums/donjuma/$name/"."$newname");
rename() returns a bool, not a filename. So your move_uploaded_file() call is going to fail. Any file renaming should be part of your move_uploaded_file() call, don't try and do anything with your temporary file apart from move it.

Categories