PHP: File I/O

  1. Overview
    1. Most PHP scripts save/load data to/from a file or database
    2. Later we will learn how to work with MySQL, a relational database
    3. Here we will learn how to work with text files
  2. Writing to a text file
    1. A PHP script is executed by the Apache web server process
    2. The process must have permission to write to the local file system
    3. You must first create the file in the public_html directory using WinSCP and give the file world-write permissions: -rw-rw-rw

      Properties dialog box showing Others with write permission
    4. Since everyone can write to the file, the Apache process can as well
    5. Example writing to a file
      // Open the file for writing or terminate if there is an error
      $outputFile = fopen("myfile.txt", "w") or 
      	die("Can't open myfile.txt for writing.");
      	
      // Write a string to the file
      fwrite($outputFile, "This is a test.\n");
      
      // Release the file connection
      fclose($outputFile);
      
      1. fileHandle = fopen(filename, mode) - Attempts to open the file in the given mode
        1. Returns a file handle on success or FALSE on error
        2. Modes include: "r" - reading, "w" - writing, "a" - appending, and others
      2. fwrite(fileHandle, string) - Writes the string to the file
      3. fclose(fileHandle) - Closes an open file handle
  3. Reading from a text file
    1. Example reading an entire file using file_get_contents
      // Read entire file into $file
      $file = file_get_contents("myfile.txt");
      
    2. Same function can make an HTTP request and retrieve the entire response
      // Read response into $homepage
      $homepage = file_get_contents("http://cs.harding.edu/");
      
    3. Example reading a single line from a text file
      $myfile = fopen("myfile.txt", "r") or die("Unable to open file!");
      $line = fgets($myfile);
      fclose($myfile);
      
    4. Reading until EOF is reached
      $myfile = fopen("myfile.txt", "r") or die("Unable to open file!");
      
      // Output one line at a time until EOF
      while(!feof($myfile)) {
        echo fgets($myfile) . "
      \n"; } fclose($myfile);