Tuesday, February 22, 2011

how to open a php file?

ust like how we create a new file, we also use fopen() to open existing files as well. However to open am existing file, we need to use different modes.

If you forgot what arguments fopen() takes, here they are again.

fopen ($filename, $mode);

PHP file open modes

Below is the list of modes to open existing files. We can use either of the modes to open files.
'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.
'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.

Let's look at some examples how to open files using fopen.

Example 1 - open file for reading



The code above opens myfile.txt for reading and places the pointer in the beginning of the files, which means, it will read everything from the start of the file to the end.

What happens if the file doesn't exist?

If the myfile.txt doesn't exist, the file handle $fh will return false. If you like to create the file in case it doesn't exist, you can use the file mode 'a'. This will create a new file myfile.txt, if it doesn't already exists.

Example 2 - open file for reading and writing



The code above opens myfile.txt for both reading and writing and places the pointer in the beginning of the file, which means, it will read or write from the start of the file.

What if I want to place pointer at the end of a file?

For that you can use file mode 'a' and 'a+' respectively to read/write from the end of the file.

Open remote files/urls

We can open files on local machine easily, like wise to open file sitting on a remote server or even urls, you can use fsockopen() function.

The function fsockopen() takes in several arguments as seen below.

fsockopen($hostname, $port, $errno, $errstr, $timeout);

* $hostname - location or URL of the file or page.
* $port - the default port is 80, unless otherwise told.
* $errno - optional. contains system level error number that occurred while connecting.
* $errstr - optional. contains error message if errro occurs while connecting.
* $timeout - optional. you can specify time in seconds before the connection fails and error is returned.

Example 1 - open remote files

The example below shows how to read the source code of a page and display it.



So, in this tutorial we learned how to open files for reading and writing. In the next tutorial, we will cover how to read from files and how to write to files.

No comments:

Post a Comment