PHP CLI: Files

From The Uniform Server Wiki
Jump to navigation Jump to search

 

MPG UniCenter

UniServer 5.0-Nano
PHP CLI.

CLI Files

One reason for learning a scripting language is to have the capability to manipulate files. This includes mundane tasks such as create, move and delete to more powerful tasks like recursive search and replace text.

This page provides working example code snippets, although Uniform Server specific are general enough for use in other applications.

Initial test setup

Edit our two test files Run.bat and test_1.php contained in folder UniServer to have the following content:

Run.bat test_1.php;
TITLE CLI TEST BAT
COLOR B0
@echo off
cls
echo.
usr\local\php\php.exe -n test_1.php
echo.
pause
<?php
$fileName = "z_test_1.txt";          // File to check for
if(file_exists($fileName)){          // Does file exist
 echo " Found file $fileName \n";    // yes: Inform user
}
else{                                // no:
 echo " File $fileName not found\n"; // Inform user
}
exit(0);
?>

Run the batch file (double click on Run.bat) Expected result file not found.

Note: UniServer Mona users change path to udrive\usr\local\php\php.exe -n test_1.php

Top

Create File

Modify test_1.php to have the following content:

test_1.php  
<?php
$fileName = "z_test_1.txt";           // File to check for
if(file_exists($fileName)){           // Does file exist
 echo " Found file $fileName \n";     // yes: Inform user
}
else{                                 // no:
 echo " File $fileName not found \n"; // Inform user

 $FileHandle = fopen($fileName, 'w'); // Create file
 fclose($FileHandle);                 // Close file handle

 echo " File $fileName created \n";   // Inform user
}
exit(0);
?>


Run the batch file (double click on Run.bat)

File not found so it is created and user informed accordingly.

To create a file use function fopen for writing (or appending) if the file does not exist it is created. Function requires two arguments, a file name $fileName and what we want to do "w" write to file.

Function fopen returns a file handle (reference to that file) this is saved to variable $FileHandle.

We don’t really want to perform a write operation on this file the act of opening a file for writing creates a file, which is what we wanted to achieve. However you must always close an open file using function fclose() it takes a single argument the file handle.

Note 1: You would not specifically create a file since its implied when you open a file for writing or appending, if it does not exist it is created.

Basic ways to open a file:

* Append: 'a' Opens a file for write. If file does not exist create it. Data is preserved new data is written at the end of the file.
* Read: 'r' Open a file for read.
* Write: 'w' Open a file for write. If file does not exist create it. Data in the file is erased before writing new data.

Note 2: It is bad programming to use this $FileHandle = fopen($fileName, 'w'); if for whatever reason a file cannot be opened you need to bail out. Hence the following is the correct way to open and and check the file status:

$FileHandle = fopen($fileName, 'w') or die("can't open file");

To reduce line size I have not included this in the following examples.

Note 3: Unless you specify a path the file is created in the current working folder generally where the scripts resides.

Top

Delete File - unlink()

Modify test_1.php to have the following content:

test_1.php  
<?php
$fileName = "z_test_1.txt";           // File to check for
if(file_exists($fileName)){           // Does file exist
 echo " Found file $fileName \n";     // yes: Inform user
 unlink($fileName);                   // Delete file
 echo " File $fileName deleted \n";   // Inform user
}
else{                                 // no:
 echo " File $fileName not found \n"; // Inform user
}
exit(0);
?>


Run the batch file (double click on Run.bat)

Check file z_test_1.txt has been deleted.

PHP does not have a delete function instead it uses a function named unlink()

Top

File Write - fwrite()

fwrite(file,string,length)

  • file - Required. Specifies the open file to write to
  • string - Required. Specifies the string to write to the open file
  • length - Optional. Specifies the maximum number of bytes to write
  • fwrite() writes to an open file.
  • This function is binary-safe
  • Returns number of bytes written, or FALSE on failure

Modify test_1.php to have the following content:

test_1.php  
<?php
$fileName = "z_test_1.txt";               // File to write to
$Data1 = "This is test file $fileName\n"; // Data to write
$Data2 = "Current location\n";            // Data to write
$path = dirname(__FILE__)."\n";           // Save this to a variable

$fh = fopen($fileName, 'w');       // Open for write save file handle 
fwrite($fh, $Data1);               // Write to file
fwrite($fh, $Data2);               // Write to file
fwrite($fh, $path);                // Write to file
fclose($fh);                       // close file handle

echo "\n === END ===\n";
exit(0);
?>


Run the batch file (double click on Run.bat) The file was deleted in the previous example hence it is first create and then data written to it.

Open file z_test_1.txt and check its content.

Change $Data1 and $Data2 text, run the batch file again, note the file is overwritten with new data.

Top

File Append

Modify test_1.php to have the following content:

test_1.php
<?php
$fileName = "z_test_1.txt";                            // File to write to
$Data1 = "More data 1\n";                              // Data to write

$fh = fopen($fileName, 'a') or die("can't open file"); // Open for append save file handle 
fwrite($fh, $Data1);                                   // Write variable to file
fwrite($fh, "More data 2 \n");                         // Write string to file

fclose($fh);                                           // close file handle
echo "\n === END ===\n";
exit(0);
?>

Run the batch file (double click on Run.bat)

Open file z_test_1.txt and check its content, note new data added to end of file.

Top

File Read - fread() Into a variable

fread(file,length)

  • file - Required. Specifies the open file to read from.
  • length - Required. Specifies the maximum number of bytes to read
  • fread() reads from an open file.
  • This function is binary-safe
  • Returns read string, or FALSE on failure.

Modify test_1.php to have the following content:

test_1.php  
<?php
$fileName = "z_test_1.txt";              // File to read

$fh = fopen($fileName, 'r');             // Open file for read
$Data = fread($fh, filesize($fileName)); // Read all data into variable
fclose($fh);                             // close file handle
echo $Data;                              // Display data
                                           
echo "\n === END ===\n";
exit(0);
?>


Run the batch file (double click on Run.bat)

Content of file is displayed.

I have assumed you have not deleted z_test_1.txt

and it contains content from the previous test.

Top

File Read - file() Into array

file(path,include_path,context)

  • file - Required. Specifies the file to read.
  • include_path - Optional. Set to '1' search in include_path
  • context - Optional. Context of file handle.
  • file() reads a file into an array.
  • Each array element contains a single line including newline character from the file.
  • This function is binary-safe.
  • Returns FALSE on failure.

Modify test_1.php to have the following content:

test_1.php  
<?php
// === Get Apache listening port ====================================================
 $filename='./usr/local/apache2/conf/httpd.conf';        // Apache config file

 if ($filearray=file($filename)) {                       // read file into array
   foreach ($filearray as $txt) {                        // scan array for port
    if(preg_match("/^Listen\s+(\d+)/", $txt,$matches)){  // check $text line save $matches  
      $apache_port =  $matches[1];                       // match found save port number
      echo "\n Apache port = $apache_port \n";           // inform user
      break;                                             // give up nothing else to do
    }
   }
 }

 else {                                                  // failed to read file
   echo "Failed! Cannot read the file";                  // inform user
 }
// === END Get Apache listening port ===================================================
exit(0);
?>


Run the batch file (double click on Run.bat)

Reads file into array.

Array scanned line-by-line. If a match found exit using break.

Displays Apache listening port or failed.

Note: UniServer Mona users change path to

$filename='./udrive/usr/local/apache2/conf/httpd.conf'; // Apache config file Top

General Manipulation

File Copy - copy()

copy(file,to_file)

  • file - Required. Specifies the file to copy.
  • to_file - Required. Specifies the file to copy to.
  • copy() function copies a file
  • If destination file exists will be overwritten
  • Returns TRUE on success and FALSE on failure

Top


Directory - mkdir()

mkdir(path,mode,recursive,context)

  • path - Required. Specifies the name of the directory (folder) to create
  • mode, recursive, context - Optional.
  • mkdir() function creates a directory (folder)
  • Returns TRUE on success, or FALSE on failure.
  • mkdir("./udrive/fred1/me"); -- Will fail if udrive and fred1 do not exist
  • mkdir("./udrive/fred1/me", 0777, true); -- recursive=true if udrive and fred1 do not exist are created. Note: 0777 dummy value required but ignored by Windows

Top


Directory - rmdir()

rmdir(dir,context)

  • dir - Required. Specifies the directory to be removed
  • context - Optional.
  • rmdir() function removes an empty directory (folder)
  • Returns TRUE on success, or FALSE on failure.

Top

Summary

The above is intended to get you started by providing a few pieces of working code.

If you are running UniServer Nano run server status, Apache port displayed was extract by a function similar to the above as were the other ports displayed.

There are times when you will want to update certain pieces of information in a file.

The next page covers file Search and Replace

Top


MPG (Ric)