Showing posts with label fopen(). Show all posts
Showing posts with label fopen(). Show all posts

Monday 30 July 2012

PHP fread Function


PHP - File Read

If you wanted to read all the data from the file, then you need to get the size of the file. The filesize function returns the length of a file, in bytes, which is just what we need! The filesize function requires the name of the file that is to be sized up.

PHP Code:

$myFile = "testfile.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;

Output:

Floppy Jalopy Pointy Pinto 
Note: It is all on one line because our "testfile.txt" file did not have a <br /> tag to create an HTML line break. Now the entire contents of the testfile.txt file is stored in the string variable $theData.

PHP Create a File


Create a File

The fopen function needs two important pieces of information to operate correctly. First, we must supply it with the name of the file that we want it to open. Secondly, we must tell the function what we plan on doing with that file (i.e. read from the file, write information, etc).
Since we want to create a file, we must supply a file name and tell PHP that we want to write to the file. Note: We have to tell PHP we are writing to the file, otherwise it will not create a new file.

PHP Code:

$ourFileName = "testfile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);
 
The file "testfile.txt" should be created in the same directory where this PHP code resides. PHP will see that "testFile.txt" does not exist and will create it after running this code. There's a lot of information in those three lines of code, let's make sure you understand it.
  1. $ourFileName = "testfile.txt"; Here we create the name of our file, "testfile.txt" and store it into a PHP String variable $ourFileName.
  2. $ourFileHandle = fopen($ourFileName, 'w') or die("can't open file"); This bit of code actually has two parts. First we use the function fopen and give it two arguments: our file name and we inform PHP that we want to write by passing the character "w".
    Second, the fopen function returns what is called a file handle, which will allow us to manipulate the file. We save the file handle into the $ourFileHandle variable. We will talk more about file handles later on.
  3. fclose($ourFileHandle); We close the file that was opened. fclose takes the file handle that is to be closed. We will talk more about this more in the file closing lesson.