Hello, welcome to zhullyblog. If this is your first time here , please
Subscribe to Zhullyblog by Email to get latest tutorial.
PHP File system: How to create, access and manipulate a file
In this tutorial, you will learn to create, read , remove files using the PHP file system function.
Open a file
In PHP, to work with a file, you need to open the file. The PHP
fopen() function is used to open a file.
The Syntax
SYNTAX
From the syntax above, you can see the
•
filename : The file name specifies the name of the file you want to open
•
mode : the mode specifies the mode the file should be open. Do you want it to open a read only file , or open a read and write file. These are the job of the mode.
Here is an example
<?php
$file = 'file.txt';
$handle = fopen($file ,'w');
?>
Reading from file
After you have opened a file, you need to learn how to read from the file you have opened.
When reading a file ,you can decide to read a fixed number of characters from a file or read the entire file.
<?php
$file = 'file.txt';
$data =fread($file, 'r' );
?>
Writing the File
You can write a file using the PHP
fwrite() function. Here is the syntax
SYNTAX
fwrite(filehandle , string)
Example
<?php
$file = 'file.txt';
$handle = fopen( $file, 'w');
fwrite( $file ,'w');
?>
Looking at the example above, if the file doesn't exist, PHP will create it and write the file. But PHP will erase the content before writing a new file because of the mode. We would talk about the mode as we continue.
Close file
To close a file, you use the
fclose() function.
<?php
$file = 'file.txt';
$handle = fopen($file ,'w' )
fclose($handle);
?>
Delete a file
You can delete a file using the
unlink() function. Here is an example:
SYNTAX
<?php
$file = 'file.txt' ;
unlink($file);
?>
Now that we have talked about creating, opening and manipulating a file. We need to talk more about the mode.
Let's talk more about the
mode. There are several modes to open a file which I would list below. They are :
• r
Opens a read only file
• r+
Opens a read and write file
• w
Opens file for writing only
• w+
Opens a file for writing and reading and clears the content of the file.
• a
Opens a file for writing only. If files does not exist, PHP will open it.
• a+
Read/ Append. Opens a file for both reading and writing.
• x
Opens a file for writing only. But if the file already exists, it returns FALSE
• x+
Opens the file for reading and writing and returns false if file already exist.
Please share
Follow us on
1) Introduction to PHP
2) PHP Syntax
3) PHP Comment
4) PHP Data types
5) PHP Variables
6) PHP Echo and Print - How to display output
7) PHP If, if else and if elseif statement
8) PHP Lopps - While , Do while
9) PHP Strings : How to create and manipulate Strings
10) PHP Arrays
11)PHP FORMS: How to create a form, access data submitted in the form by user
Comments
Post a Comment