PHP File

File can store data and data stores on file can be permanent. We also can create a file template, and it can be a form or an email template. A file template defined variable that can be replaced. In this tutorial, you learn how to access file such as read, write, appending, or delete. Moreover, you learn how to replace string within a file, and you learn how to get the URL content. You also learn how to get records from database table and save them into file, and insert records from file to database table.

  • Open File for Read
  • Open File for Write
  • Append to the beginning of a file
  • Append to the end of the file
  • Get URL Content
  • Replace String within A file
  • Using Text File as Template

Introduction

FILE PATH: You need to know the different between Windows and Linux/Unix file path.

In window: $window = fopen(“c:\\direct\file.txt”,’r’);
In Linux/Unix: $linn = fopen(“/direct/file.txt”,’r’);

Possible modes for fopen()

A list of possible modes for fopen() using mode

mode

Description

‘r’ Open for reading only; place the file pointer at the beginning of the file.
‘r+’ Open for reading and writing; place the file pointer at the beginning of the file.
‘w’ Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
‘w+’ Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
‘a’ Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
‘a+’ Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
‘x’ Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.
‘x+’ Create and open for reading and writing; otherwise it has the same behavior as ‘x’.
‘c’ Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to ‘w’), nor the call to this function fails (as is the case with ‘x’). The file pointer is positioned on the beginning of the file. This may be useful if it’s desired to get an advisory lock (see flock()) before attempting to modify the file, as using ‘w’ could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested).
‘c+’ Open the file for reading and writing; otherwise it has the same behavior as ‘c’.

 How to use fopen()

<?php
$file1 = fopen("/home/yourname/file.txt","r");
$file2 = fopen("c:\\file.txt","r");
$file3 = fopen("http://infotek-solutions.com/","r");
$file4 = fopen("ftp://user:password@doaminexample.com/file.txt","w");
?>

Reading File:

Example:

<?php
$my_file = ‘test.txt’;
$lines = file($my_file);
foreach($lines as $line) {
echo $line . “<br/>”;
}
?>

test.txt:

Manual Testing (ERP, Billing, CRM, Java and dot net based applications testing)
Functional Automation Testing
Performance Testing
Setting Up QA Service For IT Company
QA Process Improvement
Specialized QA Testing – Mobile, ETL, Script Automation
IT Security Testing
Federal Software Testing
Systems & Embedded Testing

Output:

Manual Testing (ERP, Billing, CRM, Java and dot net based applications testing)
Functional Automation Testing
Performance Testing
Setting Up QA Service For IT Company
QA Process Improvement
Specialized QA Testing – Mobile, ETL, Script Automation
IT Security Testing
Federal Software Testing
Systems & Embedded Testing

Display File Information

We would like to get information about the file, such as file size, create date, permission, etc. The file permission is based on the linux file permission. Please remember that, you need to have a file in order to display the file information. If the file does not existed, it will display a warning or error. In addition, you will have a different file information according to the file you have.

Example:

<?php
$my_file = ‘test.txt’;
getFileInfo($my_file);
function getFileInfo($filename) {
if(!file_exists($filename)) {
echo “$filename does not exist <br/>”;
}
$exec_f = (is_executable($filename) ? “yes”:”no”);
$write_f = (is_writable($filename) ? “yes” : “no”);
$read_f = (is_readable($filename) ? “yes” : “no”);
$a_f = (is_file($filename) ? “yes”:”no”);
$d_f = (is_dir($filename) ? “yes”:”no”);
echo “$filename is .. <br/>”;
echo “Executable: “. $exec_f . “<br/>”;
echo “Writable: “. $write_f . “<br/>”;
echo “Readable:” . $read_f . “<br/>”;
echo “Is A file:” . $a_f . “<br/>”;
echo “Is A Directory:” . $d_f . “<br/>”;
echo “File Change time: “. date(“D, Y M d g:i A”,filectime($filename)) . “<br/>”;
echo “File Access time: “. date(“D, Y M d g:i A”,fileatime($filename)) . “<br/>”;
echo “File Update time: “. date(“D, Y M d g:i A”,filemtime($filename)) . “<br/>”;
echo “File Size: “. filesize($filename). “bytes or “. (filesize($filename)/1023).”M<br/>”;
echo “File Permission: ” .substr(base_convert(fileperms($filename), 10, 8), 3);
}
?>

Output:

test.txt is ..
Executable: no
Writable: yes
Readable:yes
Is A file:yes
Is A Directory:no
File Change time: Tue, 2015 Dec 22 1:20 PM
File Access time: Tue, 2015 Dec 22 1:20 PM
File Update time: Tue, 2015 Dec 22 1:20 PM
File Size: 329bytes or 0.32160312805474M
File Permission: 666

Reading a File from Bottom

Example:

<?php
$my_file = ‘test.txt’;
$lines = file($my_file);
for ($i = count($lines)-1; $i >= 0; $i–) {
echo “Index: $i “. $lines[$i].”<br/>”;
}
?>

Output:

Index: 8 Systems & Embedded Testing
Index: 7 Federal Software Testing
Index: 6 IT Security Testing
Index: 5 Specialized QA Testing – Mobile, ETL, Script Automation
Index: 4 QA Process Improvement
Index: 3 Setting Up QA Service For IT Company
Index: 2 Performance Testing
Index: 1 Functional Automation Testing
Index: 0 Manual Testing (ERP, Billing, CRM, Java and dot net based applications testing)

Delete File

We call an unlink function with the file name to delete a file.

<?php
// open a file for reading
$handler1 = fopen(“test.txt”,”r”);
// delete a file
unlink(“test.txt”);
?>

Read a file content (using fread function):

Example:

<?php
$file_name = ‘test.txt’;
$file_handler = fopen($file_name, ‘r’) or exit(‘can not open the file’);
$file_content = fread($file_handler, filesize($file_name));
fclose($file_handler);
echo $file_content;
?>

Output:

Manual Testing (ERP, Billing, CRM, Java and dot net based applications testing) Functional Automation Testing Performance Testing Setting Up QA Service For IT Company QA Process Improvement Specialized QA Testing – Mobile, ETL, Script Automation IT Security Testing Federal Software Testing Systems & Embedded Testing

Read a file content (using fgets function):

Example:

<?php
$file = fopen(‘test.txt’, ‘r’) or exit(‘unable to read the file’);
while (!feof($file)) {
echo fgets($file). ‘<br/>’;
}
fclose($file);
?>

Output:

Manual Testing (ERP, Billing, CRM, Java and dot net based applications testing)
Functional Automation Testing
Performance Testing
Setting Up QA Service For IT Company
QA Process Improvement
Specialized QA Testing – Mobile, ETL, Script Automation
IT Security Testing
Federal Software Testing
Systems & Embedded Testing

Write content to a file (Write Mode)

Example:

<?php
$file_handler = fopen(‘test1.txt’,’w’) or exit(‘unable to read the file’);
$content = ‘Provide skilled QA resources for various kind of software testing need.’;
fwrite($file_handler, $content);
fclose($file_handler);
?>

Write content to a file (Append Mode)

Example:

<?php
$file_name = ‘test1.txt’;
$file_handler = fopen($file_name, ‘a’) or exit(‘can not open the file’);
fwrite($file_handler, “QA Training For Fresher & Career Change\n”);
fclose($file_handler);
?>

Write content to a file (At Beginning)

Example:

<?php
$file_name = ‘test1.txt’;
$file_handler_1 = fopen($file_name, ‘r’) or exit(‘can not open file!’);
$file_content_1 = fread($file_handler_1, filesize($file_name));
fclose($file_handler_1);
$file_handler_2 = fopen($file_name, ‘w+’) or exit(‘can not open file!’);
$conent_string = “Global\n”;
$content_content = $conent_string . $file_content_1;
if (fwrite($file_handler_2, $content_content)) {
echo ‘successfully append to the file<br/>’;
} else {
echo ‘can not write to the file<br/>’;
}
fclose($file_handler_2);
?>

Replace some file content

Example:

<?php
$file_name = ‘test1.txt’;
$file_handler_1 = fopen($file_name, ‘r’) or exit(‘can not open file!’);
$file_content_1 = fread($file_handler_1, filesize($file_name));
$new_file_content = str_replace(‘QA’, ‘BA’, $file_content_1);
fclose($file_handler_1);
$file_handler_2 = fopen($file_name, ‘w+’) or exit(‘can not open file!’);
if (fwrite($file_handler_2, $new_file_content)) {
echo ‘successfully write to the file<br/>’;
} else {
echo ‘can not write to the file<br/>’;
}
fclose($file_handler_2);
?>

URL Content

Example:

<?php
$file = fopen(‘http://infotek-solutions.com/’,’r’);
$count_line=0;
while (!feof($file)) {
echo $count_line.’ ‘. htmlspecialchars(fgets($file)) . “<br/>”;
$count_line++;
}
fclose($file);
?>

Email Template

Example:

mail.txt

Hi [[:friend]],

How are you [[:friend]]? Today is [[:today]], I will go to class. Do you want to go with me?
There are many friend will go with us? Do you know [[:ourfriend]]?

I am looking forward to hear from you? My number is [[:phonenumber]].
We are ging to meet at [[:place]].

Thanks,
-[[:myname]]

Mail_Template.php

<?php
$file_name = ‘mail.txt’;
$array_email = array(‘[[:myname]]’=>’Jay’,'[[:friend]]’=>’Infotek’,'[[:today]]’=>’Sunday’,'[[:ourfriend]]’=>’QA’,'[[:phonenumber]]’=>’800-784-6129′,'[[:place]]’=>’Worldgate Hernden’);
$file_content_1 = file_get_contents($file_name);
$new_file_content = str_replace(array_keys($array_email), array_values($array_email), $file_content_1);
echo ‘<pre>’.$new_file_content . ‘</pre>’;
?>

Output:

Hi Infotek,

How are you Infotek? Today is Sunday, I will go to class. Do you want to go with me
There are many friend will go with us? Do you know QA?

I am looking forward to hear from you? My number is 800-784-6129.
We are ging to meet at Worldgate Hernden.

Thanks,
-Jay

Reading and Writing Configuration Files

Now that you know how to read and write files, let’s try creating an application that uses the functions described in the preceding section. Assume for a second that you’re developing a Weblog application, and you’d like your users to be able to configure certain aspects of this application’s behavior—for example, how many posts appear on the index page or the e-mail address that comments are sent to. In this case, you’d probably need to build a Web-based form that allows users to input these configuration values and saves them to a file that your application can read as needed.

This next listing generates just such a Web form, allowing users to enter values for different configuration values and then saving this information to a disk file. When users revisit the form, the data previously saved to the file is read and used to prefill the form’s fields.

Example:

Configuration.php

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en”>
<head>
<title>Reading And Writing Configuration Files</title>
</head>
<body>
<h2> Reading And Writing Configuration Files</h2>
<?php
$configFile = ‘config.ini’;
if (!isset($_POST[‘submit’])) {
$data = array();
$data[‘AdminEmailAddress’] = null;
$data[‘DefAuthor’] = null;
$data[‘NumPosts’] = null;
$data[‘NumComments’] = null;
$data[‘NotifyURL’] = null;
if (file_exists($configFile)) {
$lines = file($configFile);
foreach ($lines as $line) {
$arr = explode(‘=’, $line);
$i = count($arr) – 1;
$data[$arr[0]] = $arr[$i];
}
}
?>
<form method=”post” action=”Configuration.php”>
<table width=”650″ border=”0″ cellpadding=”5″>
<tr>
<td> Administrator email address: </td>
<td><input type=”text” size=”50″ name=”data[AdminEmailAddress]” value=”<?php echo $data[‘AdminEmailAddress’]; ?>”/> </td>
</tr>
<tr>
<td> Default author name: </td>
<td> <input type=”text” name=”data[DefAuthor]” value=”<?php echo $data[‘DefAuthor’]; ?>”/> </td>
</tr>
<tr>
<td>Number of posts on index page: </td>
<td> <input type=”text” size=”4″ name=”data[NumPosts]” value=”<?php echo $data[‘NumPosts’]; ?>”/> </td>
</tr>
<tr>
<td>Number of anonymous comments: </td>
<td><input type=”text” size=”4″ name=”data[NumComments]” value=”<?php echo $data[‘NumComments’]; ?>”/> </td>
</tr>
<tr>
<td> URL for automatic notification of new posts: </td>
<td> <input type=”text” size=”50″ name=”data[NotifyURL]” value=”<?php echo
$data[‘NotifyURL’]; ?>”/> </td>
</tr>
<tr>
<td>&nbsp;</td>
<td> <input type=”submit” name=”submit” value=”Submit” /> </td>
</tr>
</table>
</form>
<?php
// if form submitted
// process form input
} else {
// read submitted data
$config = $_POST[‘data’];
// validate submitted data as necessary
if ((trim($config[‘NumPosts’]) != ” && (int)$config[‘NumPosts’] <= 0) ||
(trim($config[‘NumComments’]) != ” && (int)$config[‘NumComments’] <= 0)) {
die(‘ERROR: Please enter a valid number’);
}
// open and lock configuration file for writing
$fp = fopen($configFile, ‘w+’) or die(‘ERROR: Cannot open configuration file for writing’);
flock($fp, LOCK_EX) or die(‘ERROR: Cannot lock configuration file for writing’);
// write each configuration value to the file
foreach ($config as $key => $value) {
if (trim($value) != ”) {
fwrite($fp, “$key=$value\n”) or die(‘ERROR: Cannot write [$key] to configuration file’);
}
}
// close and save file
flock($fp, LOCK_UN) or die (‘ERROR: Cannot unlock file’);
fclose($fp);
echo ‘Configuration data successfully written to file.’;
}
?>
</body>
</html>

Output:

Configuration

Config

Reading And Writing Configuration Files

Configuration data successfully written to file.

Once the form is submitted, the data entered into it arrives in the form of an associative array, whose keys correspond to the configuration variables in use. This data is then validated and a file pointer is opened to the configuration file, config.ini. A foreach loop then iterates over the array, writing the keys and values to the file pointer in key=value format, with each key-value pair on a separate line. The file pointer is then closed, saving the data to disk.

Config.ini file:

AdminEmailAddress=qatraining@infotek-solutions.com
DefAuthor=Jay
NumPosts=10
NumComments=25
NotifyURL=www.qaonlinetraining.com/registration-for-online-demo/

If a user revisits the Web form, the script first checks if a configuration file named config.ini exists in the current directory. If it does, the lines of the file are read into an array with PHP’s file() function; a foreach loop then processes this array, splitting each line on the equality (=) symbol and turning the resulting key-value pairs into an associative array. This array is then used to prefill the form fields, by assigning a value to each input field’s ‘value’ attribute.