loop to check and remove image if not exist - php

I'm trying to make a loop which checks if an image with filename from database exists, if not to unlink all images because I have many duplicates in folder but folder is 50gb. I can't check each one.
So here's what I've tried
$id = $_GET['id'];
$sql = "SELECT thumbnail FROM files WHERE id='$id'";
$query = $mysqli->query($sql);
$row = $query->fetch_assoc();
$thumb = $row['thumbnail'];
$records = "../upload/images/";
foreach ($records as $record) {
if (file_exists('../upload/images/'.$thumb)) {}
else {
#unlink('../upload/images/'.$thumb);
}
}
Update
$sql = "SELECT thumbnail FROM filesWHERE id='$id'";
$query = $mysqli->query($sql);
$row = $query->fetchAll();
foreach($sql as $search_result) {
if(file_exists($search_result['thumbnail'])) {
$img_source = ('../upload/images/'.$search_result['thumbnail']);
} else {
#unlink('../upload/images/'.$search_result);
}
}

That's the logic I've understood. Checking if there are files in the folder that aren't present in database, and if so, delete it.
$directory = "../upload/images/";
$images = glob($directory . "*.jpg");
foreach($images as $image)
{
$sql = "SELECT thumbnail FROM files WHERE thumbnail =?";
$stmt = $mysqli->prepare($sql);
if($stmt) {
$stmt->bind_param('s', $image);
$stmt->bind_result($result);
$stmt->execute();
$stmt->fetch();
if(!$result) {
if(unlink($image)) {
echo "Image deleted $image <br>\n";
}
}
} else {
echo "Unable to prepare SQL";
}
}

Related

How to delete image from folder when delete button is clicked [duplicate]

I have admin panel where I show rows from database with ability to delete them.
Here is how I delete them delete.php
UPDATE
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
$id = $_GET['id'];
$name = "SELECT name FROM images WHERE id=$id";
$name=mysql_fetch_assoc($name);
$name=$name['name'];
if ($stmt = $con->prepare("DELETE FROM images WHERE id = ? LIMIT 1"))
{
$stmt->bind_param("i",$id);
$stmt->execute();
unlink("../upload/" . $name);
$stmt->close();
}
else
{
echo "ERROR: could not prepare SQL statement.";
}
$con->close();
header("Location: images_delete.php");
}
else
{
header("Location: images_delete.php");
}
Then I must open 'Upload' form to delete the image which I deleted from mysql. How can I make when I delete that image from mysql also to delete from folder?
In mysql I store path and name of the image.
UPDATE: Here is final version of the file which is working-> delete file from folder and record in DB
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
$id = $_GET['id'];
$name = "SELECT * FROM images WHERE id=$id" or die(mysqli_error($con));
$res = mysqli_query($con, $name);
$row = mysqli_fetch_assoc($res);
$name1 = $row['name'];
//print_r($name1);
if ($stmt = $con->prepare("DELETE FROM images WHERE id = ? LIMIT 1"))
{
$stmt->bind_param("i",$id);
$folder = 'C:\wamp\www\upload';
chown($folder,465);
//var_dump($name1);
unlink($_SERVER['DOCUMENT_ROOT'] . "/upload/$name1");
$stmt->execute();
$stmt->close();
}
else
{
echo "ERROR: could not prepare SQL statement.";
}
$con->close();
use unlink($your_image_path) to delete image

Unable to store pic link into database

I am trying to upload my pic into folder and file link store into database although file store in folder but unfortunately doesn't store link in database. Please see where I am doing mistake.
<?php
include('dbconnection.php');
if(count($_FILES["file"]["name"]) > 0)
{
sleep(3);
for($count=0; $count<count($_FILES["file"]["name"]); $count++)
{
$file_name = $_FILES["file"]["name"][$count];
$tmp_name = $_FILES["file"]['tmp_name'][$count];
$file_array = explode(".", $file_name);
$file_extension = end($file_array);
if(file_already_uploaded($file_name, $connect))
{
$file_name = $file_array[0] . '-'. rand() . '.' . $file_extension;
}
$location = 'files/' . $file_name;
if(move_uploaded_file($tmp_name, $location))
{
$stmt= $connect->prepare("INSERT INTO tbl_image (image_name) VALUES (:image_name)");
$stmt->bindParam(':image_name', $file_name);
$stmt->execute();
}
}
}
function file_already_uploaded($file_name, $connect)
{
$statement = $connect->prepare("SELECT image_name FROM tbl_image WHERE image_name = '".$file_name."'");
$statement->execute();
$number_of_rows = $statement->rowCount();
if($number_of_rows > 0)
{
return true;
}
else
{
return false;
}
}
?>
store the image name as location with file name:
$location = 'files/' . $file_name;
if(move_uploaded_file($tmp_name, $location))
{
$stmt= $connect->prepare("INSERT INTO tbl_image (image_name) VALUES (:image_name)");
$stmt->bindParam(':image_name', $location.'/'.$file_name);
$stmt->execute();
}

Use a variable from one IF - Statement into the other IF - Statement in PHP

I have a variable $target inside an IF - Statement in my login.php. I created the folders and sub-folders based on this variable. Now i want to move the uploaded file to this location. How can I do that?
here is the code
$upload = "E:/demons";
if(isset($_POST['userid'], $_POST['pid']))
{
$userid = trim($_POST["userid"]);
$pid = trim($_POST["pid"]);
$sql = "SELECT * FROM template WHERE uname = '$userid' and pword = '$pid'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
echo "公司".'<br/>';
echo $row['client'].'<br/>'.'<br/>';
echo "第".'<br/>';
echo '<a href="upload.html"/>'.$row['day1'].'</a>'.'<br/>';
$target = $upload.'/'.$row['week'].'/'.$row['day1'].'/'.$row['client'].'/'.$row['brand'].'/'.$row['sc'].'/';
$imagename = $row['week'].'.'.$row['day1'].'.'.$row['client'].'.'.$row['brand'].'.'.$row['sc'].'.'.'jpg';
if(!file_exists($target))
{
mkdir($target,null,true);
}
}
else if(isset($_FILES['image']))
{
$image = basename($_FILES["image"]["name"]);
echo $image;
//$target4 = $upload.'/'.$row['week'].'/'.$row['day1'].'/'.$row['client'].'/'.$row['brand'].'/'.$row['sc'].'/';
move_uploaded_file($_FILES['image']['tmp_name'], $target);
}
else
{
echo "asdfg";
}
Userid and Pid comes from login.html and Image value comes from upload.html
Nest the else-if as an if in the first if. Otherwise it won't be executed.
$upload = "E:/demons";
if(isset($_POST['userid'], $_POST['pid']))
{
$userid = trim($_POST["userid"]);
$pid = trim($_POST["pid"]);
$sql = "SELECT * FROM template WHERE uname = '$userid' and pword = '$pid'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
echo "公司".'<br/>';
echo $row['client'].'<br/>'.'<br/>';
echo "第".'<br/>';
echo '<a href="upload.html"/>'.$row['day1'].'</a>'.'<br/>';
$target = $upload.'/'.$row['week'].'/'.$row['day1'].'/'.$row['client'].'/'.$row['brand'].'/'.$row['sc'].'/';
$imagename = $row['week'].'.'.$row['day1'].'.'.$row['client'].'.'.$row['brand'].'.'.$row['sc'].'.'.'jpg';
if(!file_exists($target))
{
mkdir($target,null,true);
}
if(isset($_FILES['image']))
{
$image = basename($_FILES["image"]["name"]);
echo $image;
move_uploaded_file($_FILES['image']['tmp_name'], $target);
}
}
$upload = "Your desired location";
//comes from the login.html page
if(isset($_POST['userid'],$_POST['pid']))
{
$userid = trim($_POST["userid"]);
$pid = trim($_POST["pid"]);
$sql = "SELECT * FROM template WHERE uname = '$userid' and pword = '$pid'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
echo "Whatever coloumn you wish to echo from database".'<br/>';
echo $row['col1'].'<br/>'.'<br/>';
echo "Second Coloumn".'<br/>';
echo '<a href="upload.html"/>'.$row['col2'].'</a>'.'<br/>';
//create the folders and subfolders based on the data from the database
$target = $upload.'/'.$row['col1'].'/'.$row['col2'].'/'.$row['col3'].'/'.$row['col4'].'/'.$row['col5'].'/';
//for renaming the image.
$imagename = $row['col1'].'.'.$row['col2'].'.'.$row['col3'].'.'.$row['col4'].'.'.$row['col5'].'.'.'jpg';
//create the folders and subfolders
if(!file_exists($target))
{
mkdir($target,null,0777);
}
//start session and store the value of $target and $imagename in a variable
session_start();
$_SESSION['str'] = $target;
$_SESSION['img'] = $imagename;
//This comes from other HTML page but to the same PHP.
if(isset($_FILES['image']))
// image upload from upload.html
// Want the value of target here.
{
session_start();
$_SESSION['str'];
$_SESSION['img'];
$image = basename($_FILES["image"]["name"]);
//Move the uploaded file to the desired location.
move_uploaded_file($_FILES['image']['tmp_name'], $_SESSION['str'].$_SESSION['img']);
echo "Upload Successful";
Hope this would be helpful for all.

how to get picture filename from database?

I want to get the database picture path so that i can used it and store the same file-name path in the image folder so both can be matched up. Actually i am using a unique-id so that pictures have unique names but don't know how to use it rightly. Any help would be appreciated.
$insert = "UPDATE USER_LOGIN SET PICTURE = '".uniqid().$_FILES['file']['name']."' WHERE USERNAME = '".$_COOKIE['username']."'";
$result = oci_parse($con, $insert);
// Executes a statement.
$check = oci_execute($result);
$UploadDirectory = '/wamp/www/img/Users/Users/'.$row['PICTURE'];
Working Solution:
if($row)
{
$Filename = uniqid().$_FILES['file']['name'];
$DirectoryPath = '/wamp/www/img/Users/Users/'.$Filename;
if(move_uploaded_file($_FILES['file']['tmp_name'], $DirectoryPath))
{
$insert = "UPDATE USER_LOGIN SET PICTURE = '".$Filename."' WHERE USERNAME = '".$_COOKIE['username']."'";
$result = oci_parse($con, $insert);
// Executes a statement.
$check = oci_execute($result);
if($check)
{
echo "Saved";
// Commit the changes to the table.
oci_commit($con);
}
else
{
// Rollback changes to table.
oci_rollback($con);
}
}
else
{
//die('error uploading File!');
}
}

Unexpected result after file upload

This code is to update database. it updates everything even uploads image sucessfully but after image upload the whole page gets blank and only "Array()" is displayed at top. Why is that?
<?php
if(!isset($_GET["prid"])){
header("Location: prjedit.php");
}
else {
$prid = intval($_GET["prid"]);
$sqlprj = "SELECT * FROM projects WHERE id = ? LIMIT 1";
$statement = $db->prepare($sqlprj);
$statement->execute(array($prid));
$project = $statement->fetchObject();
//submitted form
if( (isset($_POST["title"])) && (isset($_POST["details"])) ) {
$title = $_POST['title'];
$desc = $_POST['descr'];
$details = $_POST['details'];
if(!empty($_FILES['image']['name'])) {
//update image
$file = basename($_FILES['image']['name']);
$dir = "projects/";
$target_path = $dir . basename($_FILES['image']['name']);
$tempname = $_FILES['image']['tmp_name'];
if(!file_exists($target_path)) {
if(move_uploaded_file($tempname, $target_path)) {
$sqlimg = "UPDATE projects SET image = ? WHERE id = ?";
$statement = $db->prepare($sqlimg);
$statement->execute(array($file, $prid));
if($statement->rowCount() > 0) {
try {
chdir('./projects/');
unlink($project->image);
chdir('..');
}
catch (Exception $e) {
$message = "Sorry image delete failed ";
echo $e->getMessage();
}
}
else {
die ($db->errorInfo());
}
}
else {
$message = "Sorry Image update failed";
}
}
else {
$message = "Sorry this image already exists but text";
}
}
// update project texts
$sqlupd = "UPDATE projects SET title = ?, descinfo = ?, details = ? WHERE id = ?";
$statement = $db->prepare($sqlupd);
$statement->execute(array($title, $desc, $details, $prid));
if($statement->rowCount()) {
$message = " Saved successfully";
}
else {
die($db->errorInfo());
}
}
}
?>
Looking at Pdo::codeInfo documentation, it returns an array.
When you write die($db->errorInfo()); it will try to display this array.
As suggested by the documentation itself, you could try print_r($db->errorInfo()); die; and see what happens.

Categories