Delete image file with PHP - 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

Related

file upload while edit row in database

I am working on simple CRUD and I am facing difficulty with the "Edit section"
Long story short:
I have MySQL base with records, I am printing them on the front page, I have added two buttons for "Add new record" via <form and "Edit record" where I can edit any record.
The problem: in the "Add" section I can upload files during adding a new record.
here is the code for uploading a file in insert.php
// Include the database configuration file
include 'db.php';
$statusMsg = '';
// File upload path
$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
}
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif','pdf','doc','xlsx');
if(in_array($fileType, $allowTypes)){
}
// Upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
}
Via this one, I am uploading the file on the server and making the record into the database as the filename.
I would like to use the same way while editing records in order if the user wants to upload a file later, but when I use the same code I am getting
Warning: Undefined array key "file" in C:\xampp\htdocs\crud\edit.php on line 12
Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\crud\edit.php on line 12
Here is my edit.php code:
<?php
// include database connection file
include_once("config.php");
// Check if form is submitted for user update, then redirect to homepage after update
if(isset($_POST['update']))
{
$id = $_POST['id'];
$toolnr=$_POST['toolnr'];
$status=$_POST['status'];
$toolname=$_POST['toolname'];
$serial=$_POST['serial'];
$usedat=$_POST['usedat'];
$owner=$_POST['owner'];
$calibrated=$_POST['calibrated'];
$nextcalibration=$_POST['nextcalibration'];
$vendors=$_POST['vendors'];
// update tools data
$result = mysqli_query($mysqli, "UPDATE tools SET toolnr='$toolnr',status='$status',toolname='$toolname',serial='$serial',usedat='$usedat',owner='$owner',calibrated='$calibrated',nextcalibration='$nextcalibration', vendors='$vendors', file_name = '$fileName' WHERE id=$id");
// Redirect to homepage to display updated tools in list
header("Location: index.php");
}
?>
<?php
// Display selected tool data based on id
// Getting id from url
$id = $_GET['id'];
// Fetech tool data based on id
$result = mysqli_query($mysqli, "SELECT * FROM tools WHERE id=$id");
while($user_data = mysqli_fetch_array($result))
{
$toolnr = $user_data['toolnr'];
$status = $user_data['status'];
$toolname = $user_data['toolname'];
$serial = $user_data['serial'];
$usedat = $user_data['usedat'];
$owner = $user_data['owner'];
$calibrated = $user_data['calibrated'];
$nextcalibration = $user_data['nextcalibration'];
$vendors = $user_data['vendors'];
}
?>
and here is the HTML pcs:
<tr>
<td>File upload:</td>
<td><input type="file" name="file" ></td>
</tr>
---- update ------
Here is the full edit.php code:
<?php
// include database connection file
include_once("config.php");
// Include the database configuration file
include 'db.php';
$statusMsg = '';
// File upload path
$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
}
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif','pdf','doc','xlsx');
if(in_array($fileType, $allowTypes)){
}
// Upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
}
// Check if form is submitted for tool update, then redirect to homepage after update
if(isset($_POST['update']))
{
$id = $_POST['id'];
$toolnr=$_POST['toolnr'];
$status=$_POST['status'];
$toolname=$_POST['toolname'];
$serial=$_POST['serial'];
$usedat=$_POST['usedat'];
$owner=$_POST['owner'];
$calibrated=$_POST['calibrated'];
$nextcalibration=$_POST['nextcalibration'];
$vendors=$_POST['vendors'];
// update tool data
$result = mysqli_query($mysqli, "UPDATE tools SET toolnr='$toolnr',status='$status',toolname='$toolname',serial='$serial',usedat='$usedat',owner='$owner',calibrated='$calibrated',nextcalibration='$nextcalibration', vendors='$vendors',file_name = '$fileName' WHERE id=$id");
// Redirect to homepage to display updated tool in list
header("Location: index.php");
}
?>
<?php
// Display selected tool data based on id
// Getting id from url
$id = $_GET['id'];
// Fetech tool data based on id
$result = mysqli_query($mysqli, "SELECT * FROM tools WHERE id=$id");
while($user_data = mysqli_fetch_array($result))
{
$toolnr = $user_data['toolnr'];
$status = $user_data['status'];
$toolname = $user_data['toolname'];
$serial = $user_data['serial'];
$usedat = $user_data['usedat'];
$owner = $user_data['owner'];
$calibrated = $user_data['calibrated'];
$nextcalibration = $user_data['nextcalibration'];
$vendors = $user_data['vendors'];
}
?>
Maybe I am working in the wrong way somehow...

update image if uploaded else use previosly stored image

<?php
include '../db_conx.php';
$id = $_POST['id'];
$file = addslashes(file_get_contents($_FILES["college_image"]["tmp_name"]));
$insert_data1 = mysqli_real_escape_string($db_conx,$_POST['college_overview']);
$insert_data2 = mysqli_real_escape_string($db_conx,$_POST['college_courses']);
$insert_data3 = mysqli_real_escape_string($db_conx,$_POST['college_facilities']);
$test = "UPDATE college_details SET college_overview='$insert_data1', college_courses='$insert_data2', college_facilities='$insert_data3',college_image = '$file' where id = '$id' ";
if (mysqli_query($db_conx,$test)){
header("Location:college.php?success");
}
{
echo("Error description: " . mysqli_error($db_conx));
}
?>
Whenever i try to update without uploading a new image the previously stored image gets removed. How do i keep the old image when no file is uploaded
You can check whether the upload file is empty or not using simple if else statement and reformat your sql statement accordingly:
if(!file_exists($_FILES["college_image"]["tmp_name"]) ||
!is_uploaded_file($_FILES["college_image"]["tmp_name"])) {
$test = "UPDATE college_details SET college_overview='$insert_data1',
college_courses='$insert_data2', college_facilities='$insert_data3',
where id = $id ";
//No file is uploaded, we skip updating the image.
}else{
//Upload File is there, we update the image file in the database
$test = "UPDATE college_details SET college_overview='$insert_data1',
college_courses='$insert_data2', college_facilities='$insert_data3',
college_image = '$file' where id = $id ";
}
Your code is vulnerable to sql injection. Use prepared statement to update your data.

Update file in database and upload file

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

delete image from file server in php

I have row that contains (id, name, pic), I can delete this row from the database, but cannot delete the image from the file server.
Below code should delete the image file:
if(isset($_GET["delete"])){
$pi=$_GET["delete"];
$qry="delete from item where id=".$_GET["delete"];
$de = mysqli_query($conn,$qry);
$filetmp = $_FILES["pic"]["tmp_name"];
// $filename = $_FILES["pic"]["name"];
$qr ="SELECT id FROM item where id='$pi'";
$res = mysqli_query($conn,$qr);
while($row = mysqli_fetch_array($res)){
$id = $row["id"];
}
$path = "uploads/$id.jpg";
//move_uploaded_file($filetmp,$path);
$fpath = "images_upload/Uitem/$path";
unlink($fpath); // delete file
}
you'll have to use the path on your server to delete the image, not the image url.
Like
unlink('/var/www/test/'.$fpath);

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