PHP open file and read file

PHP File Open and Read

In this php tutorial we will learn how to open file , read file and close file using file handling functions.

PHP functions :

  • fopen() – open file
  • fread() – read file
  • fclose() – close file

PHP fopen() function

PHP fopen() function used to open a file. If file does not exist then fopen() function will create a new file.
The fopen() function must use with mode character like ‘w’, ‘a’ ,’r’ etc.

PHP fopen() syntax:

<?php

fopen(“filename with extension”, “mode char”);

?>

The fopen() function has following modes :

  • w = write only. if file exist open it, if not then create a new file.
  • w+ = read/write
  • r = read only
  • r += read / write
  • a = append file
  • a+ = read / append
  • x = write only. create new file, returns error if file already exists.
  • x+ = read/write.

Example of fopen() function

 


PHP Read file – fread() function

The fread() function used to reads from an open file. The read() function has two arguments.The first name of the file and second parameter specifies the maximum size of file to read.

PHP fread() syntax

<?php

fread(“filename”, “filesize”);

?>

Example of fread() function

The output is :

PHP file open and read example

PHP file open and read example


PHP close file – fclose()

The fclose() function is used to close an open file.

PHP fclose() syntax

<?php

fclose(“filename”);

?>

Exmaple of fclose() function

Leave a Reply

Your email address will not be published. Required fields are marked *

7 + 8 =


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">