0% found this document useful (0 votes)
3 views

Unit 10 File Handling

The document explains file handling in PHP, focusing on the use of include, require, include_once, and require_once statements for including PHP files. It also covers file operations such as opening, reading, writing, and appending to files using functions like fopen, fread, fwrite, and fputcsv for CSV files. Additionally, it provides examples demonstrating how to read and write data from and to files, including handling CSV formatted data.

Uploaded by

lokbasnet368
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Unit 10 File Handling

The document explains file handling in PHP, focusing on the use of include, require, include_once, and require_once statements for including PHP files. It also covers file operations such as opening, reading, writing, and appending to files using functions like fopen, fread, fwrite, and fputcsv for CSV files. Additionally, it provides examples demonstrating how to read and write data from and to files, including handling CSV formatted data.

Uploaded by

lokbasnet368
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

File Handling

PHP include and require Statements

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 &copy; 1999-" . date("Y") . " W3Schools.com</p>";
?>

To include the footer file in a page, use the include statement:

Example
<html>
<body>

<h1>Welcome to my home page!</h1>


<p>Some text.</p>
<p>Some more text.</p>
<?php include 'footer.php';?>

</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:

// name of file is header.inc.php

<?php

echo "GEEKSFORGEEKS";

?>

The above file is header.inc.php


The above file header.inc.php, is included twice with include_once() function in the following
file index.php. But from the output, you will get that the second instance of inclusion is
ignored since include_once() function ignores all the similar inclusions after the first one.

// name of file is index.php

<?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:

// name of file is header.inc.php

<?php

echo "GEEKSFORGEEKS";

?>

The above file is header.inc.php


The above file header.inc.php, is included twice with require_once() function in the following
file index.php. But from the output, you will get that the second instance of inclusion is
ignored since require_once() function ignores all the similar inclusions after the first one.

// name of file is index.php

<?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 fread() function reads from an open file.

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

PHP Read Single Line - fgets()

The fgets() function is used to read a single line from a file.

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);
?>

PHP Check End-Of-File - feof()

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);
?>

PHP Read Single Character - fgetc()

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

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);
?>

PHP File Create/Write


PHP Write to File - fwrite()

The fwrite() function is used to write to a file.

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);
?>

PHP Append Text

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 (;).

Writing to a CSV file

To write a line to a CSV file, you use the fputcsv() function:

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';

// open csv file for writing


$f = fopen($filename, 'w');

if ($f === false) {


die('Error opening the file ' . $filename);
}
// write each row at a time to a file
foreach ($data as $row) {
fputcsv($f, $row);
}

// close the file


fclose($f);
?>

Reading from a CSV file

To read a CSV file, you use the fgetcsv() function:

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 = [];

// open the file


$f = fopen($filename, 'r');

if ($f === false) {


die('Cannot open the file ' . $filename);
}

// read each line in CSV file at a time


while (($row = fgetcsv($f)) !== false) {
$data[] = $row;
}

// close the file


fclose($f);
?>

You might also like