So much for reading files - how about actually writing one? In PHP, this is somewhat more complex, involving as it does the use of file "pointers" to write data to a file. The function that does most of the work here is a little munchkin called fopen(), which opens a pointer to the file. fopen() requires two parameters - the name of the file, and the mode in which the file is to be opened. This "mode" is one of the following: Read-only mode, activated by the parameter "r". Here, the file pointer is initialized at the first line of the file. Write-only mode, activated by the parameter "w". Here, the file is created anew and the pointer is initialized at the first line of the file. If the file already exists, all its contents are lost. Read/write mode, activated by the parameter "r+". Here, the file is opened for reading and writing, with the pointer initialized at the first line of the file. Append mode(write only), activated by the parameter "a". In this case, the pointer is placed at the *end* of the file, allowing you to append new content to the end of the file. If the file doesn't exist, a new one is created. Append mode(read/write only), activated by the parameter "a+". Here too, the pointer is placed at the *end* of the file, allowing you to append new content to the end of the file. If the file doesn't exist, a new one is created. You can also read from the file. Once you've got the file opened in the right mode, it's time to actually write something to it with the fputs() function. Our next example demonstrates this more clearly: In this case, we've first opened a file pointer to the file; next, we've used the fputs() function to actually write a string to the file. The fputs() function needs two parameters - the file pointer to use, and the string to be written to the file. Once your file has been written, you can close the file with fclose(), and check the contents with readfile() or file(). Our next example combines everything you've just learnt to create the world's longest story - check it out! In this example, the user is presented with a simple form containing a text box. Once the user enters something into the text box and submits the form, the text string is inserted into the file "graffiti.dat". The page is then reloaded, the file is read and the complete contents displayed; the user now has the opportunity to enter something new into the box and have this text appended to the end of the existing text in the file.
blog comments powered by Disqus |