Home arrow PHP arrow Page 3 - Reading, Writing and Creating Files in PHP

Writing to Files - PHP

Reading and writing to files can be useful if you do not require the storing of important data, such as a web counter. I must warn you though, that this method of storage should not be used to store passwords and other critical information, as it is not safe. Here we will discuss how to handle files and directories in PHP, specifically, how to create, read and write them.

TABLE OF CONTENTS:
  1. Reading, Writing and Creating Files in PHP
  2. File Permissions in a Unix Environment
  3. Writing to Files
  4. Reading from Files
By: Jacques Noah
Rating: starstarstarstarstar / 42
August 23, 2006

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Writing to files is a three step process in PHP. First you open the file; then you write data to it; and then you close it. PHP has built-in functions that make this easy. For example, if I want to write "My name is John Doe" to a file, I'd do it like this:

$file_pointer = fopen('thefilename','themode');

fwrite($file_pointer,'My name is John Doe');

fclose($file_pointer);

In PHP you do not work with a file directly, but through a file pointer. The file is assigned to the file pointer right at the start of the code and is then used throughout the script to read or write to the file, until the fclose() function is called.

The most important thing about opening a file is what mode you want to use. Depending on what you want to do with the file, the mode dictates how to open it.

Below is a table containing all the modes with their respective meanings:

Mode

Meaning

r

Reading only, begins reading a the start of the file

r+

Reading or writing, begins reading a the start of the file

w

Writing only. Creates the file if it does not exist, and overwrite any existing contents

w+

Reading or writing Creates the file if it does not exist, and overwrite any existing contents(when writing)

a

Writing only. Creates the file if it does not exist, and append the new data to the end of the file.

a+

Reading or writing Creates the file if it does not exist, and overwrite any existing contents(when writing)

x

Writing only. Creates the file if it does not exist, but do nothing, issue a warning, if the file does exist.

x+

Reading or Writing. Creates the file if it does not exist, but do nothing, issue a warning, if the file does exist.

The fwrite() function writes data (as seen in the above piece of code) to the file, in accordance with the selected mode. If you want each piece of data to be written on a new line, then an appropriate new line characters should be added at the end of the line. The line break characters depend on the operating system that you are using:

n on Unix and  MAC OS X

rn on Windows

The last line in our example of writing to a file closes the file by referring to the file pointer variable while calling the fclose() function.

As an example, let's create a text file  and write names to it. Later on we will retrieve and display the names.

First, create a text file and call it names.txt. Do not type anything in it. You can do this in any text editor. Then create a PHP document and save it as writename.php. This script will display and handle an HTML form.

writename.php
<?
//check if the form has been submitted
if(isset($_POST['submit'])){
//try to open the file
if($fp=fopen('names.txt','ab')){
//write to the file
fwrite($fp,$_POST['thename']. "rn");
fclose($fp);
//inform user that the writing was a success
echo "The name ".$_POST['thename']. " has been stored";
}else{
echo "There was an error, could not store the name.";
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-
8859-1" />
<title>Untitled Document</title>
</head>
<body>
<form action="writename.php" method="post">
<table width="100%" border="0" cellspacing="1">
  <tr>
    <td colspan="2">Please enter a name: </td>
    </tr>
  <tr>
    <td width="7%"><strong>Name:</strong></td>
    <td width="93%"><input name="thename" type="text" id="thename" size="40" /></td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td><input type="submit" name="submit" value="submit" /></td>
  </tr>
</table>
</form>
</body>
</html>

See this script in action:

Filling out the form..

Name added to the names.txt file.

If your file is on a server, chances are that more than one person at a time will want to use the file at the same time. In that case, you will have a problem. Luckily for you, PHP has functions that give you the ability to lock a file while you are busy using it.

The LOCK_EX and LOCK_UN functions will enable you to lock a file temporarily while it is being used. A revised version of our previous script would look something like this:

<?
//check if the form has been submitted
if(isset($_POST['submit'])){
//try to open the file
if($fp=fopen('names.txt','ab')){
flock($fp, LOCK_EX);
//write to the file
fwrite($fp,$_POST['thename']. "rn");
flock($fp,LOCK_UN);
fclose($fp);
//inform user that the writing was a success
echo "The name ".$_POST['thename']. " has been stored";
}else{
echo "There was an error, could not store the name.";
}
?>



 
 
>>> More PHP Articles          >>> More By Jacques Noah
 

blog comments powered by Disqus
   

PHP ARTICLES

- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...
- PHP: Building Concrete Validators
- Sanitizing Input with PHP
- Executing Shell Commands with PHP
- Handling File Data with PHP
- File Security and Resources with PHP
- ArrayObject PHP Class Examples
- ArrayObject PHP Class: An Introduction
- Getting File System Data with PHP
- PHP Tools for Working with the File and Oper...
- Working with the File and Operating System w...
- PHP Proxy Patterns: Completing a Blog


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 8 - Follow our Sitemap

Dev Shed Tutorial Topics: