PHP gives us a feature of “File Handling System”. This feature is super useful because it allows you to create files, read a files line by line, reading files character by character, write a files, append a files, delete a files and close a files. This concept will explain following functions:-
- Opening a file
- Reading a file
- Writing a file
- Closing a file
r = Read, w= write, a= append, r+ = reading/ writing, w+ =writing/ reading / creating a file.
1. PHP fopen() Function
If simply, we want to open a file or any URL then we follow fopen() Function. If the file is already created then it will simply open it, but In case, the file is not already created then it will create a file and open it. The PHP fopen() function accepts two arguments that are $filename and $mode.
Syntax:- resource = fopen ( filename , mode );
$filename = file to be opened
$mode= Mode of file. For example:- read-only, write-only, read-write.
When you will save your program, then it will return a blank web page as an output without any error. It means your file is Successfully created. Then open your newly created file and write a new data or you can make changes into your old data.
2. PHP fwrite() function
If you want to write the content of the strings into files, then PHP offers fwrite() function in the concept of File Handling. By the help of PHP fwrite() and fputs() functions are used to write data into the file. For write data into the file, you can use r+, w, w+, x, x+, c or c+ mode.
Syntax:- int fwrite=($resource , string );
3. PHP fread() Function
In PHP File Handling Concept, fread() function provides the facilities of various types of functions to read all data from the file, reading line by line and also character by character. It accepts two arguments that are resource and file size.
Syntax:- string fread (resource $handle , int $length )
$handle = “file pointer that’s created by fopen() function”
$length = “Byte’s length to be read”
4. PHP Append to File
PHP file Handling concept has another useful feature that’s a “Append to File”. If you will use “a” mode, It will add new data to your file and also It will not erase the old data. Let’s understand it with the following example:-
5. PHP unlink() function
In File Handling, the PHP unlink() function is used to delete any file. It is similar to UNIX C unlink() function. In the case file is not deleted then PHP unlink() generates the E_WARNING level error. If the file is deleted then it will return TRUE otherwise FALSE.
Syntax:- unlink ( $filename , context )
$filename = file’s name to be deleted.
6. PHP fclose() Function
The PHP fclose() function is used to close an open file pointer. After making changes to the opened file, it is important to close it with the fclose() function.
Syntax:- ool fclose ( resource $handle )
Hope this article was helpful. Happy Programming !