|Opening and Closing Files in PHP|
PHP provides number of in-built functions to handle our files related issues. PHP files functions are very advance and can offer almost all the things required in our PHP scripts. In this tutorial we will learn how to Open, Read and Close Files using PHP.
To read any file content we need to first open it using the fopen() function.
$fhandler = fopen ($filename, $mode);
The function is assigned to a variable, $fhandler, called file pointer. We need to use file pointer to make reference to the open file throughout our program.
The fopen() function takes two arguments:
Binary files require the "b" in the mode. Like
$fhandler = fopen ($filename, "ab+");
In this tutorial we will deal with text files only.
We know how to open files using PHP functions. Now, we will learn how to read the file content.
Data can be read from opened file using fread() function. Example is given below:
$fcontent = fread ($fhandler, $length);
The value of fread() function is assigned to a variable called $fcontent. This variable will contain the data which has been read by fread() function.
There are two arguments in fread() function:
$fhandle : is the file pointer to which we assigned value using fopen() function
$length : is the argument for the amount of byte which we wish to read.
To read the entire file using fread() function, we need to specify the total byte-size of the file using filesize() function.
$byte-size = filesize($filename);
Now, we will learn using a script how to open a text file and display its content to user:
$filename = "/home/username/www/myfile.txt";
We need to learn how to close any opened file after doing required operation, to clean up the memory and to avoid future corruption to file. A file which is opened using fopen() function has to closed using fclose() function:
So, in this tutorial we learned how to open file, read content of files and how to close files after operations. We will be coming up with more PHP tutorials on files handling.
|< Prev||Next >|