Unit 10 File Handling
Unit 10 File Handling
It is possible to insert the content of one PHP file into another PHP file (before the server
executes it), with the include or require statement.
The include and require statements are identical, except upon failure:
require will produce a fatal error (E_COMPILE_ERROR) and stop the script
include will only produce a warning (E_WARNING) and the script will continue
Syntax
include 'filename';
or
require 'filename';
Example 1
Assume we have a standard footer file called "footer.php", that looks like this:
<?php
echo "<p>Copyright © 1999-" . date("Y") . " W3Schools.com</p>";
?>
Example
<html>
<body>
</body>
</html>
include_once() Function
The include_once() function can be used to include a PHP file in another one, when you may
need to include the called file more than once. If it is found that the file has already been
included, calling script is going to ignore further inclusions.
If a file named a.php is a php script calling b.php with include_once() function, and does not
find b.php, a.php executes with a warning, excluding the part of the code written within b.php.
Syntax:
include_once('name of the called file with path');
Example:
<?php
echo "GEEKSFORGEEKS";
?>
<?php
include_once('header.inc.php');
include_once('header.inc.php');
?>
Output:
GEEKSFORGEEKS
require_once() Function
require_once() function can be used to include a PHP file in another one, when you may need
to include the called file more than once. If it is found that the file has already been included,
calling script is going to ignore further inclusions.
If a.php is a php script calling b.php with require_once() function, and does not
find b.php, a.php stops execution causing a fatal error.
Syntax:
require_once('name of the called file with path');
Example:
<?php
echo "GEEKSFORGEEKS";
?>
<?php
require_once('header.inc.php');
require_once('header.inc.php');
?>
Output:
GEEKSFORGEEKS
Reading and writing to file
Open File - fopen()
A better method to open files is with the fopen() function. This function gives you more options
than the readfile() function.
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
PHP Read File - fread()
The first parameter of fread() contains the name of the file to read from and the second parameter
specifies the maximum number of bytes to read.
The following PHP code reads the "webdictionary.txt" file to the end:
fread($myfile,filesize("webdictionary.txt"));
Modes Description
r Open a file for read only. File pointer starts at the beginning of the file
w Open a file for write only. Erases the contents of the file or creates a new file if it doesn't exist. File pointer
starts at the beginning of the file
a Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates
a new file if the file doesn't exist
x Creates a new file for write only. Returns FALSE and an error if file already exists
r+ Open a file for read/write. File pointer starts at the beginning of the file
w+ Open a file for read/write. Erases the contents of the file or creates a new file if it doesn't exist. File pointer
starts at the beginning of the file
a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates
a new file if the file doesn't exist
x+ Creates a new file for read/write. Returns FALSE and an error if file already exists
The example below outputs the first line of the "webdictionary.txt" file:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>
The feof() function checks if the "end-of-file" (EOF) has been reached.
The feof() function is useful for looping through data of unknown length.
The example below reads the "webdictionary.txt" file line by line, until end-of-file is reached:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
The example below reads the "webdictionary.txt" file character by character, until end-of-file is
reached:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>
The first parameter of fwrite() contains the name of the file to write to and the second parameter
is the string to be written.
The example below writes a couple of names into a new file called "newfile.txt":
Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
You can append data to a file by using the "a" mode. The "a" mode appends text to the end of the
file, while the "w" mode overrides (and erases) the old content of the file.
In the example below we open our existing file "newfile.txt", and append some text to it:
Example
<?php
$myfile = fopen("newfile.txt", "a") or die("Unable to open file!");
$txt = "Donald Duck\n";
fwrite($myfile, $txt);
$txt = "Goofy Goof\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
CSV FILE
CSV stands for comma-separated values. A CSV file is a text file that stores tabular data in the
form of comma-separated values. A CSV file stores each record per line. And it may have a
header.
When you open a CSV file using a spreadsheet application, you’ll see that the file is nicely
formatted like this:
However, if you view the CSV file in a text editor, it looks like the following:
Symbol,Company,Price
GOOG,"Google Inc.",800
AAPL,"Apple Inc.",500
AMZN,"Amazon.com Inc.",250
YHOO,"Yahoo! Inc.",250
FB,"Facebook, Inc.",30
Code language: plaintext (plaintext)
Typically, a CSV file uses a comma (,) to separate fields in a CSV file. If the field content also
contains a comma(,), the CSV file surrounds that field with double quotes, e.g., “Facebook,
Inc..”
Besides using the comma (,) character, a CSV file may use other characters to separate fields
such as semicolon (;).
fputcsv ( resource $handle , array $fields , string $delimiter = "," , string $enclosure = '"' , string
$escape_char = "\\" ) : int|false
Code language: PHP (php)
The following example uses the fputcsv() function to write data to a CSV file:
<?php
$data = [
['Symbol', 'Company', 'Price'],
['GOOG', 'Google Inc.', '800'],
['AAPL', 'Apple Inc.', '500'],
['AMZN', 'Amazon.com Inc.', '250'],
['YHOO', 'Yahoo! Inc.', '250'],
['FB', 'Facebook, Inc.', '30'],
];
$filename = 'stock.csv';
fgetcsv ( resource $stream , int $length = 0 , string $separator = "," , string $enclosure = '"' ,
string $escape = "\\" ) : array
Code language: PHP (php)
The fgetcsv() function reads a line of CSV data from the file pointer’s position and places it into
an array; each line of the CSV file is an array element.
The function fgetcsv() returns false if there is an error occurred while reading the file or when
the file pointer reaches the end-of-file.
The following example shows how to read the stock.csv file created above:
<?php
$filename = './stock.csv';
$data = [];