使用 PHP glob() 函數搜尋目錄內的檔案
使用 PHP 編寫程式, 很多時都需要搜尋目錄內的檔案。 很多程式編寫軟件都可以使用 If File Exist 很容易及快捷來完成。 PHP 沒有 File Exist 這函數, 但是, PHP 有glob() 函數, 讓我們可以很容易的列出目錄內的檔案。
這章課程討論如何搜尋目錄內的檔案。
目錄內的檔案
我們需要搜尋目錄內的 jpg 圖片檔案, 當然也可以搜尋目錄內的任何檔案。在這例子中, 假設我們需要搜尋 photo-keung.jpg 的圖片檔案。這檔案有以下的圖片檔案:
photo-keung.jpg
photo-kong.jpg
photo-wai.jpg
photo-yau.jpg
第一步: 加入以下 PHP 語言於 HTML 文件中
<body>
<p>PHP Search Files In Directory</p>
<?php
// Use glob() function find all searched jpg files in directory
// It will then returns the filenames into an array
// $pics = glob("/path/to/directory/*.jpg");
$pics = glob("*.jpg");
// Test if it is working
// The first index of an array is 0
// The second index of an array is 1
// etc...
echo "The first pic is: " . $pics[0];
echo "<br />";
echo "The second pic is:" . $pics[1];
?>
</body>
</html>
將以上文件儲存成 php-search-file-1.php PHP 檔案.
測試 php-search-file-1.php 是否可以正常執行.
PHP 實例:
瀏 灠 器 應 出 現 :
The second pic is:photo-kong.jpg
可以看出, 使用 glob() 函數可以很容易的列出目錄內的檔案。 一旦可以列出目錄內的檔案, 搜尋檔案的功夫就很輕鬆了。
第二步: 搜尋目錄內的檔案
繼續使用以上的 PHP 檔案, 加入以下的 PHP 程式。
<body>
<p>PHP Search Files In Directory</p>
<?php
// Use glob() function find all searched jpg files in directory
// It will then returns the filenames into an array
// $pics = glob("/path/to/directory/*.jpg");
$pics = glob("*.jpg");
// Test if it is working
// The first index of an array is 0
// The second index of an array is 1
// etc...
echo "The first pic is: " . $pics[0];
echo "<br />";
echo "The second pic is:" . $pics[1];
echo "<br />";
//File need to searched for:
$picSearched = "photo-keung.jpg";
// Loop through the pics array and search line by line if the pic exist
foreach ($pics as $val) {
// each value of the array is:
//echo $val;
if ($val == $picSearched) {
echo "The searched file is found!";
// do something here ....
break;
}
}
?>
</body>
</html>
將以上文件儲存成 php-search-file-2.php PHP 檔案.
測試 php-search-file-2.php 是否可以正常執行.
PHP 實例:
瀏 灠 器 應 出 現 :
The first pic is: photo-keung.jpg
The second pic is:photo-kong.jpg
The searched file is found!