Writing to a file in PHP - fopen() R R




You will be writing scripts that will require you to save information into some database, but you're hampered by a lack of MySQL. Some of my scripts use MySQL for storing info. Maybe your isp has php enabled, but does not provide mysql server. Well, all hope is not lost. In this tutorial, I'll show you how to write information to a simple text file, instead of a database.

First let's briefly go over security issues. MySQL allows you to create user accounts, and only such users can access the database. That provides security for your files. On the other hand, when you use a text file, like I'm about to show you, the file will just be a plain text file that can be accessed and viewed by anybody. What that means is that somehow, someone could see all the info on your users, which is not a good thing.

But what can be done to make the text file secure so nobody can access it, but still be available for reading and writing by your script? Well, two ways you can go about this:

  • You can encrypt it in some way. Be sure to also see this. That way, if someone accesses it, all they'll see is gibberish.
  • The other way to prevent access to the content of the file is to save it somewhere on your hard drive outside your server's documents directory. Your documents directory is where you put all your html and image files that people can access over the net. If you place a file outside this directory, it becomes inaccessible over the net. Your php script can still read and write to this file, but web users cannot.

OK, so now let's talk about writing to a flat text file instead of to a database. How difficult is it to understand what we're about to learn? It's very easy! You could learn the basics in less than 5 minutes. After that, spend time in exploring the complexities associated with it.

Reading and writing to a file is done by the php functions fopen( ), fputs( ), fread( ), fclose( ).

I can tell right away that the F that precedes each of these functions stands for the word file. Can you? :)


Writing to a file

There are at least four steps to writing to a file.

  • You open the file for writing.
  • You define what you want to write to the file.
  • You do the actual writing.
  • You close the file.

Let's look at them step by step.


Opening a file for writing

How do you open a file? With the fopen( ) function of course. This function requires two parameters: the name of the file you want to open, and the mode (read, write, etc) you want the file to be in once it's open.

$fp = fopen("filename","mode");

  • $fp stores the file opening info for later use.
  • Change filename to the name of the file you want to open. Eg. c:/windows/desktop/whatever.txt. It can also be a url: http://yourdomain/whatever.txt. Other options are available. Eg. ftp://, php://stdin, etc.
  • Change mode to the correct format. You can use: "r", "r+", "w", "w+", "a", "a+", "b", "1". We will use "a" mode here. "r" mode opens the file for reading only, "w" mode for writing only, and "a" mode for writing only. r+, w+ and a+ open file for reading and writing. This stuff is well explained in the php manual, so I'm not going to spend much time on it. So let's say our filename is or will be accounts.txt, and we're using "a" mode. What we will have is:

    $fp = fopen("c:/windows/desktop/accounts.txt","a");


Define what you want to write to the file

Once the file is open, it's now ready to be written to. So you need to define what you want to write to it.

$str = "Hello World";

Keeping it simple, we're going to write "Hello World" into the file. $str will store that info. $str is just a variable to store the string we're going to write to accounts.txt.


Doing the actual writing

So now the file is open and you have defined what you're going to write. The next step is to do the actual writing.

$size = fputs($fp, $str);

$size stores the writing info, $fp we already know holds the file opening info, and $str holds the info to be written to the file.

Note: you don't have to create a file before hand before you can perform a read or write operation on it. If the file does not exist, php will automatically create it for you. Neato! In our example, if c:/windows/desktop/accounts.txt didn't exist, php creates it.


Closing the file

The final step is to close the file. That can be achieved quite simply with the fclose() function.

fclose($fp);


Putting everything together


<?php

$filename = "c:/windows/desktop/accounts.txt";

$fp = fopen($filename,"a+");

$str = "Hello World";

$size = fputs($fp, $str);

fclose($fp);

?>

Save the above file with a .php3 extension (or whatever extension you use for your php files). Place the file within your documents directory, so it can be accessible over the web. Open your web browser and run the file. So there you have it, you have successfully written "Hello World" to a file called accounts.txt, which is now sitting comfortably on your desktop. Go to your desktop now and open that file to make sure I'm not lying to you.

What other function could we have used to write to our file? We could have used fwrite() function. Both functions are identical in every way, and can be used interchangeably. Here's another neat example.


<?php

$filename = "c:/windows/desktop/test.txt";

$fp = fopen($filename,"w");

fwrite($fp, print (date ("l dS of F Y h:i:s A")));

fclose($fp);

echo "file was succefully written to.";

?>

A file called test.txt should be created on your desktop containing the current date and time. Open it and take a look.

Reading from a file

What about reading from a file?


$filename = "c:/windows/desktop/accounts.txt";
$fp = fopen ($filename, "r");
$contents = fread ($fp, filesize ($filename));
fclose ($fp);

The above should be clear enough to understand. First we open the accounts.txt file, then use fopen() function to open the file in "r" mode. We then read the contents of the file using fread() function. The content of the file is stored in the variable $contents. Finally we close the file.

When we use fread() to get the content of a file, how is the info stored in $contents? It is stored as one continous string from beginning to the end of the file.

But if the info is stored as one long string, how do you differentiate individual records? To answer this question, let's say you have login/password pairs stored in your file. Usually such pairs are stored in the format login:password. For example, we have three such pairs in our file

johnny:alps19
sinncity:pkmmjlo
sachsd:9951648

When we first read the info from the file, we get a long string like this

johnny:alps19 sinncity:pkmmjlo sachsd:9951648

But what we want is to separate the individual logins and passwords. This could be needed if you want to authenticate a user for example. The separation can be done easily. Php provides the explode() function.

$pairs = explode (" ", $contents);

$pairs = explode (":", $contents);

explode() requires two parameters: the delimiter (ie. something that separates the stuff we're trying to split apart), and the string to separate.

So in the example $pairs = explode (":", $contents);, our login:password pairs will be split up into two parts each. The result is stored in $pairs as an array. The string delimiter is :, and the string we're separating into parts is $contents, which we got from reading our file above. Of course, before we split the login/password pairs by "semicolon", we separated them by "space" first.


Practical Example

I know by now you're eager to know what you can use file read/write for in real life. I'll show you how to use the knowledge you have now to allow users to register for an account at your site without your intervention. To do this,

  1. Create a form into which your visitors will type info.
  2. Write a php script to process the info, and save such info into a file.

Form

You already know how to create html forms. Here's an example


<html><head><title>Register</title></head>

<body>

<form action="register.php3" method="post">

Choose a Login Name: <input type="text" name="login">

Choose a Password: <input type="text" name="passwd">
<input type="submit" name="submit" value="Register">

</form>

</body>

</html>

Under "action" above, you have indicated that you want register.php3 to process your form. Register.php3 is a file we will create to handle our form processing. Also notice that all the INPUT tags have a NAME attribute defined. The NAME attribute is extremely important when you're gathering info with a form that'll be processed by a script. Basically, when a user is done typing and clicks on the Submit button, the script register.php3 is called (ie. activated). register.php3 will now be looking for the NAME attributes in the form that called it. Each NAME attribute will be a variable that stores values typed in by the user.

So let's say a user visits your site to register and types in richie as the login name, and am16fdmJ as the password. register.php3 will store the info as $login="richie", $passwd="am16fdmJ".

Copy the form code above and paste it into notepad. Save it under your documents directory as register.html.

OK, so what will register.php3 look like? Let's take a look.


<?php

$filename = "c:/windows/desktop/user_accts.txt";

$fp = fopen($filename,"w");

$str = "$login" . ":" . "$passwd";

$size = fputs($fp, $str);

fclose($fp);

?>

Copy and paste the script into notepad. Save it to your web documents directory as register.php3. It must be in the same directory as register.html you saved earlier.

Let's take a look at the script. Most of it should be familiar to you already, especially the file-write part, which we tackled earlier on. We want to create a file called user_accts.txt, to be saved on the desktop. Php will automatically create the file if it doesn't already exist. user_accts.txt will contain login and passwords of your users or customers.

Take a look at the line $str = "$login" . ":" . "$passwd". Do you see anything peculiar about it? We have used two dots and a colon. A dot is used when we want php to concatinate (ie. join) strings. The colon will be the delimiter (separator) of our login/password pair.

That's all you need. What is left is for you to open your web browser, load the form register.html. Type in a username and password. Submit the form. A new file, user_accts.txt should be created on your desktop containing richie:am16fdmJ.

If you're wondering if it's really this easy to create a user registration app on your site, don't be. It's really that simple!

So far I have shown you the basics of reading and writing to a flat file. I have also presented you with a real life example of how to use that knowledge to create an auto user registration on your site.

The user registration script above is very basic. To use it on your site, there are things you should add to it. Things such as:

  • Form verification - what happens if a user decides to send a blank form?

    if(empty($login || $passwd)) { echo "error! Form must be filled in completely."; exit";}

  • Password verification - you should make the user types the password twice, then use the script to check that they match.

    if strcmp($passwd1 != $passwd2) { echo "Your passwords do not match!"; exit;}else{...

  • Password length - you can make your users enter login names and passwords of a certain length. The longer the passwords are, the harder it will be for other people to try to guess it, and of course, it makes your site more secure.

    if substr($passwd,0,strlen($passwd) < 6) { echo "Your password must be atleast SIX characters long!"; exit;}else{...

  • Registered user verification - the script should be able to check to make sure that you don't already have members with the same registration info.
  • Complete info - you can add more form fields such as First and Last Names, email address, etc.
  • Auto emailing - You can also include email functionality in the script where the registration info is automatically emailed to the address provided at registration time. A copy could also be sent to you to let you know.

    mail($first." ".$last <$email>,"Dear $first,\n\nThanks for registering with our site!\n Here is your registration info\n Login: $login\n Password" $passwd...","From: www.YourSite.com ");

  • Post-registration action - you will need to tell the script what to do next after the registration process is complete, eg. redirect user to another page. And so forth...

    header (location: /somewebpage.html);

Most of the examples I have presented above are just some of the features you can introduce into your script to make it smarter. My next tutorial will address these issues, so you can create one hot User Registration script. See a complete user registration script here.

Home