PHP provides real comfort when you are
working with files. It does not matter whether they are on the local server ‘localhost’ or on a remote server. There are many cases when you will have to work with the content of different files, for example when you are using simple counters or string treatment of any kind. As well as many other abilities of the language the work with files in
PHP is easy and simple.
We will provide the main functions and constructions which will help you to perform operations on the file server as well as work with remote files.
Opening file in PHP.
Before doing anything with any file the first step is to open it. We can do that with ‘fopen ()’ function.
'r' Open for reading only; place the file pointer at the beginning of the file.
'r+' Open for reading and writing; place the file pointer at the beginning of the file.
'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
'a' Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
'a+' Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
'x' Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.
'x+' Create and open for reading and writing; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.
To describe how the file functions are working we will give you the notion here.
When ‘fopen ()’ function is executed it will return the file identification variable(in this case ‘$fp’), which variable we will use every time when we are working with that
open file. Besides that there is so called pointer which simply is showing where we are going to do any changed on the file.
For example if we want to open a file to put some text lines inside using the parameter “a+” the editing will be at the end of the file. And if we use the parameter “w+” the editing will start at the beginning of the file. You should do difference between “a+” and “а” since the second will open the file for writing only.
We will continue with the next
PHP tutorial about
reading a file in PHP.