W3Schools.com

PHP More Functions

previous next

This section describes file handling in PHP.


Opening a File

The fopen() function is used to open files in PHP.

The first parameter of this function contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened in:

<html>
<body>

<?php
$f=fopen("welcome.txt","r");
?>

</body>
</html>

The file may be opened in one of the following modes:

File Modes Description
r Read only. File pointer at the start of the file
r+ Read/Write. File pointer at the start of the file
w Write only. Truncates the file (overwriting it). If the file doesn't exist, fopen() will try to create the file
w+ Read/Write. Truncates the file (overwriting it). If the file doesn't exist, fopen() will try to create the file
a Append. File pointer at the end of the file. If the file doesn't exist, fopen() will try to create the file
a+ Read/Append. File pointer at the end of the file. If the file doesn't exist, fopen() will try to create the file
x Create and open for write only. File pointer at the beginning of the file. If the file already exists, the fopen() call will fail and generate an error. If the file does not exist, try to create it
x+ Create and open for read/write. File pointer at the beginning of the file. If the file already exists, the fopen() call will fail and generate an error. If the file does not exist, try to create it

Note: If the fopen() function is unable to open the specified file, it returns 0 (false).

Example

The following example generates a message if the fopen() function is unable to open the specified file:

<html>
<body>

<?php
if (!($f=fopen("welcome.txt","r")))
exit("Unable to open file!");
?>

</body>
</html>


Closing a File

The fclose() function is used to close a file.

fclose($f);


Reading from a File

The feof() function is used to determine if the end of file is true.

Note: You cannot read from files opened in w, a, and x mode!

if (feof($f))
echo "End of file";


Reading a Character

The fgetc() function is used to read a single character from a file.

Note: After a call to this function the file pointer has moved to the next character.

Example

The example below reads a file character by character, until the end of file is true:

<?php
if (!($f=fopen("welcome.txt","r")))
exit("Unable to open file.");
while (!feof($f))
{
$x=fgetc($f);
echo $x;
}
fclose($f);
?>


previous next
WEB HOSTING
Best Web Hosting
PHP MySQL Hosting
Best Hosting Coupons
UK Reseller Hosting
Cloud Hosting
Top Web Hosting
$7.95/mo SEO Hosting
Premium Website Design
WEB BUILDING
Download XML Editor
FREE Website BUILDER
Free Website Templates Free CSS Templates
Make Your Own Website
W3SCHOOLS EXAMS
Get Certified in:
HTML, CSS, JavaScript, XML, PHP, and ASP
W3SCHOOLS BOOKS
New Books:
HTML, CSS
JavaScript, and Ajax
STATISTICS
Browser Statistics
Browser OS
Browser Display
SHARE THIS PAGE