PHP Chapter 9
PHP Chapter 9
Development
ITSE 3302
تطوير تطبيقات الشبكة العالمية
Dr. Moamar Elyazgi
PHP Language
Chapter 9
File Inclusion, Files & I/O, Date
and Time and File Uploading
9.1 PHP ─ File Inclusion
You can include the content of a PHP file into another PHP file
before the server executes it.
There are two PHP functions which can be used to included one
PHP file into another PHP file.
1. The include() Function
2. The require() Function
3. include_once()
3
4. require_once()
9.1 PHP ─ File Inclusion
NOTE: You may get plain warning messages or fatal error messages or
nothing at all. This depends on your PHP Server configuration.
10
9.1.3 The require_once() and include_once() Functions
عبارة require_onceمطابقة للعبارة requireباستثناء أن PHP
ستتحقق مما إذا كان الملف مض ّمنًا أم ال ،وذلك لتجنّب تضمينه )(require
مرة أخرى.
الملف المحدد وتعالجه أثناء تنفيذ الشيفرة.
ّ تُ ّ
ضمن العبارة include_once
هذه السلوك مشابه لعبارة includeوالفرق الوحيد هنا هو إن كانت شيفرة
ذلك الملف مض ّمنة من قبل فإنّها لن ت ُ ّ
ضمنَه مرة أخرى ،وترجع
11
include_onceالقيمة ،TRUEوهذا السلوك متوقع من اسم العبارة.
9.2 PHP ─ Files & I/O
One of the benefits of PHP being a server side scripting environment is
that it gives the web developer easy access to the filesystem of the
server on which the web server is running.
This gives us the ability to create, open, delete, read and write to files.
PHP file handling (i/o) became essential to learn when you are going to
deal with files on your web or website using PHP program.
Using PHP, you can easily handle file on the web or on your website.
12
9.2.1 Types of File Handling Actions in PHP
Here are the list of action types used in file handling using PHP:
creating a file
opening a file
writing to a file
appending to a file
reading from a file
closing a file
deleting a file 13
9.2.2 PHP Create File
Here you will learn about how to create a file using PHP with example.
To create a file in PHP, use ‘w’ as file opening mode. This mode is used to
write some content to an existing file, and in case if file doesn't exist
inside the current directory, then this mode creates a new file.
PHP Create File Example
Here is step by step example shows how to create a file using PHP.
Before creating any new file inside the current directory, first see the
screenshot of the folder of current directory, that is, C:\xampp\htdocs\ 14
9.2.2 PHP Create File
<html>
<head>
<title>Create a File in PHP</title>
</head>
<body>
<?php
// new_file.txt is the file, that is going
// to create using this PHP example
// let's initialize that filename with extension
// to a php variable named $create_file_name
$create_file_name = 'new_file.txt';
// below code will creates the file inside
// the current directory يتبع البرنامج 15
$file_handle = fopen($create_file_name, 'w');
9.2.2 PHP Create File
// below code checks if file successfully creates or not
if(!empty($file_handle))
{
echo "<p>File named <b>new_file.txt</b> is created successfully.</p>";
}
// else block is used, if error occurred in creating the file
else
{
echo "<p>Error occurred in creating the file.</p>";
}
// close the file
fclose($file_handle);
?>
</body> 16
</html>
9.2.2 PHP Create File
• Below is the sample output produced by
the above example code in PHP to create
a new file.
• After running the above file creating
program in PHP, you will see there is a
file named new_file.txt is created inside
the current directory. Here is the
screenshot of the current directory after
running the above file creating program.
• If the file new_file.txt already exists inside the current directory, then on running
the above code in your browser, no action will be performed and the file will still be
exist after running and re-running the above program as w mode only creates a new
17
file, if file doesn't exist.
9.2.3 PHP Open File
To open a file in PHP, use fopen() function. Let's see how to open any file on
the web using PHP.
PHP Open File Syntax
Below is the general form to open any file in PHP.
fopen(filename, "filemode");
Let's see the list of file modes used in opening a file along with its
description.
Appending is used only if you don't want to remove the previous content of
18
the file.
9.2.3 PHP Open File
• The PHP fopen()
function is used
to open a file.
• It requires two
arguments
stating first the
file name and
then mode in
which to operate.
• Files modes can
be specified as
one of the six
options in this
table:
19
9.2.3 PHP Open File
To open a file in PHP, use fopen() function. Let's see how to open any file on
the web using PHP.
PHP Open File Syntax
Below is the general form to open any file in PHP.
fopen(filename, "filemode");
Let's see the list of file modes used in opening a file along with its
description.
Appending is used only if you don't want to remove the previous content of
20
the file.
9.2.3 PHP Open File
Let's see how to open file in PHP. This example opens a file in reading mode.
<html>
<head>
<title>Open a File in PHP</title>
</head>
<body>
<?php
$file = fopen("new_file.txt", "r");
if($file)
{
echo "<p>File <b>new_file.txt</b> opened successfully.</p>";
}
21
9.2.3 PHP Open File
Let's see how to open file in PHP. This example opens a file in reading mode.
else
{
echo "<p>Error occurred in opening the file <b>new_file.txt</b></p>";
}
fclose($file); Here is the sample output produced by the above
PHP file opening example code:
?>
</body>
</html>
22
9.2.4 PHP Write to File
To write some content to a file, first you have to open that file in
writing mode.
The code to open a file in writing mode is ‘w’, you have already
learned about it in previous slides.
The ‘w’ opens a file in writing mode and if file doesn't exist inside
the current directory, then this mode creates a new file.
Let's take an example to understand about writing to a file using PHP.
23
9.2.4 PHP Write to File
Let's see an example shows how to write some content to a file in PHP. Here is an example
of writing to a file in PHP.
<html>
<head>
<title>Write to a File in PHP</title>
</head>
<body>
<?php
// $file_name contains name of file to use in this example
$file_name = "codescracker.txt";
// opens file in writing mode, creates if not exist
$file_handle = fopen($file_name, "w");
// checks whether file is opened or not
if($file_handle == false) 24
{
9.2.4 PHP Write to File
echo "<p>Error occurred in opening the file...exiting...</p>";
exit();
}
// writing content to the file codescracker.txt
fwrite($file_handle, "<p>This is writing to a file tutorial in PHP</p>");
// writing again to the same file
fwrite($file_handle, "<p>All the content inside this file is written using PHP
program</p>");
echo "<p>All the content is written to the file successfully.</p>";
// closing file
fclose($file_handle);
?>
</body>
25
</html>
9.2.4 PHP Write to File
Here is the sample output produced by the above write to a file example code in PHP.
After running the above program in your browser,
following content is written to the file named
codescracker.txt
Here is the screenshot of written content
to the file codescracker.txt using above
program in PHP.
If you refresh your browser again and again, then
content of the file will be overwritten. Overwritten
means, previous content will be deleted and new
content will be added. You will learn about how to
append content instead of overwrite in next tutorial. 26
9.2.5 PHP Append to File
Here you will learn about how to append some content in a file using
PHP with example.
If you don't want to delete previous content present inside the file when
adding new content, then use append mode to open and append content
to the file. To open a file in appending mode in PHP, use ‘a’.
PHP Append to File Example
Let's take an example of appending content to a file in PHP.
Here is an example of appending content to file in PHP. 27
9.2.5 PHP Append to File
Let's take an example of appending content to a file in PHP. Here is an example of appending
content to file in PHP.
<html>
<head>
<title>Append to a File in PHP</title>
</head>
<body>
<?php
// $fileName contains name of file to use in this example
$fileName = "myappendfile.txt";
// opens file in appending mode, creates new file if not exist
$fileHandle = fopen($fileName, "a");
// checks whether file is opened or not
if($fileHandle == false) 28
{
9.2.5 PHP Append to File
echo "<p>Error occurred while opening the file...exiting...</p>";
exit();
}
// appending content to the file codescracker.txt
fwrite($fileHandle, "<p>This is appending to a file tutorial in PHP</p>");
// appending again to the same file
fwrite($fileHandle, "<p>All the content inside this file is appended using PHP
program</p>");
echo "<p>All the content is appended to the file successfully.</p>";
// closing the file
fclose($fileHandle);
?>
</body>
</html>
29
9.2.6 PHP Read File
To read content from a file in PHP, use fread() function.
You can also use fgets() and fgetc() to read a file line by line and
character by character.
Ways to Read a File in PHP
Here are the list of three ways, you can go for, to read a file in PHP:
reading a file directly using fread() function
reading a file line by line using fgets()
reading a file character by character using fgetc() 30
9.2.6 PHP Read File
<p>This is reading a file tutorial in PHP.</p> <p>Here
PHP Append to File Example you will learn about how to read a file in PHP both line
by line and character by character.</p> <p>Every
Here is an example of reading a file topics in this reading file tutorial contains its respective
directly using fread() function in examples in PHP.</p>
PHP.
Before going to example of reading
a file, let's first create a file named
codescracker.txt and place the
following content inside it.
Save this file inside the current
directory folder, that is,
C:\xampp\htdocs\
31
9.2.6 PHP Read File
Here is the sample output produced by the above reading a file example code
in PHP.
32
9.2.6 PHP Read File
$myfilehandler = fopen("codescracker.txt",
Reading a File Line by Line "r");
in PHP if($myfilehandler == false)
{
To read a file line by line in PHP,
echo "Error in opening the
use fgets() function. file...exiting...";
Here is an example shows how to exit();
}
read any file line by line in PHP. while(!feof($myfilehandler))
<html> {
<head> echo fgets($myfilehandler);
<title>Reading a file line by }
line using PHP Example</title> fclose($myfilehandler);
</head> ?>
<body> </body>
<?php </html> 33
9.2.6 PHP Read File
The output produced by the above reading a file line by line example code in
PHP is given below:
34
9.2.6 PHP Read File
Reading a File Character by
Character in PHP
o read any file character by
character in PHP, then use PHP
fgetc() function. Here is an
example demonstrates about
reading file character by character.
35
9.2.6 PHP Read File
The output of the above reading a file character by character example code in
PHP is given here:
36
9.2.7 PHP Close File
To close a file in PHP, use fclose()
function. Here is an example of
closing a file in PHP after opening
the file and performing some
action.
37
9.2.7 PHP Close File
Here is the sample output produced by the previous closing a file example
code in PHP.
38
9.2.8 PHP Delete File
39
9.2.8 PHP Delete File
Here is the sample output produced by the previous deleting file example
code in PHP.
40
9.3 PHP Date and Time
Why to use Date/Time on Web using PHP
• You can use date/time on the web or on your website using PHP to
remind that when the work or comment is posted on the website
and many more uses of date and time on web.
• If you want to implement comment system on your website, then
you have to use date and time system there to show when and at
what time the comment was posted by the particular user.
• PHP date() Function
• You can use date() function of PHP to work with date and time.41
9.3 PHP Date and Time
Why to use Date/Time on Web using PHP
• You can use date/time on the web or on your website using PHP to
remind that when the work or comment is posted on the website
and many more uses of date and time on web.
• If you want to implement comment system on your website, then
you have to use date and time system there to show when and at
what time the comment was posted by the particular user.
• PHP date() Function
• You can use date() function of PHP to work with date and time.42
9.3.1 PHP Date and Time
• Here is an example shows how to print current/present date using PHP.
43
9.3.2 PHP Day's Name
• Here is an example shows how to print the name of the current day using PHP.
L Small Letter
44
9.3.3 Print Current Date with Month Name
• Here is an example shows <html>
<head>
how to print current date <title>printing current date with month
name using php</title>
using PHP along with month </head>
<body>
name.
<?php
echo "Current Date: ";
echo date("d");
echo " ";
echo date("M");
echo ", ";
echo date("Y");
?>
</body>
45
</html>
9.3.4 Other Examples
The following characters can be used to format the time string:
•h – Represents hour in 12-hour format with leading zeros (01 to 12).
•H – Represents hour in in 24-hour format with leading zeros (00 to 23).
•i – Represents minutes with leading zeros (00 to 59).
•s – Represents seconds with leading zeros (00 to 59).
•a – Represents lowercase ante meridian and post meridian (am or pm).
•A – Represents uppercase ante meridian and post meridian (AM or PM).
<?php
echo date("h:i:s") . "<br>"; 04:57:56
echo date("M,d,Y h:i:s A") . "<br>"; Apr,19,2021 04:57:56 PM
echo date("h:i a"); 04:57 pm
?>
46
9.3.4 Other Examples
Adding, Subtracting, and Comparing Dates
<?php
$present = date_create('now');
$future = date_create('last day of January 2024');
$interval = date_diff($present, $future);
// Output — 05 years, 04 months and 17 days
echo $interval->format('%Y years, %M months and %d days');
$present = new DateTime('now');
$future = new DateTime('last day of January 2024');
$interval = $present->diff($future);
// Output — 05 years, 04 months and 17 days
echo $interval->format('%Y years, %M months and %d days');
?> 47
48