Reading, Writing and Creating Files in 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.

File permissions in a Windows Environment

In order to be able to read and write to files and directories on any system you need to have the right privileges. I’m using a Windows system and am logged in as  Administrator. This status gives me all the access I need to read and write to files on my system. For those of you who do not have this “status,” you can set the file permissions by right clicking on the file that you want to work with. A dialog box should pop up that looks something like this:

Fig.1 Properties dialogbox…

In the screen shot you’ll see various options in the permissions section of the dialog box. Clicking on the “full control” checkbox will give you full access to the file.

If you do not have the right permission set on a file and then try to open, write or read it, then you will get a error warning, as in the screen shot below:

Fig.1 Permission denied error message…

{mospagebreak title=File Permissions in a Unix Environment}

In a Unix environment, all files and directories are owned by two different entities — a user and a group. Each file in the File System has three permission sets that determine who can access a file or directory. These sets are: group-level, user-level and global-level. Each permission set has three flags: read, write and execute. If  a user does not have, for example, a read flag set, he or she will not be able to read a particular file or directory. The same applies to a user that does not have a execute flag set; he or she will not be able to execute that script.

How to set the permissions

Permissions are set using a command called CHMOD. CHMOD stands for CHange MODe. CHMOD comes as a set of three numbers. Each of these three numbers is a sum total of three other numbers. So you have to add three numbers to get the first CHMOD number, add three numbers to get the second CHMOD number and add three numbers to get the third CHMOD number. 

Let me explain. Each digit is a number value from 0 to 7. The value specifies what capabilities are available (or not). These numbers correspond to three command types: read(r), write(w) and execute(x).

Read (r) has a value of 4. It allows listing files in the directory.
Write (w) has a value of 2. It allows the addition of new files to the directory.
Execute (x) has a value of 1. It allows access to the files in the directory.

Possible combinations available using these command types include:

Digit

rwx

Result

0

no access

1

–x

execute

2

-w-

write

3

-wx

write and execute

4

r–

read

5

r-x

read and execute

6

rw-

read and write

7

rwx

read write execute


Sometimes you’ll hear people say “chmod to 775.”
 Okay… so what do the three digits stand for?

The first digit represents the host server/computer. This will usually be set to seven. The second digit represents the group. And the third represents the world or “others.”

How do we arrive at the number 775? For the group “owner” we have:
1 [execute access] + 2 [write access] + 4 [read access] = 7.

For the group “groups” we have:
1 [execute access] + 2 [write access] + 4 [read access] = 7.

For group “others” we have:
1 [execute access] + 0 [no write access] + 4 [read access] = 5.

This means that the “host” and the “group” can do anything to the file, but anyone else can only execute it or read it. They can’t modify it.

How and when do you use the CHMOD command?

The easiest way is by using an FTP program. Most FTP programs have a  right-click menu that allows you to set the CHMOD on a specific folder. I use DreamWeaver 8; it provides a GUI on which I can set the permissions by right clicking on a file or directory, as below:

Fig3. CHMOD example

{mospagebreak title=Writing to Files}

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.”;
}
?>

{mospagebreak title=Reading from Files}

In PHP, to read from a file is easier than to write to a file. Instead of creating a file pointer and using the fopen() function, you simply read the entire file into an array and then retrieve it from there:

$theArray = file(‘theFilename’);

The file() function does all the work of reading the entire file and placing it in a array. Each element in the array will then contain one line from the file.

To demonstrate how to read from a file, let’s read the names from the text file that we stored them in. Create a PHP document and call it readnames.php:

 <?
$thenames = file(‘names.txt’);
$num_names = count($thenames);
for($i=0; $i < $num_names; $i++){
echo $thenames[$i]. “<br>”;
}
?>

The for Loop runs through the contents of the arrays and prints the names out. Below is a screen shot of the results I got:

Conclusion

We’re finished with part one of this discussion. In part two of this article, we will be looking at file uploading and how to handle file uploads. Till then, have fun reading and writing from files.

[gp-comments width="770" linklove="off" ]

chat sex hikayeleri Ensest hikaye