Update file in database and upload file - php

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);
}
}

Related

Using move_uploaded_file To Rename File BEFORE Being Placed In uploads/ Folder

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;

Script Not Reading String

I have a php script that uploads a profile picture to the server and then edits a field in the DB.
At the top of the script, I've added a line of code that will create a new folder in a directory, that's labeled by the user's id. The ID is echoed with $id. This works for the folder, but when I set the upload path to something like ../img/users/$id, it uploads to ..img/users instead.
CODE:
<?php
require '../login_check.php';
include_once 'db_connect.php';
$dir = "../img/users/$id";
if( is_dir($dir) === false )
{
mkdir($dir);
}
fclose($file);
$dir = "./users/$result[id]";
if( is_dir($dir) === false );
$path_to_image_directory = "../img/users/$id";
if(isset($_FILES['imgupload']))
{
$id = $_SESSION['id'];
if ($_FILES["imgupload"]["size"] > 500000)
{
header('Location: ../profile');
}
if(preg_match('/[.](jpg)|(JPG)|(gif)|(GIF)|(PNG)|(png)$/',
$_FILES['imgupload']['name']))
{
$source = $_FILES['imgupload']['tmp_name'];
$randString = md5(time());
$filename = $_FILES['imgupload']['name'];
$splitName = explode(".", $filename);
$fileExt = end($splitName);
$newfilename = strtolower($randString.'.'.$fileExt);
$target = $path_to_image_directory . $newfilename;
move_uploaded_file($source, $target);
$updatestmt = $conn->prepare("UPDATE members SET profilepic= ? WHERE id = ?");
$updatestmt->bind_param("si", $newfilename, $id);
$updatestmt->execute();
header('Location: ../profile');
}
else
{
header('Location: ../profile');
}
}
?>
Can anyone tell me what I did wrong and how to fix this?
You are using $id variable before assigning $_SESSION['id'] value to it.
First you have to assign the value to $id
$id = $_SESSION['id'];
Then use this $id to setting directory path variable.
$path_to_image_directory = "../img/users/$id";
Make sure your $_SESSION['id'] is not empty/null
Move $id = $_SESSION['id']; to below include_once 'db_connect.php';

Users upload images to website and then is displayed in gallary

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}')");

Delete image file with PHP

Below is the code that should delete the image file.
I have row that contains (id, name, pic), I can delete this row from database,
but did not delete the image from file.
if(isset($_GET["delete"])){
$pic=$_GET["pic"];
$qry="delete from section where id=".$_GET["delete"];
$de = mysqli_query($conn,$qry);
$filetmp = $_FILES["pic"]["tmp_name"];
// $filename = $_FILES["pic"]["name"];
$name = $_POST["name"];
$qr ="SELECT id FROM section ORDER BY id ASC";
$res = mysqli_query($conn,$qr);
$path = "uploads/$id.jpg";
//move_uploaded_file($filetmp,$path);
$fpath = "/images_upload/$path";
unlink("$fpath");
}
I appreciate any help.
$path = "uploads/$id.jpg";
you must assign a value of $id

Preventing image duplicates on server

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)

Categories