Reading files

Open and immediately output the file

readfile(file) ;

<?php
	readfile("/home/derrick/myFile.txt") ; //Linux

	readfile("c:\\boot.ini") ; //windows
?>

 

Open and assign file as a string

file_get_contents(file) ;

<?php
	$fileContents = file_get_contents("/home/derrick/myFile.txt") ;

	echo $fileContents ;
?>

 

Open and assign file into array

file(file) ;

<?php
	$fileName = "/home/d/myFile.txt" ; //specify file name

	$myArray = file($fileName); //open and assign to array

	while (list($key,$value) = each($myArray)) { //using list() function to get key/value pair

		print "$value"; //display just the value

	}
?>

 

Read single line from opened file

fgets(file, [length]) ; //note, [length] is optional

<?php
	$fileName = "/home/d/myFile.txt" ; //specify file name

	$fileHandle = fopen($fileName,"r") ; //open above and assign to handle

	while( !feof( $fileHandle ) ) { //loop until EOF

		$line=fgets( $fileHandle ) ; //read current line

		echo "$line"; //display current line
	}

	fclose( $fileHandle ) ; //close file
?>

*note feof(); tests for EOF from the file handle

*If no length specified will keep reading until end of line, or \n

 

Read opened file

fread(file, length) ; //note, length is mandatory

<?php
	$fileName = "/home/d/myFile.txt" ; //specify file name

	$fileHandle = fopen($fileName,"r") ; //open above and assign to handle

	$fileContents = fread($fileHandle, filesize($fileName)) ; //assign contents of file

	fclose( $fileHandle ) ; //close file

	echo $fileContents ; //display contents
?>

Leave a Reply