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.
Outline
- You will learn how to access file from PHP
- 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()
- Source(http://www.php.net)
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 $handler1 = fopen("/home/yourname/file.txt","r"); $handler2 = fopen("c:\\file.txt","r"); $handler3 = fopen("http//www.php.net/","r"); $handler4 = fopen("ftp://user:password@doaminexample.com/file.txt","w"); ?>
Open file with file()
open1.php
If you need to get file that is larger than 10M, you are better use fopen().
test.txt file content
Hello world,
I love you,
I miss you,
I need you,
I want you,
I give you,
I let you,
I meet you
getfile1.php
<?php $my_file = 'test.txt'; $lines = file($my_file); foreach($lines as $line) { echo $line . "<br/>"; } ?>
Display
Hello world,
I love you,
I miss you,
I need you,
I want you,
I give you,
I let you,
I meet you
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. So don’t expect to have the same information as what we have now.
<?php $my_file = 'book.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); } ?>
Display
book.txt is ..
Executable: no
Writable: yes
Readable:yes
Is A file:yes
Is A Directory:no
File Change time: Mon, 2011 Jun 20 8:25 PM
File Access time: Mon, 2011 Jun 20 9:59 PM
File Update time: Mon, 2011 Jun 20 9:59 PM
File Size: 121bytes or 0.11827956989247M
File Permission: 666
Reverse File
test.txt file content
Hello world,
I love you,
I miss you,
I need you,
I want you,
I give you,
I let you,
I meet you
reversefile.php
We retrieve the file in the reverse order.
<?php $my_file = 'test.txt'; $lines = file($my_file); for ($i = count($lines)-1; $i >= 0; $i--) { echo "Index: $i ". $lines[$i]."<br/>"; } ?>
Display
Index: 7 I meet you
Index: 6 I let you,
Index: 5 I give you,
Index: 4 I want you,
Index: 3 I need you,
Index: 2 I miss you,
Index: 1 I love you,
Index: 0 Hello world,
Delete File
We call an unlink function with the file name to delete a file. That’s it. How you delete a file.
<?php // open a file for reading $handler1 = fopen("file.txt","r"); // delete a file unlink("file.txt"); ?>
Read from file content
test.txt file content
Hello world,
I love you,
I miss you,
I need you,
I want you,
I give you,
I let you,
I meet you
readingFile.php
Read a file content.
<?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; ?>
Display
Hello world, I love you, I miss you, I need you, I want you, I give you, I let you, I meet you
readingFile2.php
We loop through a file and display each line.
<?php $file = fopen('test.txt', 'r') or exit('unable to read the file'); while (!feof($file)) { echo fgets($file). '<br/>'; } fclose($file); ?>
Display
Hello world,
I love you,
I miss you,
I need you,
I want you,
I give you,
I let you,
I meet you
Write content to a file
write2afile.php
We would like to write a content to file.
<?php $file_handler = fopen('test1.txt','w') or exit('unable to read the file'); $content = 'Peace from your heart'; fwrite($file_handler, $content); fclose($file_handler); ?>
Appending to the end of a file
test.txt file content
Hello world,
I love you,
I miss you,
I need you,
I want you,
I give you,
I let you,
I meet you
appending2theend.php
We want to add the content at the end of a file.
<?php $file_name = 'test1.txt'; $file_handler = fopen($file_name, 'a') or exit('can not open the file'); fwrite($file_handler, "good day\n"); fclose($file_handler); ?>
File Content
Hello world,
I love you,
I miss you,
I need you,
I want you,
I give you,
I let you,
I meet you
good day
Appending to the beginning of a file
test1.txt file content
Hello world,
I love you,
I miss you,
I need you,
I want you,
I give you,
I let you,
I meet you
appendFile1.php
We want to append a new content to the beginning of a file.
<?php $file_name = 'test1.txt'; // open file for reading only $file_handler_1 = fopen($file_name, 'r') or exit('can not open file!'); // store the file content into $file_content_1 $file_content_1 = fread($file_handler_1, filesize($file_name)); // close file 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); ?>
File Content
Global
Hello world,
I love you,
I miss you,
I need you,
I want you,
I give you,
I let you,
I meet you
Replace file content
test.txt file content
Hello world,
I love you,
I miss you,
I need you,
I want you,
I give you,
I let you,
I meet you
avgScore4EachSubject.php
We would like to replace “I” with “Father” in the file content.
<?php $file_name = 'test1.txt'; // open file for reading only $file_handler_1 = fopen($file_name, 'r') or exit('can not open file!'); // store the file content into $file_content_1 $file_content_1 = fread($file_handler_1, filesize($file_name)); // replace file content $new_file_content = str_replace('I', 'Father', $file_content_1); // close file 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); ?>
File Content
Hello world,
Father love you,
Father miss you,
Father need you,
Father want you,
Father give you,
Father let you,
Father meet you
Replace a string from an associative array
We have a list of string to be replaced within a file.
<?php $file_name = 'test1.txt'; $str_replace = array('Father'=>'Mother','love'=>'care'); // open file for reading only $file_handler_1 = fopen($file_name, 'r') or exit('can not open file!'); // store the file content into $file_content_1 $file_content_1 = fread($file_handler_1, filesize($file_name)); // replace file content with a list of string $new_file_content = str_replace(array_keys($str_replace), array_values($str_replace), $file_content_1); // close file 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
Get URL content
<?php $file = fopen('http://jobs.perl.org/','r'); $count_line=0; while (!feof($file)) { echo $count_line.' '. htmlspecialchars(fgets($file)) . "<br/>"; $count_line++; } fclose($file); ?>
Email Template
myprofile.txt
Hi [[:friend]], How are you [[:friend]]? Today is [[:today]], I will go to shopping mall to buy some clothes. 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]]. See you, [[:myname]]
Email Template
We want to create a text file template for our email.
myLetter.php
<?php $file_name = 'myprofile.txt'; $array_email = array('[[:myname]]'=>'John', '[[:friend]]'=>'Cristina', '[[:today]]'=>'Sunday', '[[:ourfriend]]'=>'Janny', '[[:phonenumber]]'=>'318-555-3333', '[[:place]]'=>'Dillair Mall'); // open file for reading only $file_content_1 = file_get_contents($file_name); // replace file content $new_file_content = str_replace(array_keys($array_email), array_values($array_email), $file_content_1); echo '<pre>'.$new_file_content . '</pre>'; ?>
Display
Hi Cristina, How are you Cristina? Today is Sunday, I will go to shopping mall to buy some clothes. Do you want to go with me? There are many friend will go with us? Do you know Janny? I am looking forward to hear from you? My number is 318-555-3333. We are ging to meet at Dillair Mall. See you, John
Text File Template
book.txt
The book Infor:
Author: {:author}
Price: {:price}
Publisher: {:publisher}
Title: {:title}
Info: {:body}
bookTemplate.php
<?php $file = 'book.txt'; $template_aa = array('{:author}','{:price}','{:publisher}','{:title}','{:body}'); $array_aa = array('Jannifer Bill',30,'Orailly','PHP/MySQL','It\' a book for Web Developer and MySQL'); if (file_exists($file)) { $file_content = file_get_contents($file); $fin_content = str_replace($template_aa, $array_aa, $file_content); print nl2br($fin_content); } ?>
Display
The book Infor:
Author: Jannifer Bill
Price: 30
Publisher: Orailly
Title: PHP/MySQL
Info: It’ a book for Web Developer and MySQL
Select From MySQL and Save result to file, and from file insert into MySQL
In this tutorial, we will demonstrate on how to create an class to handle the query the table from the MySQL and store the result into text file. We also learn how to insert from text file into MySQL table.
We use the singleton class for the PDO connection to connect to the MySQL.
pdo_mysql.php connector for PDO
<?php define('USERNAME2', 'youruser'); define('PASSWORD2', 'yourpassword'); define('DSN2', "mysql:host=localhost;dbname=socms"); class pdo_mysql { private static $_instance; public static function &pdo_connection() { if (!self::$_instance) { try { self::$_instance = new PDO(DSN2, USERNAME2, PASSWORD2); self::$_instance->setAttribute(PDO::ATTR_PERSISTENT, true); self::$_instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $est) { die("pdo connection error! " . $est->getMessage() . "<br/>"); } } return self::$_instance; } private function __construct() { } private function __clone() { } } ?>
This class is the main class that we create to access to the MySQL table as well as store the result into the text file. Moreover, we also create method to insert into the MySQL table from text file.
insert2file.php
<?php require_once 'pdo_mysql.php'; class insert2file extends pdo_mysql { private $conn; private $return_sql; public $sql; public function __construct() { $this->conn = pdo_mysql::pdo_connection(); } public function insert() { $db = $this->conn->prepare($this->sql); if (!$db->execute()) { return false; } else { return true; } return false; } public function select() { $db = $this->conn->prepare($this->sql); if (!$db->execute()) { return false; } $this->return_sql = $db->fetchall(PDO::FETCH_ASSOC); return $this->return_sql; } public function save2file($file_nam=null) { if (!empty($file_nam)) { $file_name = $file_nam; } else { $file_name = 'ablec.txt'; } $file_handler = fopen($file_name, 'w') or exit('can not save to file!!!'); $column_name = $this->column(); $string_column_name = implode(',', $column_name); fwrite($file_handler, $string_column_name . "\n"); foreach ($this->return_sql as $key => $value) { $string_to_save = implode(',', $value); fwrite($file_handler, $string_to_save . "\n"); } fclose($file_handler); } public function column() { $result = $this->select($this->sql . ' LIMIT 1'); return array_keys($result[0]); } public function file2insert($file_name, $table_name) { $file_handler = fopen($file_name, 'r') or exit('can not open file!'); $column_name = fgets($file_handler); $column_array = explode(",", $column_name); $column_array = explode(",", $column_name); // create binding value $temp = array(); $type_bind = array(); for ($i = 0; $i < count($column_array); $i++) { $temp[] = "?"; } $column_value = implode(', ', $temp); // create binding insert statement $this->sql = 'INSERT INTO ' . $table_name . '(' . $column_name . ') VALUES(' . $column_value . ')'; // total column need to bind $total_coln = count($temp); while (!feof($file_handler)) { $value = fgets($file_handler); if (!empty($value)) { $arr_v = explode(",", $value); $insert_statment = $this->conn->prepare($this->sql); $insert_statment->execute($arr_v); } } } } ?>
insert() method
This method call to insert into the MySQL table.
select() method
This method return the result from the query.
save2file() method
Call this function, a file is created and the content of the query will be stored on that file.
column() method
return the column/field name of the table.
file2insert($filename, $tablename) method
Call this function to insert from a text file into a table. The text file must include a data that could be used to insert into a specific table. If you encountered an error while you try to insert from the file to the table, you must check whether it is problem with duplication key which is not allow for primary key.
Test The Example
We select everything from the page table and store it into the text file called ‘page222.txt’
<?php $test = new insert2file(); $test->sql = "SELECT * FROM page"; $test->save2file('page222.txt'); ?> </pre> <h3>Test The Example 2</h3> Insert into the table from the text file. Please note that if the content of the record have the same duplicate primary key, it will display a warning or error. <?php $test = new insert2file(); $test->file2insert('page222.txt','page'); ?>
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.
Here’s the code (configure.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 // define configuration filename and path $configFile = 'config.ini'; // if form not yet submitted // display form if (!isset($_POST['submit'])) { // set up array with default parameters $data = array(); $data['AdminEmailAddress'] = null; $data['DefAuthor'] = null; $data['NumPosts'] = null; $data['NumComments'] = null; $data['NotifyURL'] = null; // read current configuration values // use them to pre-fill the form 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="configure.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> </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>
This example illustrates a common, and practical, use of PHP’s file functions: to read and write configuration files in the context of a Web application. Figure 6-1 illustrates the Web form generated by this script.
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.
Fig 1: A Web form to enter configuration data
Here’s an example of what config.ini would look like after submitting the form in Fig 1 :
AdminEmailAddress=admin@abc.com
DefAuthor=Charles W
NumPosts=8
NumComments=4
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.
Figure 2 illustrates one such Web form, prefilled with data read from the configuration file.Users are, of course, free to resubmit the form with new data; as explained previously, this submission will then be used to rewrite the configuration file with new values.

Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka, Bangladesh. I’m a Certified Engineer on ZEND PHP 5.3, I served my first Fifteen years a number of leadership positions at AmarBebsha Ltd as a CTO, Winux Soft Ltd, SSL Wireless Ltd, Canadian International Development Agency (CIDA), World Vision, Care Bangladesh, Helen Keller, US AID and MAX Group where I worked on ERP software and web development., but now I’m a founder and CEO of TechBeeo Software Company Ltd. I’m also a Course Instructor of ZCPE PHP 7 Certification and professional web development course at w3programmers Training Institute – a leading Training Institute in the country.
Very good post! We will be linking to this particularly great content on our
website. Keep up the great writing.