-1

I have a system that allows user to upload PDF files and save the name of the file on the database.

How can I make this script works so user can delete all files from server whose name is not in my database?

This is what I actually have, but the script deletes all files. I don't know how to proceed.

<?php 

include 'fimg.class.php';
require('../../../php/cone.php');
//header('Location: ../produccion.php');

$directory = "upload/";

//get all image files with a .jpg extension.
$images = glob($directory . "*");

foreach($images as $image)
{
    $name = explode('_',$image);
    $name = 'photos/' . $name[0];
    $sql = mysql_query("SELECT imagen FROM r_alumnos");
    if(mysql_num_rows($sql) == 0)
        unlink($image);
}

?>
jotik
  • 17,044
  • 13
  • 58
  • 123
  • 2
    Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Apr 12 '16 at 14:56
  • 1
    Use a `WHERE` clause. – Funk Forty Niner Apr 12 '16 at 14:58
  • What's the image filename in the DB ? full path or just filename ? Also make sure you get only `jpg` files using `glob($directory . "*.jpg");` – Pedro Lobito Apr 12 '16 at 15:00
  • Its just a filename, and actually is not images what im saving, its documents, its a little confusing for the field name but i want to delete all files from folder if the name is not in the db: the name is save it like this: doc_20160412150503c7b053eb38c0e4f5f50749.pdf – Agustin Acosta Apr 12 '16 at 15:05
  • If I understand you right, you want to delete all file names matching a certain name, independently of the extension, right ? – Pedro Lobito Apr 12 '16 at 15:09
  • Right! if the name is not stored in the database, the field must be unlink, but i dont know how to do this action – Agustin Acosta Apr 12 '16 at 15:10

1 Answers1

0

You could create something like a maintenance-script which handels this.

First, load everything in an array (I personally don't like the multiple queries execute):

$database_files = array();
$result_db_files = mysqli_query("SELECT imagen FROM r_alumnos");

while ($row = $result_db_files->fetch_assoc())
{
    $database_files[] = $row['imagen'];
}

Then check each file:

$images = glob($directory . "*");

    foreach($images as $image)
    {
        $name = explode('_',$image);
        $name = 'photos/' . $name[0];
        if (!in_array($name, $database_files))
        {
            unlink($image);
        }
    }
JKMurray
  • 37
  • 3