2012-06-21 53 views
0

我正在使用以下php腳本在我的網站上顯示一個隨機圖像,它的工作原理很好,除了它會抓取圖像,我不希望它抓住所以我想添加一個檢查腳本,以便它只會抓取圖像,如果它以字母「TN-」開頭,但我不是一個PHP編碼器,所以我想我會問這裏的專家一些幫助。特定文件名的php隨機圖像腳本

<?php 

    // files to search for 
    $extList = array(); 
     $extList['gif'] = 'image/gif'; 
     $extList['jpg'] = 'image/jpeg'; 
     $extList['jpeg'] = 'image/jpeg'; 
     $extList['png'] = 'image/png'; 

    // set to specific image if needed 
    // null will result in a random image 
    $img = null; 

    // path to the directory you want to scan 
    $directory = './'; 
    if (substr($directory,-1) != '/') { 
     $directory = $directory.'/'; 
    } 

    // if img is set, show it 
    if (isset($_GET['img'])) { 
     $imageInfo = pathinfo($_GET['img']); 
     if (
      isset($extList[ strtolower($imageInfo['extension']) ]) && 
      file_exists($directory.$imageInfo['basename']) 
     ) { 
      $img = $directory.$imageInfo['basename']; 
     } 
    } 
    // if img isnt set, grab a random 
    else { 
     //cycle through directory and subfolders 
     $it = new RecursiveDirectoryIterator("$directory"); 
     foreach(new RecursiveIteratorIterator($it) as $file) 
     { 
      $file_info = pathinfo($file); 
      if (
       isset($extList[ strtolower($file_info['extension']) ]) 
      ) { 
       $items[] = $file; 
      } 
     } 
     sort($items); 
     // get the random image 
     if (count($items) > 0) { 
      $imageNumber = time() % count($items); 
      $img = $directory.$items[$imageNumber]; 
     } 
    } 

    // if img isnt null, display it 
    if ($img!=null) { 
     $imageInfo = pathinfo($img); 
     $contentType = 'Content-type: '.$extList[ $imageInfo['extension'] ]; 
     header ($contentType); 
     readfile($img); 
    } 
    // else, try to create one or give error 
    else { 
     if (function_exists('imagecreate')) { 
      header ("Content-type: image/png"); 
      $im = @imagecreate (100, 100) 
       or die ("Cannot initialize new GD image stream"); 
      $background_color = imagecolorallocate ($im, 255, 255, 255); 
      $text_color = imagecolorallocate ($im, 0,0,0); 
      imagestring ($im, 2, 5, 5, "IMAGE ERROR", $text_color); 
      imagepng ($im); 
      imagedestroy($im); 
     } 
    } 
?> 

回答

1

您可以添加一個檢查到在你的腳本開始行32塊:

//cycle through directory and subfolders 
    $it = new RecursiveDirectoryIterator("$directory"); 
    foreach(new RecursiveIteratorIterator($it) as $file) 
    { 
     $file_info = pathinfo($file); 
     if (
      isset($extList[ strtolower($file_info['extension']) ]) && 
      strpos($file_info['basename'], 'TN-') === 0 
     ) { 
      $items[] = $file; 
     } 
    } 
+0

謝謝,現在的偉大工程。非常感激。 – nosx