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
?>

:: PHP Tutorials Home ::
PHP String Functions
 • concatenation • echo
 • ereg • ereg_replace
 • explode • htmlspecialchars
 • preg_match • preg_replace
 • preg_split • print,sprintf
 • regular expr. • str_replace
 • strcmp • strpos
 • strrev • strrpos
 • strtr • substr
 • substr_replace
PHP Array Functions
 • array_diff • array_flip
 • array_intersect • array_key_exists
 • array_keys • array_merge
 • array_pop • array_push
 • array_rand • array_search
 • array_splice • array_unshift
 • array_values • asort & arsort
 • count • in_array
 • ksort • shuffle
 • sort
PHP Data Types
 • array • associative array
 • date & time • number
 • class, object • regular expression
 • string • variables
PHP Loop & Conditions
 • continue & break • for loop
 • foreach • if else
 • not equal • while
PHP File System Functions
 • copy • delete, unlink
 • dirname • download url
 • file_exists • is_file
 • mkdir • read file
 • scandir • write file
PHP Popular Topics
 • ajax • clone
 • comments • constants
 • cookie • database
 • defined • die
 • form validation • gd, draw images
 • global variables • header url
 • heredoc • mail
 • pass by reference • print
 • regular expr. • sessions
 • threads • xml parse
PHP Math Functions
 • abs • cos
 • exp • floor & ceil
 • fmod • log
 • max & min • pow
 • round • sin
 • sqrt • tan
endmemo.com © 2024  | Terms of Use | Privacy | Home