File Handling In PHP
PHP File System allows us to create a file, read file line by line, read file character by character, write a file, append file, delete a file and close file.

PHP Open File - fopen()
The PHP fopen() function is used to open a file.
Syntax
fopen(filename,mode,include_path,context)
Open File Example
<?php
$handle = fopen("c:foldermyfile.txt", "r");
?>
click for more details
PHP Close File - fclose()
The PHP fclose() function is used to close an open file pointer.
Syntax
fclose(file)
Example
<?php
$file = fopen("mytest.txt","r");
//some code to be executed
fclose($file);
?>
PHP Read File - fread()
The PHP fread() function is used to read the content of the file. It accepts two arguments: resource and file size.
Syntax
fread(file,length)
| Parameter | Description |
|---|---|
| file | Required. Specifies the open file to read from |
| length | Required. Specifies the maximum number of bytes to read |
Example 1: Read 10 bytes from file:
<?php
$file = fopen("test.txt","r");
fread($file,"10");
fclose($file);
?>
Output : hello php file
Example 2: Read entire file:
<?php
$file = fopen("test.txt","r");
fread($file,filesize("test.txt"));
fclose($file);
?>
PHP Write File - fwrite()
The PHP fwrite() function is used to write content of the string into file.
Syntax
fwrite(file,string,length)
Example
<?php
$fp = fopen("data.txt", "w");//open file in write mode
fwrite($fp, "hello");
fwrite($fp, "php file");
fclose($fp);
echo "File written successfully";
?>
Output : File written successfully
click for more details
PHP Delete File - unlink()
The PHP unlink() function is used to delete the file.
Syntax
unlink(filename,context)
| Parameter | Description |
|---|---|
| filename | Required. Specifies the file to delete |
| context | Optional. Specifies the context of the filehandle. Context is a set of options that can modify the behavior of a stream |
Example
<?php
unlink("data.txt");
echo "File deleted successfully";
?>
click for more details
PHP rename() Function
- The rename() function renames a file or directory.
- This function returns TRUE on success or FALSE on failure.
Syntax
rename(oldname,newname,context)
| Parameter | Description |
|---|---|
| oldname | Required. Specifies the file or directory to be renamed |
| newname | Required. Specifies the new name of the file or directory |
| context | Optional. Specifies the context of the filehandle. Context is a set of options that can modify the behavior of a stream |
Example
<?php
rename("images","pictures");
?>
Series:
PHP Tutorials Hub
