| Home | About | Downloads | Features | Demo | FAQ | Forum | Screenshots | PHP Tutorials | |
<< PHP File Tutorial |
PHP Tutorials |
PHP Read File >>
PHP Open File - fopen()
The function that is used most of the time to open files in PHP is the fopen() function. To be able to use this function you need to know the name of the file you'll be working with and the mode. The file name can be a relative path (/file.txt, file.txt) or a URL if your PHP configuration supports it (most of the time not though). There will be working examples down below, but to get a feel for the function it will look something like this:
<?php
$file_handle = fopen('example.txt', 'w') or die('Error opening file'); fclose($file_handle); ?> Different File Modes
There are countless reasons why you might want to open a file in PHP. The only thing is, how do you tell the PHP parser what you want to do? This can be done using modes. The following modes can be used when using the fopen() function:
There are also some more advanced modes that can be used:
*Note: A file pointer is just the location in the file where the PHP parser is. Opening the File
Opening a file is the first thing that needs to be done before you can do anything else with it. The fopen() function should be used like this:
$file_handle = fopen('file_name', 'open_mode') or die('Error opening file');
The file_name and open_mode need to be replaced with what you need. Here is another example of just opening and closing a file:
<?php
$file_handle = fopen('example.txt', 'w') or die('Error opening file.'); fclose($file_handle); That will simply open example.txt, or create it if it doesn't exist. It then will close the handle to the file. Creating a File
Using the fopen() function you are able to create a file. This file can then be dealt with like a regular file, had you had uploaded it. Here is a simple example of how to create example.txt:
<?php
$data = 'This is the new file content.'; $file_handle = fopen('example.txt', 'x') or die('Error creating file.'); fwrite($file_handle, $data); fclose($file_handle); ?>
Here you see three functions; fopen(), fwrite() and fclose().
|
|
| © Douglas Rennehan 2007 - 2008 | Terms of Service | Privacy Policy | Valid XHTML 1.0 | Valid CSS | |