从图像搜索中排除目录结构

时间:2014-08-21 12:05:05

标签: php str-replace trim

我正在编写一个脚本来扫描电子商务网站以查找未使用的图片。该脚本会搜索“图像”。文件夹及其文件子文件夹然后按以下格式创建它找到的任何图像的列表:

image.jpg
product_images/2000/image.jpg

然后脚本扫描数据库中的预定义表以检查对图像的引用,但是,图像仅通过文件名存储在数据库中(即' image.jpg')而不是完整的文件路径,因此即使图像路径是' product_images / 2000 / image.jpg',它也会以' image.jpg'的形式存储在数据库中。并且前端代码根据当前产品的产品代码计算出文件结构的其余部分。

由于数据库扫描正在查找' image.jpg但服务器文件扫描正在查找' product_images / 2000 / image.jpg'。

任何人都可以告诉我如何编辑下面的代码以删除'子目录/'服务器文件扫描的部分内容是什么?

<?php
/*
AZER: (This is an option to set n the code below)
commented out gif and png reports since it give a lot of infos on image type few people use for products photos
*/
require('includes/application_top.php');
set_time_limit (0);
require(DIR_WS_LANGUAGES . $language . '/' . FILENAME_REMOVE_IMAGES);

// azer modifid to read from configure.php : $root_dir = 'v:/easyphp/www/ms2fr/shop'; 
$root_dir = DIR_FS_CATALOG ;// look in this root

// azer modifid, to read from configure.php :  $base_dir = 'http://localhost/ms2fr/shop'; 
$base_dir = HTTP_SERVER . DIR_WS_CATALOG ; // for links

///////////////////////////////////////////////////////////////////////////////////
//                           ADDITIONAL OPTIONS AND SETTINGS BELOW                                
// if script timesout you may elect to turn off the displays for the list of images
// in the DB and the server, this will free up server resources,
// the lists are for infomational purposes only anyway.
//
///////////////////////////////////////////////////////////////////////////////////

//TURN OFF DB DISPLAY
$turn_off_db_display = 0;  // 0 means it is on, 1 means it is off

//TURN OFF SERVER DISPLAY
$turn_off_server_display = 0;  // 0 means it is on, 1 means it is off

// look in this images folder - do not add more folders here - just the main one
$images_dir = DIR_WS_IMAGES; // set to catalog images folder ie 'images'; 

// Check product descriptions for images (set to false to disable)
$descip_check = true;

// Remove images matching pattern from the check, ie put 'thumb' to exclude all images with 'thumb' as part of the name (or directory).
$pattern = '';

// Add links to product images with missing files, only applies to product images (not description) (set to true to enable)
$product_links = true;

// check sub-folders within the 'images' directory (will only go 'one deep') (set to true to enable)
$check_folders = true; 

// exclude the following folders from the check, format must be EX: $exclude_folders = array("banners","default","icons","mail","infobox","pr","links");
// Compare with (if you have it): Select Product Image Directory & Instant Update - Multilanguage V1.15
// catalog/images subfolders to exclude from adding new images
// $exclude_folders = array( "UHtmlEmails","banners","default","icons","mail","buttons","infobox","js"); 

$exclude_folders = array("UHtmlEmails","UNUSED","banners","default","mail","icons","infobox","thumbs","AboutGeyser","Payment_and_Delivery","ProductGuides","Showroom","Contact-us","account_page","Checkout","Returns","Vacancies","brands");

// to add more tables use do it like so: $table_array = array("products_image","products_image_med");
// see below for possible image names
$table_array = array("products_image");

/* Additional possible image names 
,"products_image_med","products_image_lrg","products_image_sm_1","products_image_xl_1","products_image_sm_2","products_image_xl_2","products_image_sm_3","products_image_xl_3","products_image_sm_4","products_image_xl_4","products_image_sm_5", "products_image_xl_5","products_image_sm_6","products_image_xl_6"
*/

// name of this script
$script_name = "remove_unused_images.php";

/* ADVANCED OPTION for SQL query - 
DEFAULT SETTING: get all products even if status is off and there is no quantity
$optional_sql = ""

get image info if the product status is on or if the product has a qty greater than 0 example query: 
$optional_sql = " where p.products_status = '1' or p.products_quantity >= '0'";

get image info if the product status is on only example query: 
$optional_sql = " where p.products_status = '1'";
*/
$optional_sql = "";

// Additional tables to be checked ie TABLE_LINKS
$dbase_tables = array(TABLE_CATEGORIES, TABLE_MANUFACTURERS, 'products_images_gallery', 'products_images_gallery');
// Image Field names within above tables (THESE MUST MATCH) ie  'links_image_url'
$image_array = array('categories_image', 'manufacturers_image', 'large', 'small');

/////////////////////////////////////////////////////
//                                                 //  
//            Do not edit below                    //
//                                                 //
/////////////////////////////////////////////////////

// AZERISH ***** 
//original:  AZER  removed the extra slash : $root_images_dir = $root_dir . '/' . $images_dir;// look in this main images folder
   $sess_id = (tep_not_null(SID));
   if (substr($images_dir, -1) != '/') $images_dir .= '/'; //add trailing slash to images dir if none.. 
   $exclude_folders[] = "UNUSED";

   $root_images_dir = $root_dir .  $images_dir;// look in this main images folder

if (!file_exists($root_images_dir)) die('<center><br><br><b>'.TEXT_LINE_96_1.' ('.$root_images_dir.') '.TEXT_LINE_96_2.'</b></center><br><br>');

// Read the database, then put all existing db images into an array called $full_image_list[]
$sql = "select ";

  $numb_tables = count($table_array);
  for ($i = 0; $i < $numb_tables; ++$i)
  {
    $sql .= ' p.' . $table_array[$i] . ($i == ($numb_tables-1) ? ' ' : ', ');
  }
if ($product_links) { $sql .= ', p.products_id '; $id_array = array(); }
$sql .= "from " . TABLE_PRODUCTS . " p ";
$sql .= $optional_sql;

if (require ('includes/configure.php')){}else{echo '<center><br><br>'.TEXT_LINE_110.'</center><br><br>';break;}// login info

$conn = mysql_connect(DB_SERVER, DB_SERVER_USERNAME, DB_SERVER_PASSWORD) or die("<center><br><br>".TEXT_LINE_112."</center><br><br>" . mysql_error());// connect to db

$select_db = mysql_select_db(DB_DATABASE, $conn) or die("<center><br><br>".TEXT_LINE_114."</center><br><br>" . mysql_error()); //select the right db

$image_info_query = mysql_query($sql, $conn) or die("<center><br><br>".TEXT_LINE_116."</center><br><br>" . mysql_error());

$numb_tables = count($table_array);
// put the images in an array

while ($image_info = mysql_fetch_array($image_info_query))
{

    for ($i = 0; $i < $numb_tables; ++$i)
    {

// ***azerish: *If only jpg format is used*  if (strpos($image_info[$table_array[$i]], 'jpg'))   
if( strpos(strtolower($image_info[$table_array[$i]]), 'jpg') || strpos(strtolower($image_info[$table_array[$i]]), 'gif') || strpos(strtolower($image_info[$table_array[$i]]), 'png'))
{ $full_image_list[] = strip_tags($image_info[$table_array[$i]]);  //put all db images into 1 array
 if ($product_links) $id_array[$image_info[$table_array[$i]]] = $image_info['products_id']; } // store product id for image
    }
}

// Place images from additional tables into the same array
        if (count($dbase_tables) != count($image_array)) die("<center><br><br>".TEXT_LINE_135."</center><br><br>"); 

            for ($i = 0; $i < count($dbase_tables); ++$i)
        {

$image_query = tep_db_query("select " . $image_array[$i] . " as image from " . $dbase_tables[$i]);
while ($image = tep_db_fetch_array($image_query)){ 
if (strpos(strtolower($image['image']), 'jpg') || strpos(strtolower($image['image']), 'gif') || strpos(strtolower($image['image']), 'png')) $full_image_list[] = strip_tags(str_replace($images_dir, '', $image['image'])); }

}
// end reading the database for installed images

// get the server images/
  $serverfiles = array();
  GetImageListFromServer($root_images_dir,$serverfiles);

// get all sub-directories of images directory, exlude any in exclude list

if ($check_folders) {

function expandDirectories($base_dir) {
    global $exclude_folders;
      $directories = array();
      foreach(scandir($base_dir) as $file) {
            if($file == '.' || $file == '..') continue;
            $dir = $base_dir.DIRECTORY_SEPARATOR.$file;
            if(is_dir($dir) && !in_array($file,$exclude_folders)) {
                $directories []= $dir;
                $directories = array_merge($directories, expandDirectories($dir));
            }
      }
      return $directories;
}

$dir_array = expandDirectories(rtrim($root_images_dir,"/"));


// get images in sub-directories

 foreach ($dir_array as $key => $value)
     //echo $value."<br>";
       GetImageListFromServer($value,$serverfiles);

}

if (tep_not_null($pattern)) {

    sort($serverfiles);// server file list
  for ($i = 0; $i < count($serverfiles); ++$i) // remove any pattern matched images from the server list
    {
        if (strpos(strtolower($serverfiles[$i]),strtolower($pattern))) { unset($serverfiles[$i]); }
    }
    }

  $serverfiles = array_unique($serverfiles);  //remove duplicates
  sort($serverfiles);// server file list

  for ($i = 0; $i < count($serverfiles); ++$i)
    {
     $serverfiles[$i] = trim(str_replace( array($root_images_dir,) , "", $serverfiles[$i]),"/");// remove the root part of the image name
    }

 if ($descip_check)  {
// check if any server images are used within product description & add to db list if so.
    $image_desc_query = mysql_query('select p.products_description as products_description from ' . TABLE_PRODUCTS_DESCRIPTION . ' p ', $conn) or die(TEXT_LINE_188 . mysql_error());

    while ($image_desc = mysql_fetch_array($image_desc_query))
   { 
      for ($i = 0; $i < count($serverfiles); ++$i)
                        {
                        if (strpos($image_desc['products_description'], $serverfiles[$i])) $full_image_list[] = $serverfiles[$i];
                        }
    }
    }

// check for images in specific files, ie header.php, index.php etc add to db list if so.
    $check1 = file_get_contents (DIR_FS_CATALOG.DIR_WS_INCLUDES . 'header.php');
    $check2 = file_get_contents (DIR_FS_CATALOG.FILENAME_DEFAULT);
    $check3 = file_get_contents (DIR_FS_CATALOG.'stylesheet.css');
    $check4 = file_get_contents (DIR_FS_CATALOG.DIR_WS_FUNCTIONS . 'html_output.php');
    $check5 = file_get_contents (DIR_FS_CATALOG.'skin/css/geyser.css');
    for ($i = 0; $i < count($serverfiles); ++$i)
                        {
                        if (strpos($check1, $serverfiles[$i])) { $full_image_list[] = $serverfiles[$i]; continue; }
                        if (strpos($check2, $serverfiles[$i])) { $full_image_list[] = $serverfiles[$i]; continue; }
                        if (strpos($check3, $serverfiles[$i])) { $full_image_list[] = $serverfiles[$i]; continue; }
                        if (strpos($check4, $serverfiles[$i])) { $full_image_list[] = $serverfiles[$i]; continue; }
                        if (strpos($check5, $serverfiles[$i])) $full_image_list[] = $serverfiles[$i];
                        }

  $full_image_list = array_unique($full_image_list); //remove duplicates
  sort($full_image_list);
    $count_db_list = count($full_image_list);//number of images installed in the database
  $count_server_list = count($serverfiles);//number of files on the server

// start the html listing page

3 个答案:

答案 0 :(得分:1)

$image = 'product_images/2000/image.jpg';
$image_path = explode('/', $image);
echo end($image_path);

显示image.jpg

http://3v4l.org/cR5SO

答案 1 :(得分:0)

使用explode()函数分隔url,然后使用PHP中的end()函数选择最后一个数组。以下是代码的外观

$image_url = 'http://yoursitename.com/product_images/2000/image.jpg';
$image_array = explode('/', $image_url);
echo end($image_array); // will output image.jpg the last array

希望这有助于你

答案 2 :(得分:0)

使用

basename(product_images/2000/image.jpg);