https://wiki.uniformserver.com/index.php?title=PHP_CLI:_Files&feed=atom&action=historyPHP CLI: Files - Revision history2024-03-29T01:16:53ZRevision history for this page on the wikiMediaWiki 1.41.0https://wiki.uniformserver.com/index.php?title=PHP_CLI:_Files&diff=3823&oldid=prevRic: New page: {{Uc nav 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 del...2009-08-15T09:55:31Z<p>New page: {{Uc nav 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 del...</p>
<p><b>New page</b></p><div>{{Uc nav PHP CLI}}<br />
'''''CLI Files'''''<br />
<br />
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.<br />
<br />
This page provides working example code snippets, although Uniform Server specific are general enough for use in other applications. <br />
<br />
== Initial test setup ==<br />
Edit our two test files '''Run.bat''' and '''test_1.php''' contained in folder UniServer to have the following content:<br />
{|<br />
|-<br />
|'''''Run.bat'''''||'''''test_1.php''''';<br />
|-valign="top"<br />
|<br />
<pre><br />
TITLE CLI TEST BAT<br />
COLOR B0<br />
@echo off<br />
cls<br />
echo.<br />
usr\local\php\php.exe -n test_1.php<br />
echo.<br />
pause<br />
</pre><br />
|<br />
<pre><br />
<?php<br />
$fileName = "z_test_1.txt"; // File to check for<br />
if(file_exists($fileName)){ // Does file exist<br />
echo " Found file $fileName \n"; // yes: Inform user<br />
}<br />
else{ // no:<br />
echo " File $fileName not found\n"; // Inform user<br />
}<br />
exit(0);<br />
?><br />
</pre><br />
|}<br />
Run the batch file (double click on '''Run.bat''') Expected result file not found.<br />
<br />
'''''Note'':''' UniServer Mona users change path to '''udrive\'''usr\local\php\php.exe -n test_1.php<br />
<br />
'''''[[#top | Top]]'''''<br />
<br />
== Create File ==<br />
Modify test_1.php to have the following content:<br />
{|<br />
|-<br />
|'''''test_1.php'''''||&nbsp;<br />
|-valign="top"<br />
|<br />
<pre><br />
<?php<br />
$fileName = "z_test_1.txt"; // File to check for<br />
if(file_exists($fileName)){ // Does file exist<br />
echo " Found file $fileName \n"; // yes: Inform user<br />
}<br />
else{ // no:<br />
echo " File $fileName not found \n"; // Inform user<br />
<br />
$FileHandle = fopen($fileName, 'w'); // Create file<br />
fclose($FileHandle); // Close file handle<br />
<br />
echo " File $fileName created \n"; // Inform user<br />
}<br />
exit(0);<br />
?><br />
</pre><br />
|<br />
<br><br />
Run the batch file (double click on Run.bat)<br />
<br />
File not found so it is created and user informed accordingly.<br />
<br />
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.<br />
<br />
Function '''fopen''' returns a '''file handle''' (reference to that file) this is saved to variable $FileHandle.<br />
<br />
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. <br />
|}<br />
'''''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.<br />
<br />
'''''Basic ways to open a file'':'''<br />
{|<br />
|-<br />
|* 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. <br />
|-<br />
|* Read: ||''''r''''|| Open a file for read.<br />
|-<br />
|* Write: ||''''w''''|| Open a file for write. If file does not exist create it. Data in the file is erased before writing new data. <br />
|}<br />
'''''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:<br />
<br />
'''$FileHandle = fopen($fileName, 'w') or die("can't open file");'''<br />
<br />
''To reduce line size I have not included this in the following examples.'' <br />
<br />
'''''Note 3'':''' Unless you specify a path the file is created in the current working folder generally where the scripts resides. <br />
<br />
'''''[[#top | Top]]'''''<br />
<br />
== Delete File - unlink() ==<br />
Modify test_1.php to have the following content:<br />
{|<br />
|-<br />
|'''''test_1.php'''''||&nbsp;<br />
|-valign="top"<br />
|<br />
<pre><br />
<?php<br />
$fileName = "z_test_1.txt"; // File to check for<br />
if(file_exists($fileName)){ // Does file exist<br />
echo " Found file $fileName \n"; // yes: Inform user<br />
unlink($fileName); // Delete file<br />
echo " File $fileName deleted \n"; // Inform user<br />
}<br />
else{ // no:<br />
echo " File $fileName not found \n"; // Inform user<br />
}<br />
exit(0);<br />
?><br />
</pre><br />
|<br />
<br><br />
Run the batch file (double click on '''Run.bat''')<br />
<br />
Check file '''z_test_1.txt''' has been '''deleted'''.<br />
<br />
PHP does not have a delete function instead it uses a function named '''unlink()''' <br />
|}<br />
'''''[[#top | Top]]'''''<br />
<br />
== File Write - fwrite() ==<br />
{|<br />
|-valign="top"<br />
|<br />
'''fwrite(file,string,length)'''<br />
|<br />
* '''file''' - Required. Specifies the open file to write to<br />
* '''string''' - Required. Specifies the string to write to the open file<br />
* '''length''' - Optional. Specifies the maximum number of bytes to write<br />
|<br />
* fwrite() writes to an open file.<br><br />
* This function is binary-safe<br />
* Returns number of bytes written, or FALSE on failure <br />
|}<br />
<br />
Modify test_1.php to have the following content:<br />
{|<br />
|-<br />
|'''''test_1.php'''''||&nbsp;<br />
|-valign="top"<br />
|<br />
<pre><br />
<?php<br />
$fileName = "z_test_1.txt"; // File to write to<br />
$Data1 = "This is test file $fileName\n"; // Data to write<br />
$Data2 = "Current location\n"; // Data to write<br />
$path = dirname(__FILE__)."\n"; // Save this to a variable<br />
<br />
$fh = fopen($fileName, 'w'); // Open for write save file handle <br />
fwrite($fh, $Data1); // Write to file<br />
fwrite($fh, $Data2); // Write to file<br />
fwrite($fh, $path); // Write to file<br />
fclose($fh); // close file handle<br />
<br />
echo "\n === END ===\n";<br />
exit(0);<br />
?><br />
</pre><br />
|<br />
<br><br />
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.<br />
<br />
Open file z_test_1.txt and check its content.<br />
<br />
Change $Data1 and $Data2 text, run the batch file again, note the file is '''overwritten''' with new data. <br />
|}<br />
<br />
'''''[[#top | Top]]'''''<br />
<br />
=== File Append ===<br />
Modify test_1.php to have the following content:<br />
{|<br />
|-<br />
|'''''test_1.php'''''<br />
|-valign="top"<br />
|<br />
<pre><br />
<?php<br />
$fileName = "z_test_1.txt"; // File to write to<br />
$Data1 = "More data 1\n"; // Data to write<br />
<br />
$fh = fopen($fileName, 'a') or die("can't open file"); // Open for append save file handle <br />
fwrite($fh, $Data1); // Write variable to file<br />
fwrite($fh, "More data 2 \n"); // Write string to file<br />
<br />
fclose($fh); // close file handle<br />
echo "\n === END ===\n";<br />
exit(0);<br />
?><br />
</pre><br />
|}<br />
Run the batch file (double click on Run.bat) <br />
<br />
Open file z_test_1.txt and check its content, note new data added to end of file.<br />
<br />
'''''[[#top | Top]]'''''<br />
<br />
== File Read - fread() ''Into a variable'' ==<br />
{|<br />
|-valign="top"<br />
|<br />
'''fread(file,length)'''<br />
|<br />
* '''file''' - Required. Specifies the open file to read from.<br />
* '''length''' - Required. Specifies the maximum number of bytes to read<br />
|<br />
* fread() reads from an open file.<br />
* This function is binary-safe<br />
* Returns read string, or FALSE on failure. <br />
|}<br />
<br />
'''Modify''' test_1.php to have the following content:<br />
{|<br />
|-<br />
|'''''test_1.php'''''||&nbsp;<br />
|-valign="top"<br />
|<br />
<pre><br />
<?php<br />
$fileName = "z_test_1.txt"; // File to read<br />
<br />
$fh = fopen($fileName, 'r'); // Open file for read<br />
$Data = fread($fh, filesize($fileName)); // Read all data into variable<br />
fclose($fh); // close file handle<br />
echo $Data; // Display data<br />
<br />
echo "\n === END ===\n";<br />
exit(0);<br />
?><br />
</pre><br />
|<br />
<br><br />
Run the batch file (double click on Run.bat) <br />
<br />
Content of file is displayed.<br />
<br />
I have assumed you have not deleted z_test_1.txt<br />
<br />
and it contains content from the previous test. <br />
<br />
|}<br />
'''''[[#top | Top]]'''''<br />
<br />
== File Read - file() ''Into array'' ==<br />
{|<br />
|-valign="top"<br />
|<br />
'''file(path,include_path,context)'''<br />
|<br />
* '''file''' - Required. Specifies the file to read.<br />
* '''include_path''' - Optional. Set to '1' search in include_path<br />
* '''context''' - Optional. Context of file handle.<br />
|<br />
* file() '''reads a file into an array'''.<br />
* Each array element contains a single line '''including newline''' character from the file.<br />
* This function is binary-safe.<br />
* Returns FALSE on failure. <br />
|}<br />
<br />
'''Modify''' test_1.php to have the following content:<br />
{|<br />
|-<br />
|'''''test_1.php'''''||&nbsp;<br />
|-valign="top"<br />
|<br />
<pre><br />
<?php<br />
// === Get Apache listening port ====================================================<br />
$filename='./usr/local/apache2/conf/httpd.conf'; // Apache config file<br />
<br />
if ($filearray=file($filename)) { // read file into array<br />
foreach ($filearray as $txt) { // scan array for port<br />
if(preg_match("/^Listen\s+(\d+)/", $txt,$matches)){ // check $text line save $matches <br />
$apache_port = $matches[1]; // match found save port number<br />
echo "\n Apache port = $apache_port \n"; // inform user<br />
break; // give up nothing else to do<br />
}<br />
}<br />
}<br />
<br />
else { // failed to read file<br />
echo "Failed! Cannot read the file"; // inform user<br />
}<br />
// === END Get Apache listening port ===================================================<br />
exit(0);<br />
?><br />
</pre><br />
|<br />
<br><br />
Run the batch file (double click on '''Run.bat''') <br />
<br />
Reads file into array.<br />
<br />
Array scanned line-by-line. If a match found exit using break.<br />
<br />
Displays Apache listening port or failed.<br />
|}<br />
<br />
'''''Note'':''' UniServer Mona users change path to<br />
<br />
$filename='.'''/udrive'''/usr/local/apache2/conf/httpd.conf'; // Apache config file<br />
'''''[[#top | Top]]'''''<br />
<br />
== General Manipulation ==<br />
<br />
=== File Copy - copy() ===<br />
{|<br />
|-valign="top"<br />
|<br />
'''copy(file,to_file)'''<br />
|<br />
* '''file''' - Required. Specifies the file to copy.<br />
* '''to_file''' - Required. Specifies the file to copy to.<br />
<br />
|<br />
* copy() function copies a file<br />
* If destination file exists will be overwritten<br />
* Returns TRUE on success and FALSE on failure <br />
|}<br />
'''''[[#top | Top]]'''''<br />
<hr><br />
=== Directory - mkdir() ===<br />
{|<br />
|-valign="top"<br />
|<br />
'''mkdir(path,mode,recursive,context)'''<br />
|<br />
* '''path''' - Required. Specifies the name of the directory (folder) to create<br />
* '''mode''', '''recursive''', '''context''' - Optional. <br />
|<br />
* mkdir() function creates a directory (folder)<br />
* Returns TRUE on success, or FALSE on failure. <br />
|}<br />
*mkdir("./udrive/fred1/me"); -- Will fail if udrive and fred1 do not exist <br />
*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 <br />
'''''[[#top | Top]]'''''<br />
<hr><br />
<br />
=== Directory - rmdir() ===<br />
{|<br />
|-valign="top"<br />
|<br />
'''rmdir(dir,context)'''<br />
|<br />
* '''dir''' - Required. Specifies the directory to be removed<br />
* '''context''' - Optional. <br />
|<br />
* rmdir() function removes an '''empty''' directory (folder)<br />
* Returns TRUE on success, or FALSE on failure. <br />
|}<br />
'''''[[#top | Top]]'''''<br />
<br />
== Summary ==<br />
The above is intended to get you started by providing a few pieces of working code.<br />
<br />
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.<br />
<br />
There are times when you will want to update certain pieces of information in a file. <br />
<br />
The next page covers file [[PHP CLI: Files Search and Replace| '''Search and Replace''']]<br />
<br />
'''''[[#top | Top]]'''''<br />
<br />
----<br />
<br />
{| <br />
| [[Image:uc_small_logo.gif]] || '''MPG''' (Ric)<br />
|}<br />
<br />
[[Category: Tutorials]]<br />
[[Category: How To]]<br />
[[Category: Uniform Server 5.0-Nano]]</div>Ric