File Handling in PHP
File Handling in PHP
The command takes two parameters, the file to be opened, and the mode in which to open the file. The function returns a file pointer if successful, otherwise zero (false). Files are opened with fopen for reading or writing. $fp fopen(!m"file.t#t!, !r!)$
%f fopen is unable to open the file, it returns &. This can be used to e#it the function with an appropriate message. if ( '($fp fopen(!m"file.t#t!, !r!) ) )
e#it(!(nable to open the input file.!)$ File Modes The following table shows the different modes the file may be opened in. File Modes r r* w w* a a* # Description )ead onl". File pointer at the start of the file )ead+,rite. File pointer at the start of the file ,rite onl". Truncates the file (o-erwriting it). %f the file doesn.t e#ist, fopen() will tr" to create the file )ead+,rite. Truncates the file (o-erwriting it). %f the file doesn.t e#ist, fopen() will tr" to create the file /ppend. File pointer at the end of the file. %f the file doesn.t e#ist, fopen() will tr" to create the file )ead+/ppend. File pointer at the end of the file. %f the file doesn.t e#ist, fopen() will tr" to create the file 0reate and open for write onl". File pointer at the beginning of the file. %f the file alread" e#ists, the fopen() call will fail and generate an error. %f the file does not e#ist, tr" to create it 0reate and open for write onl". File pointer at the beginning of the file. %f the file alread" e#ists, the fopen() call will fail and generate an error. %f the file does not e#ist, tr" to create it
#*
1ote2 The mode ma" also contain the letter .b.. This is useful onl" on s"stems which differentiate between binar" and te#t files (i.e. ,indows. %t.s useless on (ni#+3inu#). %f not needed, it will be ignored. Closing a File The fclose function is used to close a file when "ou are finished with it. fclose($fp)$ Reading from Files 4ou can read from files opened in r, r*, w*, and a* mode. The feof function is used to determine if the end of file is true. if ( feof($fp) ) echo !5nd of file6br7!$
The feof function can be used in a while loop, to read from the file until the end of file is encountered. / line at a time can be read with the fgets function2 while( 'feof($fp) ) 8 ++ )eads one line at a time, up to 9:; characters. 5ach line ends with a newline. ++ %f the length argument is omitted, PHP defaults to a length of <&9;. $m"line fgets($fp, 9::)$ echo $m"line$ = 4ou can read in a single character at a time from a file using the fgetc function2 while( 'feof($fp) ) 8 ++ )eads one character at a time from the file. $ch fgetc($fp)$ echo $ch$ = 4ou can also read a single word at a time from a file using the fscanf function. The function takes a -ariable number of parameters, but the first two parameters are mandator". The first parameter is the file handle, the second parameter is a 0>st"le format string. /n" parameters passed after this are optional, but if used will contain the -alues of the format string. $listFile !list.t#t!$ ++ ?ee ne#t page for file contents if ('($fp fopen($listFile, !r!))) e#it(!(nable to open $listFile.!)$ while ('feof($fp)) 8 ++ /ssign -ariables to optional arguments $buffer fscanf($fp, !@s @s @d!, $name, $title, $age)$ if ($buffer A) ++ $buffer contains the number of items it was able to assign print !$name $title $age6br7Bn!$ = Here is the file list.t#t2 Ca-e Programmer A; ?ue Cesigner 9< 3isa Programmer 9D 1igel (ser <D 4ou can also store the -ariables in an arra" b" omitting the optional parameters in fscanf2 while ('feof($fp)) 8 $buffer fscanf($fp, !@s @s @d!)$ ++ /ssign -ariables to an arra" ++ (se the list function to mo-e the -ariables from the arra" into -ariables list($name, $title, $age) $buffer$ print !$name $title $age6br7Bn!$ = 4ou can read in an entire file with the fread function. %t reads a number of b"tes from a file, up to the end of the file (whiche-er comes first). The filesize function returns the size of the file in b"tes, and can be used with the fread function, as in the following e#ample. $listFile !m"file.t#t!$ if ('($fp fopen($listFile, !r!))) e#it(!(nable to open the input file, $listFile.!)$ $buffer fread($fp, filesize($listFile))$ echo !$buffer6br7Bn!$ fclose($fp)$ 4ou can also use the file function to read the entire contents of a file into an arra" instead of opening the file with fopen2 $arra" file(Efilename.t#tF)$ 5ach arra" element contains one line from the file, where each line is terminated b" a newline. Writing to Files The fwrite function is used to write a string, or part of a string to a file. The function takes three parameters, the file handle, the string to write, and the number of b"tes to write. %f the number of b"tes is omitted, the whole string is written to the file. %f "ou want the lines to
appear on separate lines in the file, use the Bn character. 1ote2 ,indows reGuires a carriage return character as well as a new line character, so if "ou.re using ,indows, terminate the string with BrBn. The following e#ample logs the -isitor to a file, then displa"s all the entries in the file. 6Hphp $logFile !stats.t#t!$ $fp fopen($logFile, !a*!)$ ++ Ipen the file in append+read mode $userCetails $J?5)K5)LEHTTPJ(?5)J/M51TFN$ ++ 0reate a string containing user details if (isset($J?5)K5)LEHTTPJ)5F5)5)FN)) $userCetails . ! 8$J?5)K5)LEHTTPJ)5F5)5)FN=6br7BrBn!$ else $userCetails . !6br7BrBn!$ fwrite($fp, !$userCetails!)$ ++ ,rite the user details to the file rewind($fp)$ ++ Oo-e the file pointer to the start of the file $entries &$ while('feof($fp)) 8 ++ Cispla" each line in the file $buffer fgets($fp, <&9;)$ if ($buffer ' !!) 8 echo $buffer$ $entries**$ = = ++ ?how a summar" echo !There are $entries entries in the log file6br7!$ fclose ($fp)$
H7
oc!ing Files boolean flock ( resource fp, integer operation) PHP supports a portable wa" of locking complete files in an ad-isor" wa" (which means all accessing programs ha-e to use the same wa" of locking or it will not work). %f there is a possibilit" that more than one process could write to a file at the same time then the file should be locked. flock() operates on fp which must be an open file pointer. operation is one of the following2 P To acGuire a shared lock (reader), set operation to 3I0QJ?H P To acGuire an e#clusi-e lock (writer), set operation to 3I0QJ5R P To release a lock (shared or e#clusi-e), set operation to 3I0QJ(1 P %f "ou don.t want flock() to block while locking, add 3I0QJ1S to 3I0QJ?H or 3I0QJ5R ,hen obtaining a lock, the process ma" block. That is, if the file is alread" locked, it will wait until it gets the lock to continue e#ecution. flock() allows "ou to perform a simple reader+writer model which can be used on -irtuall" e-er" platform (including most (ni# deri-ati-es and e-en ,indows). flock() returns T)(5 on success and F/3?5 on error (e.g. when a lock could not be acGuired). Here is a script that writes to a log file with the fputs function and then displa"s the log fileFs contents2 6Hphp $fp fopen(T+tmp+log.t#tU, TaU)$ flock($fp, 3I0QJ5R)$ ++ get lock fputs($fp, date(Th2i / l F d?, 4BnU))$ ++ add a single line to the log file flock($fp, 3I0QJ(1)$ ++ release lock fclose($fp)$ echo T6pre7U$ ++ dump log readfile(T+tmp+log.t#tU)$ echo T6+pre7BnU$ H7 Other "sef#l File F#nctions The opendir function returns a director" handle$ closedir closes a director"$ readdir reads a director" entr".
$m"Cirector" opendir(T.U)$ ++ use the current director" while($entr"name readdir($m"Cirector")) 8 echo T6tr7U$ echo T6td7$entr"name6+td7U$ echo T6td align BUrightBU7U$ echo filesize($entr"name)$ ++ the filesize function returns the file size in b"tes echo T6+td7U$ echo T6+tr7BnU$ = closedir($m"Cirector")$ The isJdir function tests if a filename refers to a director"2 if(isJdir($filename)) echo $filename . T is a director"U$ The isJfile function determines if a filename refers to a file2 if(isJfile($filename)) echo $filename . T is a fileU$ The isJreadable function returns T)(5 if the file e#ists and it is readable, otherwise it returns false. In (ni#+3inu# this is determined b" the fileFs permissions. In ,indows, T)(5 is alwa"s returned if the file e#ists. if(isJreadable($filename)) echo $filename . T is readableU$ The isJwritable function determines whether the ser-er will allow "ou to write data to the file before "ou attempt to open it2 if(isJwritable(E..+Guotes.t#tF)) 8 ++ attempt to open the file and write to it = else 8 echo EThe file is not writableF$ =