Google News
logo
PHP File Handling
File handling is an important part of any web application. PHP File System allows us to create file, read file line by line, read file character by character, write file, append file, delete file and close file.

The PHP file handling functions are,  creating, reading, uploading, fopen(), fclose(), fread(), fwrite(), fgets(), fgetc(), feof(), fileupload, file append, file delete etc.
PHP File Read - readfile() Function

The readfile() function reads a file and writes it to the output buffer.

MY_FILE.txt

JPEG = Joint Photographic Experts Group

GIF = Graphics Interchange Format

PNG = Portable Network Graphics

PSD = Photoshop Document

SVG = Scalable Vector Graphics

The PHP code to read the file and write it to the output buffer is as follows.
<!DOCTYPE HTML>  
<html>
<head>
	<title>File Handling - readfile()</title>
</head>
<body>  

<?php
echo readfile("MY_FILE.txt");
?>

</body>
</html>
PHP File Write - fwrite() Function

The PHP fwrite() function is used to write content of the string into file.

<!DOCTYPE HTML>  
<html>
<head>
	<title>File Handling - fwrite()</title>
</head>
<body>  

<?php  
$fp = fopen('MY_FILE_2.txt', 'w');//open file in write mode  
fwrite($fp, 'Free Time Learning ');  
fwrite($fp, 'Free Time Learn');  
fclose($fp);  
  
echo "File written successfully";  
?>  

</body>
</html>
PHP Close File - fclose()

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

The fclose() requires the name of the file (or a variable that holds the filename) we want to close:

Syntax
<?php
   fclose($file_name); 
?>
<!DOCTYPE HTML>  
<html>
<head>
	<title>Close File - fclose()</title>
</head>
<body>  
 
<?php    
	$file = fopen("MY_FILe.txt", "r");
	  echo fread($file,filesize("MY_FILE.txt"));
	  fclose($file);
?>     

</body>
</html>
Output :