| Home | About | Downloads | Features | Demo | FAQ | Forum | Screenshots | PHP Tutorials | |
<< PHP Open File |
PHP Tutorials |
PHP Write to File >>
PHP Read File
When reading a file there are certain things to keep in mind. The PHP parser will not automatically read the entire content of the file. You must define how much of the data you want out of the file.
The fread() Function
If you want to test this out, make the example.txt file on your site and put it in the directory you wish to work with this code. It must have some content in it or the code will return an error. Here is the code:
<?php
$file_name = 'example.txt'; $file_handle = fopen($file_name, 'r') or die('Error opening file.'); // Requires the file handle and the amount of bytes $file_data = fread($file_handle, filesize($file_name)); fclose($file_handle); // Print the data read echo $file_data; ?>
In the above example you can see that we used the fopen() function to open the file and put the handle in the $file_handle variable. Next we have a new function, the fread() function.
Read a Little
As I said above, you don't have to read the entire file. For example, if you had a file that looked like this (example.txt):
The quick brown fox jumps over the lazy dog.
And you only wanted to read 15 bytes from it, you could do it like this:
<?php
$file_handle = fopen('example.txt', 'r') or die('Error opening file.'); // Requires the file handle and then amount of bytes $file_data = fread($file_handle, 15); fclose($file_handle); // Print the data read echo $file_data; ?>
This will successfully read 15 bytes from the file and output this:
The quick brown
You can change that number to anything you want, as long as it doesn't go over the entire length of the file. << PHP Open File | PHP Tutorials | PHP Write to File >> |
|
| © Douglas Rennehan 2007 - 2008 | Terms of Service | Privacy Policy | Valid XHTML 1.0 | Valid CSS | |