First, it's important to know that if the PHP server runs on a Linux server, a folder must have minimum CHMOD access permissions of 0755 for PHP scripts to open a file.
To create or alter files, you normally need to set global access permissions of 0777.
If you use PHP server (WampServer, XAMPP) on Windows you don't need to set these CHMOD permissions
PHP has a set of functions that allow you to open a file, read it and/or write to it, and then close the file.
- fopen() - opens a file or URL, and returns a file pointer resource on success, or FALSE on error
- fgets() - reads a line from file pointer
- fread() - reads a specified amount of a file
- fwrite() - writes to a file
- filesize() - returns the size of the file in bytes, or FALSE
- fclose() - close a file opened with fopen()
The first of these,
fopen(), is the most important. Before apply any of the other functions, you must open the file with "fopen()".
-
Syntax:
fopen('filename', mode)
"
filename" contains the name of the file to be opened.
"
mode" specifies the type of access to the file. It may be any of the following:
- 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 - Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist.
- w+ - Opens for reading and writing, and clears the contents of file; or creates a new file if it doesn't exist.
- a - Opens and writes to the end of the file or creates a new file if it doesn't exist.
- a+ - Opens for reading and writing, to add new data at end of file. Creates a file if it doesn't already exist.
- x - Creates a new file. Returns FALSE and an error if file already exists
- x+ - Creates a new file and open for reading and writing, but fails if a file of the same name already exists.
- c - Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to 'w'). The file pointer is positioned on the beginning of the file.
- c+ - Open the file for reading and writing.
- [mode]b - Open the file in binary mode.
- The
internal pointer is like the cursor in a word processor: PHP starts reading or writing from wherever the pointer is positioned when you call fread() or fwrite().
Under Microsoft Windows, ASCII files and binary files are treated differently. When you open a binary file on Windows, specify "b" as the last character of the "mode". For example, "rb" for reading, "wb" for writing, "a+b" to read and add.
Closing a File
An open file consumes system resources. When a script has finished using a file, the script should close the file, freeing those resources.
At the end of a script, PHP automatically closes open files. However, it is recommended to close files more quickly, whenever possible.
To close a file, use
fclose().
fclose(file_handle);
- "
file_handle" is a handle to a file successfully opened by "fopen()".
-
Example:
<?php
$fo = fopen('files/test.txt', 'r');
// some code to be executed
fclose($fo);
?>
Creating a new file with fopen()
To create a new file with fopen(), set a name for the file, use this function with "x" (or "xb") mode, add some data with "fwrite()", than close the file.
Using the "x" (or "xb") mode, it makes sure you're not overwriting an existing file. But if you want to overwriting an existing file, you can use "w" (or "wb") mode.
PHP must have read and write permissions (CHMOD 0777) in the folder in which you want to create the file.
-
Example:
<?php
$filename = 'files/test.txt';
$str = 'Free PHP course and tutorials.'. PHP_EOL. 'Web site: https://coursesweb.net';
// opens the file with "xb" mode
if ($fo = fopen($filename, 'xb')) {
// write the $str value
fwrite($fo, $str);
// close the file and output a message if success
if (fclose($fo)) echo 'The file was created';
}
else echo 'Unable to create the file.';
?>
-
PHP_EOL is a PHP constant that represents a new line on any operating system.
If you run this script in your browser, it should create a "test.txt" file in the "files" directory, with the content added in the
$str variable, and displays: "
The file was created." (This file will also be used in the next examples).
The changes to a file with read and write operations are saved only when you call fclose() or when the script comes to an end. Although PHP saves the file when the script ends all operations, you should always close the file explicitly, with "fclose()".
Reading a file with fread()
The
fread() function reads a specified amount of data from a file.
-
Syntax:
fread(file_handle, size)
"
file_handle" is a handle to a file successfully opened by "fopen()".
"
size" is the number of bytes read.
-
Example:
<?php
// gets the first 50 bytes of a file into a string
$filename = 'files/test.txt';
if ($fo = fopen($filename, 'r')) {
$str = fread($fo, 50);
echo $str;
fclose($fo);
}
else echo 'Unable to open the file.';
?>
If you want to read the whole file with "fread()", you need to use the "
filesize()" to get and pass the whole file size.
-
Example:
<?php
// gets the first 50 bytes of a file into a string
$filename = 'files/test.txt';
if ($fo = fopen($filename, 'r')) {
$str = fread($fo, filesize($filename));
echo $str;
fclose($fo);
}
else echo 'Unable to open the file.';
?>
If you want to get the whole content of a file into a string, use file_get_contents() as it has much better performance than "fread()".
Reading a File Line by Line
You can use the
fgets(file_handle) function to read a single line from a file. It needs as parameter a "file-handle" returned by "fopen()".
-
Example:
<?php
// gets the first line of a file into a string
$filename = 'files/test.txt';
if ($fo = fopen($filename, 'r')) {
$line = fgets($fo);
echo $line;
fclose($fo);
}
else echo 'Unable to open the file.';
?>
The "fgets()" function moves the file pointer to the next line, so, if it's combined with
feof() it can reads the whole file line by line.
The feof() function determines whether the end of the file (EOF) has been reached.
-
Example:
<?php
$filename = 'files/test.txt';
if ($fo = fopen($filename, 'r')) {
// output the content line by line
while(!feof($fo)) {
echo fgets($fo). '<br />';
}
fclose($fo);
}
else echo 'Unable to open the file.';
?>
Appending content with fopen()
To add new content at the end of a file (after the existing content), use fopen() with "a" (or "ab") mode.
If you want to read and append data, use "a+" (or "a+b") mode..
-
Example:
<?php
$filename = 'files/test.txt';
$new_data = PHP_EOL. 'File handling lesson.';
// opens the file with "ab" mode
if ($fo = fopen($filename, 'ab')) {
// write the $new_data value
fwrite($fo, $new_data);
// close the file and output a message if success
if (fclose($fo)) echo 'The new data was appended.';
}
else echo 'Unable to create the file.';
// outputs the whole file content
echo '<hr />'. file_get_contents($filename);
?>
Assuming that the "test.txt" is the same file created at the beginning of this lesson, this code will output:
The new data was appended.
Free PHP course and tutorials. Web site: https://coursesweb.net File handling lesson.
Moving the internal pointer
Reading and writing operations always start wherever the internal pointer happens to be.
PHP has two functions that help to move the internal pointer in the place you need:
- To get the current pointer position of the file, use
ftell(file_handle) function.
- To move the pointer to the end of a file, use:
- fseek(file_handle, 0, SEEK_END);
-
Example:
<?php
$filename = 'files/test.txt';
// opens the file
if ($fo = fopen($filename, 'r')) {
$line = fgets($fo); // read the first line
// gets and outputs the position of the file pointer
echo 'The pointer position after read the first line is: '. ftell($fo);
rewind($fo); // pointer moved back to beginning
// move the internal pointer to 30 bytes from the beginning
fseek($fo, 30, SEEK_SET);
// outputs the next 10 characters
echo '<br />'. fread($fo, 10);
// outputs the new position of the file pointer
echo '<br /> The new position of the file pointer is: '. ftell($fo);
fclose($fo);
}
else echo 'Unable to open the file.';
?>
Assuming that the "test.txt" is the same file created at the beginning of this lesson, this code will output:
The pointer position after read the first line is: 32
Web site
The new position of the file pointer is: 40
• For other util functions for file handling, see the
Using file_put_contents, file_get_contents, readfile and file() tutorial.