Web EndMemo

PHP Read File


fopen() function can open and read through a file.
<?PHP
$handle = fopen("test.txt","r");
while (!feof($handle))
{
   $line = fgets($handle); //get a line, default 1024 bytes
   ...
}
fclose($handle);
?>
If lines are more than 1024 bytes, fgets need to specify the line size:
fgets($handle, 4096); If the line is longer than 4096, it will only get 4096 bytes. If the line is short than 4096, it will get the line only.

fopen() modes:
r read only
r+ read and write

Another way to open file is using file() funtion:
<?PHP
$lines = file(test.txt);
foreach($lines as $thisline)
{
   ...
}
?>

However if the file is too large, the file() function may use up the default memory size defined by the function. To solve it, int_set() can be used.
<?PHP
ini_set( "memory_limit","42000M"); //memory limit set to 4.2Gb
$lines = file(test.txt);
foreach($lines as $thisline)
{
   ...
}
?>

Here is a function which can list all files in a directory.
<?PHP
ini_set( "memory_limit","42000M"); //memory limit set to 4.2Gb

function dirfiles($dir, $prefix = '')
{
	$dir = rtrim($dir, '\\/');
	$result = array();

	foreach (scandir($dir) as $f)
	{
	  if ($f !== '.' and $f !== '..')
	  {
		if (is_dir("$dir/$f"))
		{
		  $result = array_merge($result, $this->dirfiles("$dir/$f", "$prefix$f/"));
		}
		else
		{
		  $result[] = $prefix.$f;
		}
	  }
	}

	return $result;
}

$files = dirfiles("./",''); //list all files under current directory
?>