PHP CLI: Files
PHP CLI : Introduction | Paths | PHP INI | Process Running | Detached Processes | Hidden Process | User Input | Files | Search & Replace | Recursive Search & Replace
|
|
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
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); ?> |
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.
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); ?> |
Check file z_test_1.txt has been deleted. PHP does not have a delete function instead it uses a function named unlink() |
File Write - fwrite()
fwrite(file,string,length) |
|
|
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); ?> |
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. |
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.
File Read - fread() Into a variable
fread(file,length) |
|
|
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); ?> |
Content of file is displayed. I have assumed you have not deleted z_test_1.txt and it contains content from the previous test. |
File Read - file() Into array
file(path,include_path,context) |
|
|
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); ?> |
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) |
|
|
Directory - mkdir()
mkdir(path,mode,recursive,context) |
|
|
- 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
Directory - rmdir()
rmdir(dir,context) |
|
|
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
MPG (Ric) |