Mean of the file handling is file open, file read, file write, file delete, file copy, set file mode etc.There are more file handling functions use in php. But functions use of file read, file write, file delete and file copy are most common.
File Open
The fopen() function is used to open files in PHP. There are two parameters are use in this function. The first parameter of this function contains the name of the file to be opened. We can give file in our server or external server in this parameter. The second parameter specifies in which mode the file should be opened. These are the file mode of we can use.
r - Read only
r+ - Read/Write
w - Write only
w+ - Read/Write
a - Append
a+ - Read/Append
x - Write only
x+ - Read/Write
Example :
$file = fopen("file.txt" ,"r");
File Read
The fread() function is used to read opened file in PHP. fread(file.length) is a syntax of this function. The "file" parameter specifies the open file to read from. The length parameter specifies the maximum number of bytes to read.
Example :
$contents = fread($file, 20);
Tips : If you want to read full file, use "filesize()" for length parameter
$file = fopen("file.txt" ,"r");
$contents = fread($file, filezize("file.txt"));
print $contents;
File Write
The fwrite() function is used to writes to an open file in PHP. fwrite(file,text,length) is a syntax of this function. The "file" parameter specifies the open file to write to, the "text" parameter specifies the string to write to the open file and the "length" parameter specifies the maximum number of bytes to write.
Example :
$file = fopen("file.txt" ,"r");
$contents = fread($file,filesize("file.txt"));
fwrite($file,"This is new file",20);
Tips : 1. If you want to write full length of text you can remove "length" parameter in function
2. If yoy want to create new file use "a" mode in fopen() function. Ex fopen("file.txt" ,"a");
No comments:
Post a Comment