0% found this document useful (0 votes)
6 views41 pages

UECS2094 UECS 2194 - Topic 5 Part 3

The document provides an overview of file handling in PHP, detailing functions such as fopen, fclose, fread, fwrite, and fgetcsv for manipulating files and directories. It explains how to open, read, write, and close files, as well as handling CSV files using fgetcsv and fputcsv functions. The importance of closing files to prevent memory leaks and other issues is emphasized throughout the document.

Uploaded by

fooweichang2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views41 pages

UECS2094 UECS 2194 - Topic 5 Part 3

The document provides an overview of file handling in PHP, detailing functions such as fopen, fclose, fread, fwrite, and fgetcsv for manipulating files and directories. It explains how to open, read, write, and close files, as well as handling CSV files using fgetcsv and fputcsv functions. The importance of closing files to prevent memory leaks and other issues is emphasized throughout the document.

Uploaded by

fooweichang2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 41

Server-side

Scripting
using PHP (part 3)
FILE HANDLING

1
PHP File Handling
 In PHP, file handling refers to the manipulation of files and directories on the
server's file system.
 This is an important feature for web applications as they often need to read
from and write to files.

2
PHP File Handling
Commonly used functions:
◦ fopen
◦ fclose
◦ file
◦ feof
◦ fgetc
◦ fgets
◦ fputs
◦ fread
◦ fwrite
◦ fseek

3
fopen
 This function is used to open a file and returns a file pointer resource that can be used to
read from or write to the file.
 It takes two arguments: the filename and the mode (i.e. read, write, append, etc.).
 fopen(filename,mode)

//Example:
$file = fopen("test.txt","r");

$file = fopen("/home/test/test.txt","w");
4
fopen Mode
 "r“: Read only. Starts at the beginning of the file
 "r+“: Read/Write. Starts 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+" : Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't
exist
 “a“: Write-only mode. File pointer starts at the end of the file. If the file does not exist, it
is created.
 “a+“: Read and write mode. File pointer starts at the end of the file. If the file does not
exist, it is created
 "x“ : Write-only mode. Creates a new file. Returns FALSE and an error if the file already
exists.

5
fopen
 Once a file has been opened using fopen(), you can use other file handling functions like
fgets(), fputs(), fwrite(), and fclose() to read from or write to the
file.

 It's important to remember to close the file using fclose() when you are done with it,
to avoid potential memory leaks or other issues.

6
fclose
 Closes an opened file.
 fclose(file_pointer);

 where file_pointer is the resource returned by the fopen() function.

//Example:

$file = fopen("test.txt","r");
//some code to be executed
fclose($file);

7
fclose
 It's a good practice to always close a file using fclose() when you are done with it, to
avoid potential memory leaks or other issues.
 Not closing a file can cause the file pointer to remain open, which can cause issues if you try
to open the same file again or if you try to access the file from another program or process..

8
file
Reads a file into an array.
◦ Each array element consists of content of each line in the file

Example:

$file_content = file("test.txt");

9
Example file()
$file_lines = file('example.txt');  The file() function is used to read the
foreach ($file_lines as $line) { entire contents of the file "example.txt" into
an array called $file_lines. The
echo $line; contents of the file are then output using a
} foreach loop.

*It's important to note that file() can be used to read files of any size, but it may not be the most efficient way to read
large files as it reads the entire file into memory at once. For large files, it may be better to use functions like fopen()
and fread() to read the file in chunks.
10
feof
 The feof() function stands for "end-of-file" and is used to determine whether the file
pointer has reached the end of the file.
 It takes a file handle as its parameter and returns true if the pointer is at the end of the file,
and false otherwise.
 First open the file "example.txt" for reading
$file_handle = fopen('example.txt', 'r');
while (!feof($file_handle)) { using fopen() and assign the file handle to
$line = fgets($file_handle); $file_handle.
echo $line;  Then loop through the file using fgets() to
} read each line and echo it out until feof()
fclose($file_handle);
returns true, indicating that we have reached
the end of the file.
 Finally, close the file using fclose().
*It's important to note that feof() does not return true until an attempt is made to read past the end of the file. Therefore, it's generally
used in conjunction with functions like fgets() or fread() to determine when to stop reading the file. 11
fgets
 The fgets() function in PHP is used to read a single line from a file.
 It returns a string containing the contents of the line, up to and including the newline
character (\n).
 If the end of the file is reached before a newline is encountered, the function will return the
remaining characters in the last line, without a newline character.
 The syntax for fgets() is:

string fgets ( resource $handle [, int $length ] )

 where $handle is the file pointer, returned by a previous call to fopen(), and
$length is the maximum number of bytes to read. If $length is not specified, the
default value of 1024 bytes will be used.
12
Example fgets
$file_handle = fopen('example.txt', 'r');  First open the file "example.txt" for reading
while (!feof($file_handle)) { using fopen() and assign the file handle
to $file_handle.
$line = fgets($file_handle);
 Then loop through the file using fgets()
echo $line;
to read each line and echo it out until
} feof() returns true, indicating that we
fclose($file_handle); have reached the end of the file.
 Finally, close the file using fclose().

*It's important to note that fgets() does not remove the newline character from the end of the line it reads.
13
fgetc
 The fgetc() function in PHP is used to read a single character from a file.

 It returns a string containing the character that was read, or false if the end of the file has
been reached.

 The syntax for fgetc() is:

string|false fgetc ( resource $handle )

 where $handle is the file pointer, returned by a previous call to fopen().

14
Example fgetc
$file_handle = fopen('example.txt', 'r');  First open the file "example.txt" for reading using
while (($char = fgetc($file_handle)) !== false) { fopen() and assign the file handle to
$file_handle.
echo $char;
}  Then loop through the file using fgetc() to
read each character and echo it out until
fclose($file_handle);
fgetc() returns false, indicating that we have
reached the end of the file.

 Finally, close the file using fclose().

*It's important to note that fgetc() returns a string, even though it only reads a single character. Therefore,
you should use the strict equality operator (===) to check if fgetc() returns false, rather than the loose
equality operator (==).
15
fputs
 is used to write a string to a file.
 The syntax for fputs() is:

int|false fputs ( resource $handle , string $string [, int $length ] )

 where $handle is the file pointer, returned by a previous call to fopen(), $string
is the string to write, and $length is an optional parameter that specifies the maximum
number of bytes to write. If $length is not specified, fputs() will write the entire
string.

16
Example fputs
$file_handle = fopen('example.txt', 'w');  First open the file "example.txt" for writing using
fopen() and assign the file handle to
fputs($file_handle, 'Hello, world!'); $file_handle. We then write the string "Hello,
fclose($file_handle); world!" to the file using fputs() and close the file
using fclose().

 It's important to note that fputs() returns the


number of bytes written, or false on error.

17
fwrite
 is a function used to write data to a file.
 It is similar to the fputs() function, but the order of the parameters is different.
 Both functions behave similarly and have the same return value. fputs() is an alias of
fwrite(), so they are essentially the same function with a different name.
 The syntax for fwrite() is:
int|false fwrite ( resource $handle , string $string [, int $length ] )

 where $handle is the file pointer, returned by a previous call to fopen(), $string
is the string to write, and $length is an optional parameter that specifies the maximum
number of bytes to write. If $length is not specified, fwrite() will write the entire
string.

18
Example fwrite
 First open the file "example.txt" for writing
$file_handle = fopen('example.txt', 'w'); using fopen() and assign the file handle to
fwrite($file_handle, 'Hello, world!'); $file_handle.
 Then write the string "Hello, world!" to the file
fclose($file_handle); using fwrite() and close the file using
fclose().

 It's important to note that fwrite() returns


the number of bytes written, or false on error. If
the file pointer is at the end of the file,
fwrite() will append the data to the end of
the file. If the file pointer is not at the end of
the file, fwrite() will overwrite the existing
data starting from the current position.
19
fread
 fread() is a file handling function that reads a specified number of bytes from a file.
 It takes two arguments: the file handle returned by fopen() and the number of bytes to
read.
 The syntax of fread() is as follows:

string fread ( resource $handle , int $length )

 $handle: A file system pointer returned by fopen()


 $length: The number of bytes to read
 The function returns the data read from the file, or false on error.

20
Example fread
Example.txt  First open the file using fopen() with
Hello World!This is an example text file. read mode ("r")
 Then read the first 5 bytes of the file using
<?php fread().
 Finally, close the file using fclose().
$file = fopen("example.txt", "r");
The output of this example will be "Hello".
$data = fread($file, 5);
fclose($file);
echo $data; // Output: Hello
?>

21
fseek
 fseek() sets the file pointer's position in a file. It allows the user to move the pointer to a specific
location within a file so that the next read or write operation occurs from that position.
 The fseek() function takes three arguments:
 $handle: The file system pointer returned by fopen()
 $offset: The number of bytes to move the pointer
 $whence: The position from where the offset is to be measured. It can take one of the following
three values:
 SEEK_SET: sets the position relative to the beginning of the file.
 SEEK_CUR: sets the position relative to the current file position.
 SEEK_END: sets the position relative to the end of the file.

 The function returns 0 on success and -1 on failure.

int fseek ( resource $handle , int $offset [, int $whence = SEEK_SET ] )


22
fseek
<?php  First open the file using fopen() with read
$file = fopen("example.txt", "r"); mode ("r"),
 Then move the pointer to the 7th byte using
fseek($file, 7, SEEK_SET);
fseek().
$data = fgets($file);
 Finally, read the next line using fgets(), which
fclose($file); will read "World!" from the file. The output of this
echo $data; // Output: World! example will be "World!".

?>  Note that the pointer position after this operation


will be at the end of the line "World!".

23
Comma-separated Values (CSV)
 Comma-separated values (CSV) is a common file format used to store and exchange data
between different software applications. As the name suggests, CSV files use commas to
separate values in a line, and each line represents a record.

 CSV files can be easily created, modified, and read using different software applications,
including spreadsheet software like Microsoft Excel or Google Sheets, database software,
and programming languages like PHP.

24
fgetcsv
 fgetcsv() function is used to read a CSV file line by line and convert each line
into an array of values.
 The function takes two parameters: the file pointer resource created using
the fopen() function and the length of the longest line to be read.

25
fgetcsv
 Syntax
o fgetcsv(file,length,separator,enclosure)

 Returns an array containing values read parameter:

Function Description
file Required. Specifies the file to check
length Optional. Specifies the maximum length of a line.

separator Optional. A character that specifies the field separator.


Default is comma ( , )
enclosure Optional. A character that specifies the field
enclosure character. Default is "
26
Example fgetcsv
// Open the CSV file for reading
$file = fopen('data.csv', 'r');

// Loop through each line in the file and output the values
while (($line = fgetcsv($file)) !== false) {
echo implode(',', $line) . '<br>';
}

// Close the file pointer


fclose($file);

 the fopen() function is used to open the data.csv file in read mode, and a while loop is used to read
each line in the file using the fgetcsv() function.
 The values in each line are then concatenated using the implode() function and printed to the
output. 27
fputcsv
 CSV files can also be created and written to using the fputcsv() function.
 fputcsv() takes two parameters: the file pointer resource created using the fopen()
function and an array of values to be written to the file.

28
fputcsv
 Syntax:
◦ fputcsv(file,fields,seperator,enclosure)

Parameter Description
file Required. Specifies the open file to write to
fields Required. Specifies which array to get the data from

seperator Optional. A character that specifies the field separator.


Default is comma ( , )
enclosure Optional. A character that specifies the field enclosure
character. Default is "

29
Example fputcsv
// Open the CSV file for writing  fopen() function is used to
$file = fopen('data.csv', 'w'); open the data.csv file in write
mode, and an array representing
// Write a header row to the file
$header = ['Name', 'Email', 'Phone']; the header row is written to the
fputcsv($file, $header); file using the fputcsv()
function.
// Write data rows to the file 
$data = [ The data rows are then written to
['John Doe', 'john@example.com', '555-1234'], the file using a foreach loop and
['Jane Smith', 'jane@example.com', '555- the fputcsv() function, and
5678'], the file pointer is closed using the
['Bob Johnson', 'bob@example.com', '555-9012']
]; fclose() function.
foreach ($data as $row) {
fputcsv($file, $row);
}
30
// Close the file pointer
fclose($file);
PHP file upload
 Uploading files is a common task in web development, and PHP provides a simple way to
handle file uploads.
 The process involves creating an HTML form that allows users to select a file to upload, and
a PHP script that handles the actual upload process.

31
Step 1: HTML form
 Create an HTML form with the "enctype" attribute set to "multipart/form-data".
 This tells the browser to send the form data as a MIME multipart message, which allows for
file uploads. The form should contain an input field of type "file" for selecting the file to
upload.

<form action="upload.php" method="post" enctype="multipart/form-


data">
Select file to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload File" name="submit">
</form>

32
Step 2: PHP script
 Create a PHP script that handles the file upload.
 This script should check that the file was uploaded successfully, and move it to the desired
location on the server.
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check if file was uploaded successfully


if (isset($_POST["submit"])) {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). "
has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
33
}
?>
Step 3: Validation of file
 Process the uploaded file as needed.
 Once the file has been uploaded, you can use PHP's file handling functions to read, write,
and manipulate the file as needed.
 Note that you should also validate the uploaded file to ensure that it is of the expected
type, size, and format. You can use PHP's file validation functions to do this, such as
"getimagesize()" to check if the file is an image, or "filesize()" to check if the file
is too large.

34
Step 4: Moving the uploaded file
 After validating the uploaded file, the next step is to move the file from the temporary
directory to a permanent location on the server.
 This is done using the move_uploaded_file() function. The function takes two
parameters: the first parameter is the temporary file name, and the second parameter is the
new file location.

35
Step 4: Moving the uploaded file
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file))
{
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]
["name"])). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
 In the above example, the uploaded file is moved to the uploads/ directory on the server. The
basename() function is used to get the name of the uploaded file without the directory
path.
36
Uploading multiple files (1)
 To upload multiple files, you can use an array for the file input element in the HTML form.

<form action="upload.php" method="post" enctype="multipart/form-


data">
<input type="file" name="fileToUpload[]">
<input type="file" name="fileToUpload[]">
<input type="file" name="fileToUpload[]">
<input type="submit" value="Upload Files" name="submit">
</form>
 In the above HTML form, there are three file input elements with the same name attribute
(fileToUpload[]), which creates an array of files when submitted.

37
Uploading multiple files (2)
 In the PHP script, you can loop through the array of uploaded files and process each file using
the $_FILES superglobal variable.
$target_dir = "uploads/";

foreach($_FILES["fileToUpload"]["tmp_name"] as $key=>$tmp_name) {
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"][$key]);

if (move_uploaded_file($tmp_name, $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"]
[$key])). " has been uploaded.<br>";
} else {
echo "Sorry, there was an error uploading your file.<br>";
}
}

 In the above example, the foreach loop iterates over the array of uploaded files and moves each file to the
uploads/ directory on the server.
38
 Note that when uploading multiple files, the name and tmp_name properties of the $_FILES superglobal
variable are arrays, so you need to use array indexing to access each file's properties.
Summary
• PHP provides several functions to handle files, including fopen, fclose, file,
feof, fgetc, fgets, fputs, fread, fwrite, and fseek.
• fopen is used to open a file and returns a resource handle that can be used to read, write,
or append to the file.
• fclose is used to close an open file handle and free up system resources.
• file is used to read a file into an array, with each line of the file being an element in the
array.
• feof is used to check if the end of the file has been reached.
• fgetc is used to read a single character from a file.
• fgets is used to read a single line from a file.

39
Summary
• fputs is used to write a string to a file.
• fread is used to read a specified number of bytes from a file.
• fwrite is used to write a specified number of bytes to a file.
• fseek is used to move the file pointer to a specified position in the file.
• CSV stands for Comma-Separated Values and is a file format commonly used to store tabular
data.
• fgetcsv is used to read a line from a CSV file and parse it into an array.
• fputcsv is used to create and write to a CSV file.

40
Summary
 Steps of PHP File Upload:

1. HTML form with file input: The file upload process starts with an HTML form that includes a file
input element, which allows users to select files from their local computer to be uploaded.
2. PHP script: When the form is submitted, the data is sent to a PHP script that handles the file upload
process. The PHP script can perform various checks and validations on the uploaded file, such as
file size, file type, and file name.
3. Moving uploaded files: After the file is uploaded, it is usually saved to a temporary location on the
server. The PHP script can then move the uploaded file to a permanent location on the server, such
as a directory for storing uploaded files.
4. Uploading multiple files: The file upload process can be extended to handle multiple files by
adding multiple file input elements to the HTML form and processing each file in the PHP script
using loops and arrays.

41

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy