Studyon Minte9.com
ZCE 5.3

Study

Accesing Files



        // two types of streams: files & network
	// handler: reference to an external resourse	

	// fopen - x+ (creates, r, w); w+b (binary safe); w truncates
	// fgets($fd, 1); // new line
	// rewind($fd); // reset position of pointer
	// while(!feof($fd)) {} // may return FALSE
	// fread($fd, 1); // don't care about n (uses end of file)
	// file_exists: true/false
	// fseek($fd, 2); // pointer at 2
	// ftell($fd); // tell the current position
	// while($row = fgetcsv($fd)) {} // row will be array
	// fputcsv // reverse of fgetcsv
	// fpassthru - output from pointer

	// readfile() - outputs a file (header("Content-type: application/pdf)
	// file() - read file into an array
	// file_get_contents() - all file in a string (file OR URI)
	// file_put_contents() - write to a file / FILE_APPEND

	// clearstatcache() - clear stats about a file
	// stat($file) - $stat['mtime']
	// fstat($file) - like stat but with pointer
	// flock($fp, LOCK_UN) - unlock
	// is_writeable($fd)
	// fscanf($fd, "%st%s") on file; like sscanf on strings

There are two types of streams (files & network). 

	- php.* - standard PHP input/output
	- file - standard file access
	- http - access to remote resources via HTTP
	- ftp - access to remote resources via FTP
	- compress.zlib - access to compressed data stream using the zlib library

fopen() - open a file

<?php $filename = "counter.txt"; $counter = 0; if ($fd = @fopen($filename, "r")) { // --- Look Here --- // $counter = (int) fgets($fd); // gets first line content fclose($fd); } $fw = fopen($filename, "w+"); // open for reading and writing // --- Look Here --- // fwrite($fw, ++$counter); // writes new counter value fclose($fw); echo "There has been $counter hits to this page"; /* r - reading only (pointer at the beginning of the file) r+ - reading and writing (pointer at the beginning) w - writing only w+ - writing and reading a - writing only (pointer at the end) a+ - reading and writing (pointer at the end) x - creates a new file for writing only x+ - creates a new file for writing and reading w+b - forces binary mode (unaltered date will be written) w+t - windows only (Unix n will be converted to Windows rn) w, w+, a, a+ - automaticaly create a new file if not exists x, x+ - throw a worning if the file exists */
  fgets() - gets line from file pointer
<?php $file = "file.txt"; if ($fd = fopen($file, "w+")) { fwrite($fd, "aaarn"); fwrite($fd, "bbb"); fclose($fd); } if ($fd = fopen($file, "r")) { $aLine = fgets($fd); // 1024 byte length (default) // --- Look Here --- // echo $aLine . "<br>"; // Outputs: aaa rewind($fd); // --- Look Here --- // $aByte = fgets($fd, 1); // 1 byte length echo "^{$aByte}$" . "<br>"; // Outputs: ^$ (new line character) rewind($fd); $aByte2 = fgets($fd, 2); // 2 bytes echo "^{$aByte2}$" . "<br>"; // Outputs: ^a$ rewind($fd); $aByte5 = fgets($fd, 5); // 5 bytes echo "^{$aByte5}$" . "<br>"; // Outputs: ^aaar $ }
  feof() - determines when the internal pointer hits the end of a file
<?php $file = "file.txt"; if ($fd = fopen($file, "w+")) { fwrite($fd, "aaarn"); fwrite($fd, "bbb"); fclose($fd); } if ($fd = fopen($file, "r")) { $buffer = ""; while(!feof($fd)) { // --- Look Here --- // $buffer .= fgets($fd); } echo $buffer; // Outputs: aaa bbb }
  fread() - read arbitrary data from a file
<?php // Unlike fgets(), it does not concern itself with newline characters $file = "file.txt"; if ($fd = fopen($file, "w+")) { fwrite($fd, "aaarn"); fwrite($fd, "bbb"); fclose($fd); } if ($fd = fopen($file, "r")) { $contents = fread($fd, filesize($file)); // --- Look Here --- // echo $contents . "<br>"; // Output: aaa bbb rewind($fd); echo fread($fd, 2) . "<br>"; // Output: aa rewind($fd); echo fread($fd); // Outpus: Warning ! }
  file_exists() - Checks whether a file or directory exists (returns TRUE/FALSE)
<?php if (!file_exists('paht/to/foo.txt')) { throw new Exception ("The file does not exists"); }
  fseek() - Seeks on a file pointer
<?php if ($fd = fopen("file.txt", "w+")) { fwrite($fd, "abcrn"); fwrite($fd, "def"); fclose($fd); } if ($fd = fopen("file.txt", "r")) { fseek($fd, 2); // advance 2 chars // --- Look Here --- // echo fgets($fd) . "<br>"; // Outputs: c fseek($fd, 2, SEEK_SET); // default (go to begging of the file) echo fgets($fd) . "<br>"; // Outputs: c fseek($fd, 0, SEEK_CUR); // start from current position echo fgets($fd) . "<br>"; // Outputs: def fseek($fd, -2, SEEK_END); // start from the end of the file echo fgets($fd) . "<br>"; // Outputs: ef }
  ftell() - Returns the current position of the file read/write pointer (or FALSE)
<?php $fd = fopen("example.txt", "r"); fseek($fd, 2); echo ftell($fd); // Output: 2
 
<?php $fd = fopen("example.txt", "r"); $data = fgets($fd, 2); echo ftell($fd); // Output: 1
  fgetcsv() - Gets line from file pointer and parse for CSV fields
<?php // Reads a row from a previously opened CSV file // into an enumerative array $fd = fopen("example.csv", "r"); while($row = fgetcsv($fd)) { print_r($row); // Array ( [0] => aa [1] => bb [2] => cc ) // Array ( [0] => dd [1] => ee [2] => ff ) }
  fputcsv() - Writes the elements of an array in CSV format to an open file handle
<?php $fd = fopen("example.csv", "w"); $arr = array(1,2,3); fputcsv($fd, $arr); // Output: 1,2,3 $arr = array('a', 'b', 'c'); fputcsv($fd, $arr, ";"); // Output: a;b;c $arr = array('"a"', '"b"', '"c"'); fputcsv($fd, $arr, ";"); // Output: """a""";"""b""";"""c""" $arr = array('"a"', '"b"', '"c"'); fputcsv($fd, $arr, ";", "'"); // default delimiter: " // Output: "a";"b";"c"
  fpassthru Reads all data from the current position in an open file, until EOF, and writes the result to the output buffer.
<?php /* -- example.txt aaa bbb ccc */ $file = fopen("example.txt","r"); fgets($file); // Read first line fpassthru($file); // Send rest of the file to the output buffer // Outputs: aaa rn bbb fclose($file);
  readfile() - Outputs a file
<?php // This is useful when you need to include static files, // as it offer smuch better performance and resource utilization than C-style functions header("Content-type: application/pdf"); readfile("zce-php.pdf");
  file() - read a file into an array of lines
<?php /* --- example.txt -- aaa bbb ccc */ $arr = file("example.txt"); print_r($arr); // Array ( [0] => aaa [1] => bbb [2] => ccc )
  file_get_contents() - load an entire file into memory (returns the file as string)
<?php // Prior to PHP 4.3.0, it was common to use this function // together with implode() as a quick-and-dirty way to load an entire file into memory. // Old way $file = implode("r", file("example.txt")); // New way $file = file_get_contents("example.txt");
 
<?php $file = file_get_contents("http://studyon.minte9.com"); echo $file; // use urlencode for URI with special characters like space (?a=Hello World)
 
<?php /* --- example.txt -- aaa bbb ccc */ // Read 3 characters starting from 2st character $file = file_get_contents("example.txt", NULL, NULL, 2, 3); echo $file; // Outputs: a b (anb) // Second param can be: NULL, TRUE or FILE_USE_INCLUDE_PATH (php > 5) // Third param refers to Stream context
  file_put_contents() - allows you to write the contents of a PHP string to a file in one pass:
<?php $data = "My Data"; file_put_contents("example.txt", $data); // example.txt content is now: My Data // using flags $data = "My Data2"; file_put_contents("example.txt", $data, FILE_APPEND); // content now: My DataMy Data2 // LOCK_EX flag to prevent anyone else writing to the file at the same time file_put_contents("example.txt", "xxx", FILE_APPEND | LOCK_EX);
 
<?php // When using an array, will automatically apply the equivalent of implode('', $array) $data = array("xxx", "yyy", "zzz"); file_put_contents("example.txt", $data); // content_file: xxxyyyzzz
  clearstatcache() If you call file_exists() on a file that doesn't exist, it will return FALSE until you create the file. If you create the file, it will return TRUE even if you then delete the file. However unlink() clears the cache automatically.
<?php // Clears the information that PHP caches about a file $fw = fopen ("test.txt", "w"); fwrite ($fw, "test"); fclose ($fw); echo (int) file_exists("test.txt"); // Outputs: 1 unlink ("c:test.txt"); echo (int) file_exists ("test.txt"); // Outputs: 1 clearstatcache(); echo (int) file_exists ("test.txt"); // Outputs: 0
  stat()
<?php // Gives information about a file $stat = stat("example.txt"); echo 'Access time: ' . $stat['atime']; // file access time, // this is the same as calling fileatime() echo 'Modification time: ' . $stat['mtime']; // Print file modification time, // this is the same as calling filemtime() echo 'Device number: ' . $stat['dev']; // Print the device number
  fstat() Gets information about a file using an open file pointer. This function is similar to the stat() function except that it operates on an open file pointer instead of a filename.
<?php $fp = fopen("/etc/passwd", "r"); // open a file $fstat = fstat($fp); // gather statistics
  flock()
<?php // Lock a file $fp = fopen("example", "r+"); if (flock($fp, LOCK_EX)) { // exclusive lock ftruncate($fd); fwrite($fd, 'abc'); fflush($fd); // flush output before releasing the lock flock($fp, LOCK_UN); // release the lock } else { echo "Couldn't get the lock!"; }
  Atention: * Assigning another value to handle argument in subsequent code will release the lock. * On some operating systems flock() is implemented at the process level. You must remember that flock() uses a "cooperative" locking mechanism with one big assumption: that all other processes that want to access your file will also use flock(). Therefore, you can create a temporary directory and "hold it" until you have finished your I/O operations. is_writable()
<?php // Tells whether the filename is writable if (is_writable("example.txt")) { // OR is_writeable() echo 'The file is writable'; } else { echo 'The file is not writable'; }
  fscanf()
<?php // Parses input from a file according to a format // Similar to sscanf(), but it takes its input from a file associated with handle /* -- example.txt John Smith 24 Mary Jones 35 Tom Ferguson 45 */ $fp = fopen("example.txt", "r"); while($row = fscanf($fp, "%st%st%dn")) { list($surname, $name, $age) = $row; echo "{$name} {$age}"; break; // Outputs: Smith 24 } fclose($fp);