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

//open text file
fopen("abc.txt","w");

//open ms word .doc file
fopen("abc.doc","w");

//open pdf file
fopen('abc.pdf',"w");

?>

 


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

<html>
<head>
<title>PHP Read file</title>
</head> 
<body>
<FORM method="POST">

<input type="submit" name="Submit1" value="Read File">
</FORM>

<?php
if(isset($_POST['Submit1']))
{
$filename = fopen( "abc.txt", "r" );

if( $filename == true )
{
$filesize = filesize("abc.txt" );
$filecontent = fread( $filename, $filesize );
fclose( $filename );

echo ( " File Content = $filecontent <br>" );
echo ( "File size : $filesize bytes" );
}
else
{ 
echo "Error !! Try again" ;
} 
}
?>

</body>
</html>

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

<?php

$file = fopen("abc.txt", 'w');

fclose($file);

?>

Leave a Reply

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