12-30-2007, 12:32 AM
|
#8 (permalink)
|
|
The Frequenter
Join Date: Apr 2005
Location: South UK
Posts: 483
Thanks: 51
|
Opening files using fopen/fclose can be a bit confusing at first. Here's a little example code which will hopefully clear things up a bit
PHP Code:
// This will open the file "myfile.txt" for reading (note the 2nd argument - "r" - you can use "w" for writing). $file will then point to your newly opened file in memory. Note: at this point, all that has happened is that the file has been opened for reading - nothing has been read yet
$file = fopen('myfile.txt', 'r');
// The following code will read 2000 bytes from the file that we opened above (see how the $file pointer comes in to play here).
$contents = fread($file, 2000);
// As a further example, if you wanted to read the entire file, you would take advantage of the filesize() function like so:
$contents = fread($file, filesize('myfile.txt')); // will read the entire file and store the contents in $contents
// When you are done with your file, you will want to close it. To do this, we use the fclose() function:
fclose($file);
fopen() can do other fancy things such as opening URLs for reading. For more info on reading/writing to files using fopen/fread/fwrite/fclose see:
PHP: fopen - Manual
PHP: fread - Manual
PHP: fwrite - Manual
PHP: fclose - Manual
All have excellent examples which you can work from.
Alan.
|
|
|