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.
The PHP fopen() function is used to open a file.
fopen(filename,mode,include_path,context)
<?php
$handle = fopen("c:foldermyfile.txt", "r");
?>
The PHP fclose() function is used to close an open file pointer.
fclose(file)
<?php
$file = fopen("mytest.txt","r");
//some code to be executed
fclose($file);
?>
The PHP fread() function is used to read the content of the file. It accepts two arguments: resource and file size.
fread(file,length)
Parameter | Description |
---|---|
file | Required. Specifies the open file to read from |
length | Required. Specifies the maximum number of bytes to read |
<?php
$file = fopen("test.txt","r");
fread($file,"10");
fclose($file);
?>
Output : hello php file
<?php
$file = fopen("test.txt","r");
fread($file,filesize("test.txt"));
fclose($file);
?>
The PHP fwrite() function is used to write content of the string into file.
fwrite(file,string,length)
<?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
The PHP unlink() function is used to delete the file.
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 |
<?php
unlink("data.txt");
echo "File deleted successfully";
?>
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 |
<?php
rename("images","pictures");
?>
© 2024 Easy To Learning. All Rights Reserved | Design by Easy To Learning