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:
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 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: <?
blog comments powered by Disqus |
|
|
|
|
|
|
|