Breaking News

IPU BCA Semester 5: Web Based Programming - Simple PHP File Handling Script (#PHPProgramming)(#ipumusings)

Simple PHP File Handling Script

IPU BCA Semester 5: Web Based Programming - Simple PHP File Handling Script

Question: Write a PHP-script to open, close, read and write into a file.

Answer:

PHP provides a good number of file handling in-built functions. A few are:

file_exists( ): The function checks if file exists then it returns TRUE else FALSE boolean value is returned.

fopen( ): The api is used to open files for reading or writing or both. It accepts two arguments i.e. first is the filename (along with optional path) and second argument is mode to open file. It returns a file handle.

e.g. $filehandle = fopen('myfile.text', 'w');

The various mode values are:

r : Opens a file for reading only. It places the file pointer at the beginning of the file.

r+ : Opens a file for reading and writing, and places the file pointer at the start of the file.

w  : Opens a file for writing only, and places the file pointer at the start of the file.

w+ : Opens a file for writing and reading, and places the file pointer at the start of the file.

a : Opens the file for writing (append) only, and places the file pointer at the end of the file.

a+ : Opens the file for reading and writing, and places the file pointer at the end of the file.

b : To open binary files, generally used alongwith other mode values e.g. wb+




fread( ): to read the contents (in bytes) of a file. If you’re trying to read a file over a network link
fgets() function is a better option.

filesize( ): returns the size of the file.

fwrite( ): to write the number of bytes to a file.

fclose( ): closes the opened file.

Here is a PHP script which opens a file, reads its content, displays it, writes a line and closes the file.

<?php
 $filename = 'dummy.txt';
 if (!file_exists($filename)) 
  echo 'File does not exist';
 else
 {
  $filehandle = fopen($filename, "wb+") or die ("Cannot open file");
  // read its content and display
  $dataStr = fread($filehandle, filesize($filename));
  echo $dataStr;
  $flag = fwrite($filehandle, 'This is a test line');
  if (!$flag == FALSE) die('Fatal error: could not write to file.');
  fclose($filehandle);
 }
?>