USING PHP TO MANAGE FILES If you study

USING PHP TO MANAGE FILES If you study the preceding code, you ll notice that the second read operation uses fread(). It works perfectly with this example, but contains a nasty surprise. Change the code in fopen_pointer.php to add the following line after the external file has been opened (it s commented out in the download version): $file = fopen($filename, ‘r+’); fseek($file, 0, SEEK_END); This moves the pointer to the end of the file before the first write operation. Yet, when you run the script, fread() ignores the text added at the end of the file. This is because the external file is still open, so filesize() reads its original size. Consequently, you should always use a while loop with !feof() and fgets() if your read operation takes place after any new content has been written to a file. The changes to a file with read and write operations are saved only when you call fclose() or when the script comes to an end. Although PHP saves the file if you forget to use fclose(), you should always close the file explicitly. Don t get into bad habits; one day they may cause your code to break and lose valuable data. When you create or open a file in a text editor, you can use your mouse to highlight and delete existing content, or position the insertion point exactly where you want. You don t have that luxury with a PHP script, so you need to give it precise instructions. On the other hand, you don t need to be there when the PHP script runs. Once you have designed it, it runs automatically every time. Exploring the file system PHP s file system functions can also open directories (folders) and inspect their contents. From a web designer s viewpoint, the most practical applications of this are building a drop-down menu of files and creating a unique name for a new file. Inspecting a directory the quick way If your server runs PHP 5 or later, you can use the scandir() function, which returns an array consisting of the files and directories within a specified directory. Just pass the pathname of the directory as a string to scan dir(), and store the result in a variable like this: $files = scandir(’../images’); You can examine the result by using print_r() to display the contents of the array, as shown in the screenshot to the right (the code is in scandir.php in the download files).
Searching for affordable and reliable webhost to host and run your web applications? Go to our java web server services and you will be pleased.

Leave a Reply