I have a form where the user enters data and uploads an image. This image will be checked if there is an image that is exactly the same using md5 hashing. Each image that is uploaded will have its own md5 hash code. If a user decides to upload an image that is exactly like the one on the server, then that image will not be moved. Instead, when creating the entry, the image will inherit the name of that file from the different entry with the same hash code. But I am running into several problems with my current code. For one, when the user uploads an image for the first time, there is no hash code. Another problem I am experiencing with my code is that even when I upload an image with the same hash code, the name of the image is changing to a uniqid. It is executing the else block and not the if block.
Here's my code:
PHP
if (isset($_POST["pageNum"], $_FILES["image"], $_POST["subtitle"], $_POST["text"]))
{
$page = $_POST["pageNum"];
$url = $_SESSION["articleUrl"];
$subtitle = filter_data($_POST["subtitle"]);
$text = filter_data($_POST["text"]);
$name = $_FILES["image"]["name"];
$tempName = $_FILES["image"]["tmp_name"];
$target_file = $_SERVER['DOCUMENT_ROOT'] . "/stories/media/images/$name";
$hash = md5_file($target_file);
$resultHash = $db->query("SELECT * COUNT(*) FROM `Stories` WHERE hash = '$hash' LIMIT 1");
if ($resultHash->num_rows > 0)
{
$row = $resultHash->fetch_array();
$name = $row["image"];
}
else
{
if (#getimagesize($target_file) == true)
{
$ext = pathinfo($name, PATHINFO_EXTENSION);
$name = basename($name, "." . $ext);
$name = $name . uniqid() . "." . $ext;
$target_file = $_SERVER['DOCUMENT_ROOT'] . "/stories/media/images/$name";
}
move_uploaded_file($tempName, $target_file);
}
$result = $db->query("SELECT * FROM Stories WHERE page = '$page' AND url = '$url'");
if ($result->num_rows == 0)
{
$db->query("INSERT INTO `Stories` (`image`, `text`, `url`, `subtitle`, `page`, `hash`) VALUES ('$name', '$text', '$url', '$subtitle', '$page', '$hash')");
}
else
{
$db->query("UPDATE Stories SET image = '$name', text = '$text', url = '$url', subtitle = '$subtitle', page = '$page', hash = '$hash' WHERE url = '$url' AND page = '$page'");
}
}
The lines below are problematic because you will only get a hash if the $target_file already exists. If there is no file by that name, then there is nothing to hash and you can't get a hash to compare against the DB value.
$target_file = $_SERVER['DOCUMENT_ROOT'] . "/stories/media/images/$name";
$hash = md5_file($target_file);
The first line is useless; remove it. You should be calculating the hash of the newly uploaded file instead because that's what needs to be compared to the hashes stored in the DB:
$hash = md5_file($tempName);
Later, you also need to change your getimagesize check to work with the newly uploaded file because this is the file that needs to be processed (we get to this check if this is a new, unique file):
if (getimagesize($tempName) == true)
Related
I've seen questions similar to this but no one seems to have the problem I do.
I've set up a process to check to see if the filename already exists in a MySQL table, and if it does, it puts a timestamp between the filename and the extension (E.G. Test.PDF becomes Test-19:25:36 if it's a duplicate), thus negating any database conflicts.
My issue is that the while the database is updated correctly, the duplicate file isn't uploaded with the timestamp in the name. Instead, it uses the duplicate name and just overwrites the original and creates a ghost "filename" listing in the database.
I've seen you can use move_uploaded_file to rename files in the servers memory before they're uploaded, but I've tried multiple ways and can't get it to rename the file in memory BEFORE attempting to write it to the "/uploads" folder. Here's the upload code:
<?php
include_once 'dbconnect.php';
//check if form is submitted
if (isset($_POST['submit'])) {
// START OF PRE-EXISTING FILE CHECK
$filename = $_FILES['file1']['name'];
$dupeCheck = "SELECT * FROM tbl_files WHERE filename = '$filename'";
if ($output = mysqli_query($con, $dupeCheck)) {
if (mysqli_num_rows($output) > 0) {
$fileArray = pathinfo($filename);
$timeStamp = "-" . date("H:i:s");
$filename = $fileArray['filename'] . $timeStamp . "." . $fileArray['extension'];
}
}
// END OF PRE-EXISTING FILE CHECK
if($filename != '')
{
$trueCheck = true;
if ($trueCheck == true) {
$sql = 'select max(id) as id from tbl_files';
$result = mysqli_query($con, $sql);
//set target directory
$path = 'uploads/';
$created = #date('Y-m-d H-i-s');
$moveTargetVar = "uploads/" . $filename;
move_uploaded_file($_FILES['file1']['tmp_name'], $moveTargetVar);
// insert file details into database
$sql = "INSERT INTO tbl_files(filename, created) VALUES('$filename', '$created')";
mysqli_query($con, $sql);
header("Location: index.php?st=success");
}
else
{
header("Location: index.php?st=error");
}
}
else
header("Location: index.php");
}
?>
Any advice on how to rename a file before it's written to the uploads folder?
I'd suggest not using : to separate your time stamp, because that will cause issue with file name restrictions. Try doing something like:
$timeStamp = "-" . date("H-i-s");
Solved by replacing move_uploaded_file($_FILES['file1']['tmp_name'], $moveTargetVar); with move_uploaded_file($_FILES['file1']['tmp_name'],$path . $filename);
Deprecated $moveTargetVar = "uploads/" . $filename;
thank you in advance for your help, i need to make a system were i can upload and update a file into my database record. To do so i made this code but for some reason i cant seem to see what i have done wrong i can update the "status and so on" but the file is not uploaded into my desired directory and the record is missing in my database too, so all the rest works just fine, except the file itself, does not get updated. Here is my code, again thanks in advance!
<?php
if(isset($_POST['submit_btn']))
{
if(move_uploaded_file($_FILES['Filename']['tmp_name'], $target)) {
require 'modules/conn.php';
$target = "../account-files/";
$target = $target . basename( $_FILES['Filename']['name']);
}
$id = $_REQUEST['id'];
$status = $_REQUEST['status'];
$counts = $_REQUEST['counts'];
$Filename=basename( $_FILES['Filename']['name']);
$query = mysqli_query($conn,"UPDATE files SET id ='".$_POST['id']."', status ='".$_POST['status']."', counts ='".$_POST['counts']."', Filename ='".$_POST['Filename']."' WHERE id = '".$id."'") or die(mysqli_error($conn));
header("location: ../my-account/");
}
?>
Everything else gets updated in my database, but as i said, the file and the record of the file name does not, also its not uploaded into my directory. Please help me, an example would be very much appreciated.
Updated code i can get the records into the database but still no upload into the directory.
$target = "../account-files/";
$target = $target . basename( $_FILES['Filename']['name']);
if(isset($_POST['submit_btn']))
{
move_uploaded_file($_FILES['Filename']['tmp_name'], $target);
require 'modules/conn.php';
$id = $_REQUEST['id'];
$status = $_REQUEST['status'];
$counts = $_REQUEST['counts'];
$Filename=basename( $_FILES['Filename']['name']);
$query = mysqli_query($conn,"UPDATE files SET id = $id, status = '$status', counts = $counts , Filename = '$Filename' WHERE id = '$id'") or die(mysqli_error($conn));
header("location: ../my-account/");
}
This last solution is correct i hope i can contribute also to other members, see solution credits bellow at the correct reply to my post, that guy rocks! Thumbs up so what was the error? Simple, the path i had was wrong...
this one is wrong:
$target = "../account-files/";
This is correct and fixes all
$target = "account-files/";
Do you really have the POST['Filename']? I think you should put the variables in you query instead of .POST
Try the code below:
if(isset($_POST['submit_btn']))
{
$target_dir = "../account-files/";
$target_file = $target_dir . basename( $_FILES['Filename']['name']);
move_uploaded_file($_FILES['Filename']['tmp_name'], $target_file);
require 'modules/conn.php';
$id = $_REQUEST['id'];
$status = $_REQUEST['status'];
$counts = $_REQUEST['counts'];
$Filename=basename( $_FILES['Filename']['name']);
$query = mysqli_query($conn,"UPDATE files SET id = $id, status =
'$status', counts = $counts , Filename = '$Filename' WHERE id =
'".$id."'") or die(mysqli_error($conn));
header("location: ../my-account/");
}
And also please make sure that you have the enctype="multipart/form-data" on your form tag.
You make some mistakes:
how you can upload the file first and then determine the target
why are you updating id? while id is its primary key
i
if(isset($_POST['submit_btn'])){
$target = "../account-files/";
$fname = $_FILES['filename']['name'];
if(!empty($target) && !empty($fname)){
move_uploaded_file($_FILES['filename']['tmp_name'], $target.$fname);
}
}
So I have an admin panel built, I am wanting to be able to upload images, change the name of the image file to a number ID which is generated by how many rows there are already in the database. Then have them displayed in a gallery for visitors. I have looked around the internet for a few days now, trying different scripts, mixing and matching, but nothing seems to work. This is PHP btw. I beleive the issue is the move_uploaded_file() function. If anyone could think of a better way or find an error in my code, that would be fantastic. The website is for a client so it would be even more appreciated for promptly replies. Thanks guys
require_once("../php/connect.php");
function GetImageExtension($imagetype){
if(empty($imagetype)) return false;
switch($imagetype){
case 'image/png': return '.png';
default: return false;
}
}
if (!empty($_FILES['fileToUpload']['name'])){
$file_name = $_FILES['fileToUpload']['name'];
$temp_name = $_FILES['fileToUpload']['tmp_name'];
$imgtype = $_FILES['fileToUpload']['type'];
$ext = GetImageExtension($imgtype);
$query1 = "SELECT COUNT(*) FROM gal";
$count = mysqli_query($dbc, $query1);
$imagename = $count + 0;
$newfilename = "$imagename" . ".png";
//Debug
echo "hello <br>";
echo "$newfilename";
//End Debug
$folder = "/uploads/";
if(move_uploaded_file($_FILES['image']['tmp_name'], "$folder" . $_FILES['image']['$newfilename'])){
$query2 = "INSERT INTO `nocas_19164639_admin`.`gal` (`id`, `name`, `active`) VALUES (NULL, '$newfilename', '1')";
mysqli_query($dbc, $query2);
}else{
exit("Error while uploading file...");
}
}
Can i ask why you want to rename the file to a number relating to the row it's on?
Your making a simple task very complex.
You shouldn't store the images in your database, you should upload them to a directory within your site and store the corresponding name in the db.
I don't understand the whole reason for changing the name to a number though, it's just making a mess of everything.
you should just do something like this.
create a directory path in your config file..
defined("UPLOAD_DIRECTORY") ? null : define("UPLOAD_DIRECTORY", __DIR__ . DS . "uploads");
I have created a function for mysqli query just so i dont have to type it out all the time.
function query($sql) {
global $connection;
return mysqli_query($connection, $sql);
}
I then have a confirm query which checks for an error on the query.
function confirm($result) {
global $connection;
if(!$result) {
die("QUERY FAILED" . mysqli_error($connection));
}
}
then you can just simply do something like this to insert into db.
$product_image = escape_string($_FILES['file']['name']);
$image_temp_location = $_FILES['file']['tmp_name'];
move_uploaded_file($image_temp_location, UPLOAD_DIRECTORY . DS . $product_image);
$query = query("INSERT INTO products(product_image) VALUES( '{$product_image}')");
I want to allow users to upload images without conflicting problems that may be caused by multiple users uploading images that potentially have the same image name. I am stumped on how to execute this and I have no idea where to start..
Here is my code:
if(isset($_POST['submitimage'])){
move_uploaded_file($_FILES['file']['tmp_name'],"pictures/".$_FILES['file']['name']);
$con = mysqli_connect("localhost","root","","database");
$q = mysqli_query($con,"UPDATE users SET image = '".$_FILES['file']['name']."' WHERE user_id = '".$_SESSION['user']."'");
header("Location: index.php");
}
?>
Any help would be amazing. Thank you!
My solution is to generate a random string for each uploaded file, i.e.:
<?php
if(!empty($_POST['submitimage'])){
//get file extension.
$ext = pathinfo($_FILES['file']['name'])['extension'];
//generate the new random string for filename and append extension.
$nFn = generateRandomString().".$ext";
move_uploaded_file($_FILES['file']['tmp_name'],"pictures/".$nFn);
$con = mysqli_connect("localhost","root","","database");
$q = mysqli_query($con,"UPDATE users SET image = '{$nFn}' WHERE user_id = '{$_SESSION['user']}'");
header("Location: index.php");
}
function generateRandomString($length = 10) {
return substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, $length);
}
?>
PHP has a build in function to generate unique files on your server. This function is known as tempnam(). If you read the comments on that website carefully though, there is a small chance you'll get unwanted behaviour from that function if to many processes call it at the same time. So a modification to this function would be as follows:
<?php
function tempnam_sfx($path, $suffix){
do {
$file = $path."/".mt_rand().$suffix;
$fp = #fopen($file, 'x');
}
while(!$fp);
fclose($fp);
return $file;
}
?>
Because the file is kept open while it's being created, it can't be accessed by another process and therefor it's impossible to ever create 2 files with the same name simply because a couple of your website visitors happened to upload pictures at the exact same moment. So to implement this in your own code:
<?php
function tempnam_sfx($path, $suffix){
do {
$file = $path."/".mt_rand().$suffix;
$fp = #fopen($file, 'x');
}
while(!$fp);
fclose($fp);
return $file;
}
$uploaddir = 'pictures'; // Upload directory
$file = $_FILES['file']['name']; // Original file
$ext = pathinfo($path, PATHINFO_EXTENSION); // Get file extension
$uploadfile = tempnam_sfx($uploaddir, $ext);
move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile);
$con = mysqli_connect("localhost","root","","database");
$q = mysqli_query($con,"UPDATE users SET image = '".basename($uploadfile)."' WHERE user_id = '{$_SESSION['user']}'");
header("Location: index.php");
?>
One way you could do this, is by generating a few random numbers (and possibly attaching them to current date in number format) and give the image the number sequence.
if(isset($_POST['submitimage'])){
//generate 3 sequences of random numbers,you could do more or less if you wish
$randomNumber=rand().rand().rand();
move_uploaded_file($_FILES['file']['tmp_name'],"pictures/".$randomNumber."jpg");
$con = mysqli_connect("localhost","root","","database");
$q = mysqli_query($con,"UPDATE users SET image = '".$randomNumber.".jpg' WHERE user_id = '".$_SESSION['user']."'");
header("Location: index.php");
}
?>
Note : you could also look into generating random strings if numbers are not your thing.
I am trying to develop a user page for a forum and I'm kinda struggling with the image upload.
The problem is that I would like to limit the user to only be able to upload one single image, but be able to change it anytime. so basically, I would like to either overwrite the existing file either delete the old picture and add a new one instead.
At this point I have a piece of code that adds a timestamp at the end of the file (which I don't really need actually).
CODE:
if(isset($_POST['upload']))
{
$extension=strstr($_FILES['uploadedfile']['name'], ".");
$filename = "_/userfiles/userpics/".basename($_FILES['uploadedfile']['name'],
$extension);
$target = "_/userfiles/userpics/".basename($_FILES['uploadedfile']['name']);
$valid = true;
if(file_exists($target))
{
$filename = $filename . time();
$target = $filename . $extension;
}
if($valid)
{
// move the file into the folder of our choise
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target);
$img_sql = "INSERT INTO sp_userimage (imageid, path, id) value ('', '".$target."', '".$_SESSION['userid']."')";
$img_result = mysql_query($img_sql);
echo "upload sucessfull";
}
Make use of unlink() in PHP Manual.
if(file_exists($target))
{
unlink($target); // deletes file
//$filename = $filename . time();
//$target = $filename . $extension;
}
I think this might be a bit better suited for you. You might have to edit it a tad.
if($valid)
{
// Check if user has a file.
$img_check = mysql_query("SELECT * FROM sp_userimage WHERE id = " . (int) $_SESION['user_id']);
if( mysql_num_rows($img_check) > 0 ){
$row = mysql_fetch_object($img_check);
// Delete the file.
unlink($row->path);
}
// move the file into the folder of our choise
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target);
$img_sql = "INSERT INTO sp_userimage (imageid, path, id) value ('', '".$target."', '".$_SESSION['userid']."')";
$img_result = mysql_query($img_sql);
echo "upload sucessfull";
}
It might be easier to normalize the image type (e.g. only jpegs) and then name the file as the userid. For example:
$target = 'userpics' . DIRECTORY_SEPARATOR . $_SESSION['userid'];
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target);
This will simply overwrite the old picture with the new one. Given that this type of filename is deterministic, you also don't need to store the filename in the database.
Use unlink() function
read more here PHP unlink
okay ,if u want to delete the file for that particular user only.
then store the filename vs user in some MapTable in db.
mysql_query("CREATE TABLE t_usr_file_map(
usr_id INT NOT NULL ,
file_name VARCHAR(100),
)")
or die(mysql_error());
and at the time of reupload , fetch the filename from the table for that user , unlink it and reupload the fresh one again.
OR,
or u can use PHP file_rename function at the time of upload. rename filename to the userid
rename ( string $oldname , string $newname [, resource $context ] )
and u can always do unlink based on user-id
Its very simple by unlink()
as:
unlink(dirname(__FILE__) . "/../../public_files/" . $filename);
if (file_exists($path))
{
$filename= rand(1,99).$filename;
unlink($oldfile);
}
move_uploaded_file($_FILES['file']['tmp_name'],$filename);