За последние 24 часа нас посетили 28165 программистов и 1815 роботов. Сейчас ищут 1405 программистов ...

Скрипт поиска и удаления изображений. Помогите новичьку

Тема в разделе "Сделайте за меня", создана пользователем ushkom, 12 дек 2017.

  1. ushkom

    ushkom Активный пользователь

    С нами с:
    5 сен 2016
    Сообщения:
    68
    Симпатии:
    1
    Добрый день. Нужен скрипт для сравнения ссылок на изображения в базе и соответственно в папке на сервере. Если ссылки в базе нет а в папке есть это изображение, его с сервера удаляем. в сети нашел несколько похожих скриптов и собрал их в один.
    Сам скрипт:
    Код (Text):
    1. <?
    2. if (!defined('DATALIFEENGINE')) {
    3.     define('DATALIFEENGINE', true);
    4. }
    5.  
    6. #позвол¤ем скрипту анализировать картинки без лимита (если их много будет)
    7. set_time_limit(0);
    8. # ----------------------- декларирование основных параметров ------------------------
    9. #путь к папке с картинками
    10. define("IMGDIR", 'uploads/posts/2017-01/thumbs');
    11. #путь к конфигу
    12. define("CONF", 'engine/data/dbconfig.php');
    13. define( 'DATALIFEENGINE', true );
    14. #задать произвольный логин и пороль админа
    15. define( 'LOGIN', 'ushkom' );
    16. define( 'PASSWORD', 'ushkom102030' );
    17. class db{}
    18. # ----------------------- проверки ------------------------
    19. if (!is_dir(IMGDIR))
    20. die(IMGDIR . ' not found!');
    21. #подключаем длешный конфиг
    22. if (!file_exists(CONF))
    23. die(CONF .' not found!');
    24. include  CONF ;
    25. # ----------------------- настройки ------------------------
    26. header("Content-Type: text/html; charset=".COLLATE);
    27. session_start();
    28. # ----------------------- класы и функции ------------------------
    29. class SQL
    30. {
    31. public $server,$user,$password,$database,$connected;
    32.     function __construct($server,$password,$database,$user)
    33.     {
    34.         $this -> count = 0;
    35.         $this -> connected = false;
    36.         $this -> server = $server;
    37.         $this -> user = $user;
    38.         $this -> password = $password;
    39.         $this -> database = $database;
    40.     }  
    41.     function SetBase($base)
    42.     {
    43.     $this->database = trim($base);
    44.     }
    45.    
    46.     function connect()
    47.     {
    48.    
    49.         if ($this->connected)
    50.             mysql_close();
    51.         $curent = @mysql_connect ($this->server, $this->user, $this->password);
    52.         if (!$curent)
    53.         {
    54.             $this->connected = false;
    55.             return( mysql_error() );
    56.         }      
    57.         unset($curent);
    58.             $curent = @mysql_select_db ($this->database);
    59.             if (!$curent)
    60.             {
    61.                 $this->connected = false;
    62.                 return( mysql_error() );
    63.             }      
    64.         $this->connected = true;
    65.         $this->run("SET NAMES ".COLLATE);
    66.         return $this->connected;
    67.     }
    68.     function query($query)
    69.     {
    70.         $result = $this->run($query);
    71.         if (!$result)          
    72.             return(mysql_error());
    73.         $d = array ();
    74.                 while ($row = mysql_fetch_assoc($result))
    75.                         $d[] = $row;  
    76.         return $d;
    77.     }
    78.    
    79.     function run($query)
    80.     {
    81.     if (!$this->connected)
    82.                 $this -> connect();
    83.     $query = trim($query);
    84.     $result = mysql_query($query);
    85.     return $result;
    86.     }
    87. function SimpleQuery($query)
    88. {
    89.     $result = $this->run($query);
    90.         if (!$result)          
    91.             return(mysql_error());
    92.         $d = array ();
    93.         while ($row = mysql_fetch_assoc($result))
    94.                         return $row;  
    95.         return false;
    96. }
    97. }
    98. function IsUsed($name)
    99. {
    100. global $sql;
    101. $name = addslashes($name);
    102. $data = $sql -> query("select `id` from `" . PREFIX ."_post` where `short_story` like '%$name%' or `full_story` like '%$name%' or `xfields` like '%$name%'");
    103. if (!$data) return false;
    104. if (!isset($data[0])) return false;
    105. $id = '';
    106. foreach ($data as $c)
    107. {
    108. $id .= '<b>' . $c['id'] . '</b> , ';
    109. }
    110. return rtrim($id , ', ');
    111. }
    112. #--------------------авторизаци¤--------------------------------
    113. if (isset($_POST['Tlogin']))
    114. {
    115. if ($_POST['login'] == LOGIN && $_POST['password'] == PASSWORD) $_SESSION['logined'] = true;
    116. }
    117. if (!isset($_SESSION['logined']))
    118. {
    119. #если не залогинен
    120. ?>
    121. <form method="POST">
    122. LOGIN:</br><input type="text" name="login"></br>
    123. PASSWORD:</br><input type="password" name="password"></br>
    124. <input type="submit" name="Tlogin">
    125. </form>
    126. <?
    127. exit(0);
    128. }
    129. #всЄ ниже если залогинен
    130. #--------------------попытка подключитс¤ к базе----------------
    131. $sql = new SQL( DBHOST , DBPASS , DBNAME , DBUSER );
    132. $error = $sql -> connect();
    133. if (!$sql -> connected) die($error);
    134. #--------------главна¤ часть-------------
    135. $images = array_merge( glob(IMGDIR .'/*.jpg') , glob(IMGDIR .'/*.jpeg') , glob(IMGDIR .'/*.gif') , glob(IMGDIR .'/*.png'));
    136. if (is_null($images) || !isset($images['0'])) die("нет картинок !");
    137. ?>
    138. <table border="4">
    139. </tr>
    140.   <th>
    141.   название
    142.   </th>
    143.     <th>
    144.   используетс¤ (id)
    145.   </th>
    146.     <th>
    147.   предосмотр
    148.   </th>
    149.       <th>
    150.   ”далить
    151.   </th>
    152. </tr>
    153. <? foreach($images as $img)
    154. {
    155. echo "<tr>";
    156. #name
    157. echo "<td><a href='$img' target='blank'>$img</a></td>";
    158. #used
    159. $ids = IsUsed($img);
    160. if (!$ids)
    161. echo "<td><font color='red'>нигде не используется !</font></td>";
    162. else
    163. echo "<td>$ids</td>";
    164. echo "<td><img src='$img' height='50px'></img></td><td><a href='?d=".$img."'>Удалить!!!</a><br></td>";
    165.  
    166. if (!empty($_GET['d'])){
    167.         unlink($_GET['d']);}
    168.  
    169.  
    170.  
    171. }
    172. ?>
    173. </table>
    Подскажите как можно сделать выборку и выводить только картинки которые не используются, и как их после просмотра можно массово удалить? большое всем спасибо за помощь.
     
  2. ushkom

    ushkom Активный пользователь

    С нами с:
    5 сен 2016
    Сообщения:
    68
    Симпатии:
    1
    Подскажите хоть в каком направлении копать, статьи или еще что. Спасибо
     
  3. ushkom

    ushkom Активный пользователь

    С нами с:
    5 сен 2016
    Сообщения:
    68
    Симпатии:
    1
    Всем спасибо, сам нашел способ. Может кому пригодится
    Код (Text):
    1. <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
    2. <?
    3. if (!defined('DATALIFEENGINE')) {
    4.     define('DATALIFEENGINE', true);
    5. }
    6.  
    7. #позвол¤ем скрипту анализировать картинки без лимита (если их много будет)
    8. set_time_limit(0);
    9. # ----------------------- декларирование основных параметров ------------------------
    10. #путь к папке с картинками
    11. define("IMGDIR", 'uploads/posts/2017-01');
    12. #путь к конфигу
    13. define("CONF", 'engine/data/dbconfig.php');
    14. define( 'DATALIFEENGINE', true );
    15. #задать произвольный логин и пороль админа
    16. define( 'LOGIN', 'ushkom' );
    17. define( 'PASSWORD', 'ushkom102030' );
    18. class db{}
    19. # ----------------------- проверки ------------------------
    20. if (!is_dir(IMGDIR))
    21. die(IMGDIR . ' not found!');
    22. #подключаем длешный конфиг
    23. if (!file_exists(CONF))
    24. die(CONF .' not found!');
    25. include  CONF ;
    26. # ----------------------- настройки ------------------------
    27. header("Content-Type: text/html; charset=".COLLATE);
    28. session_start();
    29. # ----------------------- класы и функции ------------------------
    30. class SQL
    31. {
    32. public $server,$user,$password,$database,$connected;
    33.     function __construct($server,$password,$database,$user)
    34.     {
    35.         $this -> count = 0;
    36.         $this -> connected = false;
    37.         $this -> server = $server;
    38.         $this -> user = $user;
    39.         $this -> password = $password;
    40.         $this -> database = $database;
    41.     }  
    42.     function SetBase($base)
    43.     {
    44.     $this->database = trim($base);
    45.     }
    46.    
    47.     function connect()
    48.     {
    49.    
    50.         if ($this->connected)
    51.             mysql_close();
    52.         $curent = @mysql_connect ($this->server, $this->user, $this->password);
    53.         if (!$curent)
    54.         {
    55.             $this->connected = false;
    56.             return( mysql_error() );
    57.         }      
    58.         unset($curent);
    59.             $curent = @mysql_select_db ($this->database);
    60.             if (!$curent)
    61.             {
    62.                 $this->connected = false;
    63.                 return( mysql_error() );
    64.             }      
    65.         $this->connected = true;
    66.         $this->run("SET NAMES ".COLLATE);
    67.         return $this->connected;
    68.     }
    69.     function query($query)
    70.     {
    71.         $result = $this->run($query);
    72.         if (!$result)          
    73.             return(mysql_error());
    74.         $d = array ();
    75.                 while ($row = mysql_fetch_assoc($result))
    76.                         $d[] = $row;  
    77.         return $d;
    78.     }
    79.    
    80.     function run($query)
    81.     {
    82.     if (!$this->connected)
    83.                 $this -> connect();
    84.     $query = trim($query);
    85.     $result = mysql_query($query);
    86.     return $result;
    87.     }
    88. function SimpleQuery($query)
    89. {
    90.     $result = $this->run($query);
    91.         if (!$result)          
    92.             return(mysql_error());
    93.         $d = array ();
    94.         while ($row = mysql_fetch_assoc($result))
    95.                         return $row;  
    96.         return false;
    97. }
    98. }
    99. function IsUsed($name)
    100. {
    101. global $sql;
    102. $name = addslashes($name);
    103. $data = $sql -> query("select `id` from `" . PREFIX ."_post` where `short_story` like '%$name%' or `full_story` like '%$name%' or `xfields` like '%$name%'");
    104. if (!$data) return false;
    105. if (!isset($data[0])) return false;
    106. $id = '';
    107. foreach ($data as $c)
    108. {
    109. $id .= '<b>' . $c['id'] . '</b> , ';
    110. }
    111. return rtrim($id , ', ');
    112. }
    113. #--------------------авторизаци¤--------------------------------
    114. if (isset($_POST['Tlogin']))
    115. {
    116. if ($_POST['login'] == LOGIN && $_POST['password'] == PASSWORD) $_SESSION['logined'] = true;
    117. }
    118. if (!isset($_SESSION['logined']))
    119. {
    120. #если не залогинен
    121. ?>
    122. <form method="POST">
    123. LOGIN:</br><input type="text" name="login"></br>
    124. PASSWORD:</br><input type="password" name="password"></br>
    125. <input type="submit" name="Tlogin">
    126. </form>
    127. <?
    128. exit(0);
    129. }
    130. #всЄ ниже если залогинен
    131. #--------------------попытка подключитс¤ к базе----------------
    132. $sql = new SQL( DBHOST , DBPASS , DBNAME , DBUSER );
    133. $error = $sql -> connect();
    134. if (!$sql -> connected) die($error);
    135. #--------------главна¤ часть-------------
    136. $images = array_merge( glob(IMGDIR .'/*.jpg') , glob(IMGDIR .'/*.jpeg') , glob(IMGDIR .'/*.gif') , glob(IMGDIR .'/*.png'));
    137. if (is_null($images) || !isset($images['0'])) die("нет картинок !");
    138. ?>
    139. <script language="javascript" type="text/javascript">
    140. $(document).ready(function() {
    141.     $("#check_all").click(function () {
    142.          if (!$("#check_all").is(":checked"))
    143.             $(".checkbox").removeAttr("checked");
    144.         else
    145.             $(".checkbox").attr("checked","checked");
    146.     });
    147. });
    148. </script>
    149. <form method="get" action="">
    150. <table border="4">
    151. <tr>
    152.   <th>
    153.   название
    154.   </th>
    155.     <th>
    156.   используетс¤ (id)
    157.   </th>
    158.     <th>
    159.   предосмотр
    160.   </th>
    161.       <th>
    162.   ”далить
    163.   </th>
    164. </tr>
    165. <? foreach($images as $img)
    166. {
    167. $ids = IsUsed($img);
    168. if (!$ids || $img){
    169. $img1 = $img;
    170. }
    171.  
    172. echo "<tr>";
    173. #name
    174. if (!$ids)
    175. echo "<td><a href='$img1' target='blank'>$img1</a></td>";
    176. #used
    177.  
    178. if (!$ids)
    179. echo "<td><font color='red'>нигде не используетс¤ !</font></td>";
    180.  
    181. if (!$ids)
    182. echo "<td><img src='$img1' height='50px'></img><br></td>";
    183.  
    184. if (!$ids)
    185. echo "<td><label><input class=checkbox type=checkbox name=delfile[] value=$img1></label><br></td>";
    186. echo "</tr>";
    187.  
    188. }
    189. ?>
    190. </table>
    191. <br>
    192. <label><input type="checkbox" id="check_all"> Выделить всё</label><br>
    193. <br>
    194. <input type="submit" name="sub" value="Удалить все!!!" /><br>
    195.     </form>
    196.    
    197.  
    198.    
    199. <?  
    200. if (!empty($_GET[delfile])) {
    201. foreach ($_GET[delfile] as $filename)
    202. {
    203. unlink("".$filename);
    204. }
    205. }
    206. ?>