1. 程式人生 > >PHP讀取本地目錄裡的檔案並顯示

PHP讀取本地目錄裡的檔案並顯示

<?php
function printFile($filepath)
{ 
	//substr(string,start,length)函式返回字串的一部分;start規定在字串的何處開始 ;length規定要返回的字串長度。預設是直到字串的結尾。  
	//strripos(string,find,start)查詢 "php" 在字串中最後一次出現的位置; find為規定要查詢的字元;start可選。規定開始搜尋的位置
	
	//讀取檔案字尾名
	//$filetype = substr ( $filename, strripos ( $filename, "." ) + 1 );
	//判斷是不是以txt結尾並且是檔案
	#if ($filetype == "txt" && is_file ( $filepath . "/" . $filename ))		
	if ( is_file ( $filepath))
	{
		$filename=iconv("gb2312","utf-8",$filepath);
		echo $filename."內容如下:"."<br/>";
		$fp = fopen ( $filepath, "r" );//開啟檔案
		#while (! feof ( $f )) //一直輸出直到檔案結尾
		$i = 1;
		while ($i < 10)
		{
			$line = fgets ( $fp );
			echo $line."<br/>";
			$i = $i +1;
		}
		fclose($fp);
	}	
}

function readFileRecursive($filepath)
{
	if (is_dir ( $filepath )) //判斷是不是目錄
	{
		$dirhandle = opendir ( $filepath );//開啟資料夾的控制代碼
		if ($dirhandle) 
		{
			//判斷是不是有子檔案或者資料夾
			while ( ($filename = readdir ( $dirhandle ))!= false ) 		
			{
				if ($filename == "." or $filename == "..")
				{
					//echo "目錄為“.”或“..”"."<br/>";
					continue;
				}
				
				//判斷是否為目錄,如果為目錄遞迴呼叫函式,否則直接讀取列印檔案
				if(is_dir ($filepath . "/" . $filename ))
				{
					readFileRecursive($filepath . "/" . $filename);
				}
				else
				{
					//列印檔案
					printFile($filepath . "/" . $filename);
					echo "<br/>";
				}
			}
			closedir ( $dirhandle );
		}
	}
	else
	{
		
		printFile($filepath . "/" . $filename);
		return;
	}
}

header("content-type:text/html;charset=utf-8");
#echo "Hello World"."<br/>";
$filepath = "C:/phpStudy/PHPTutorial/WWW/test/results"; //想要讀取的目錄
readFileRecursive($filepath )
?>