In this tutorial you will learn about the PHP Files and its application with practical example.
PHP has the built in support and wide range of functions to perform file IO operations like –
Table Of Contents−
- Opening a file
- Reading a file
- Writing a file
- Closing a file
Reading a file in PHP
fopen() function is used to open a file. It requires two parameters first the file name and then mode in which to open.
r | Read only. Starts at the beginning of the file |
r+ | Read/Write. Starts at the beginning of the file |
w | Write only. Opens and clears the contents of file; or creates a new file if it doesn’t exist |
w+ | Read/Write. Opens and clears the contents of file; or creates a new file if it doesn’t exist |
a | Append. Opens and writes to the end of the file or creates a new file if it doesn’t exist |
a+ | Read/Append. Preserves file content by writing to the end of the file |
x | Write only. Creates a new file. Returns FALSE and an error if file already exists |
x+ | Read/Write. Creates a new file. Returns FALSE and an error if file already exists |
So here are the steps required to read a file with PHP.
- Open a file using fopen() function.
- Get the file’s length using filesize() function.
- Read the file’s content using fread() function.
- Close the file with fclose() function.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<html> <head> <title>Reading a file using PHP</title> </head> <body> <?php $filename = "text.txt"; $file = fopen( $filename, "r" ); if( $file == false ) { echo ( "Error in opening file" ); exit(); } $filesize = filesize( $filename ); $filetext = fread( $file, $filesize ); fclose( $file ); echo ( "File size : $filesize bytes" ); echo ( "<pre>$filetext</pre>" ); ?> </body> </html> |
Writing a file in PHP
A new file can be created or text can be appended to an existing file using the PHP fwrite() function. This function requires two arguments specifying a file pointer and the string of data that is to be written.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php $filename = "textfile.txt"; $file = fopen( $filename, "w" ); if( $file == false ) { echo ( "Error in opening new file" ); exit(); } fwrite( $file, "This is a simple test\n" ); fclose( $file ); ?> <html> <head> <title>Writing a file using PHP</title> </head> <body> <?php if( file_exist( $filename ) ) { $filesize = filesize( $filename ); $msg = "File created with name $filename "; $msg .= "containing $filesize bytes"; echo ($msg ); } else { echo ("File $filename does not exit" ); } ?> </body> </html> |