0% found this document useful (0 votes)
71 views42 pages

Files and Directories - PHP

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

Files and Directories - PHP

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

1

CHAPTER 3
FILES AND DIRECTORIES

5/30/2024 By:- Abreham G.


Working with Files
2

Uploading Files
 You may want users to upload files to your Web site.

 For example, you may want users to be able to upload resumes to your
job-search Web site or pictures to your photo album Web site.
 You can display a form that allows a user to upload a file by using an
HTML form designed for that purpose.
 The general format of the form is as follows:

<form enctype=”multipart/form-data” action=”file.php” method=”post”>


<input type=”hidden” name=”MAX_FILE_SIZE” value=”30000”>
<input type=”file” name=”user_file”>
<input type=”submit” value=”Upload File”>
</form>
Working with Files…
3

 Notice the following points regarding the form:


 The enctype attribute is used in the form tag. You must
set this attribute to multipart/form-data when uploading
a file.
 A hidden field is included that sends a value (in
bytes) for MAX_FILE_SIZE. If the user tries to upload a
file that is larger than this value, it won’t upload.
 The input field that uploads the file is of type file.
Working with Files…
4

 When the user submits the form, the file is uploaded to a


temporary location.
 The script that processes the form needs to copy the file to
another location because the temporary file is deleted as
soon as the script is finished.
Accessing Information About An Uploaded File
 Along with the file, information about the file is sent with
the form.
 This information is stored in the PHP built-in array called
$_FILES.
 An array of information is available for each file that
was uploaded.
Working with Files…
5

 You can obtain the information from the array by using the name of the
field.
$_FILES[‘fieldname’][‘name’] – contains filename
$_FILES[‘fieldname’][‘type’] – contains type of file
$_FILES[‘fieldname’][‘tmp_name’] – contains temporary location of file
$_FILES[‘fieldname’][‘size’] – contains size of file
 For example, suppose you use the following field to upload a file:
<input type=”file” name=”user_file”>
If the user uploads a file named test.txt by using the form, the resulting array
that can be used by the processing script looks something like this:
Working with Files…
6

echo $_FILES[‘user_file’][‘name’]; // test.txt


echo $_FILES[‘user_file’][‘type’]; // text/plain
echo $_FILES[‘user_file’][‘tmp_name’]; //D:/WINNT/php92C.tmp
echo $_FILES[‘user_file’][‘size’]; // 435

 In this array, name is the name of the file that was uploaded, type is
the type of file, tmp_name is the path/filename of the temporary
file, and size is the size of the file.
 Notice that name contains only the filename, while tmp_name
includes the path to the file as well as the filename.
 If the file is too large to upload, the tmp_name in the array
is set to none, and the size is set to 0.
Working with Files…
7

Moving Uploaded Files To Their Destination


 Since the temporary file created during upload is
deleted when the script finishes, it has to be moved to
another location if you want to store it permanently.
 The general format of the statement that moves the file
is as follows:
move_uploaded_file(path/tempfilename, path/permfilename);

 You can use the following statement to move the file to


your desired location, in this case, c:\data\new_file.txt:
move_uploaded_file($_FILES[‘user_file’][‘tmp_name’],
‘c:/data/new_file.txt’);
The destination directory (in this case, c:\data) must exist before the file can be moved
to it.
8 This statement doesn’t create the destination directory.

<html>
<head><title>File Upload</title></head>
<body>
<ol>
<li>Enter the name of the picture you want to upload to our picture archive or use the
browse button to navigate to the picture file.</li>
<li>When the path to the picture file shows in the text field, click the Upload Picture
button.</li>
</ol>
<form enctype=”multipart/form-data” action=”uploadFile.php” method=”POST”>
<input type=”hidden” name=”MAX_FILE_SIZE” value=”500000”>
<input type=”file” name=”pix” size=”20”>
<p><input type=”submit” name=”Upload” value=”Upload Picture”>
</form>
</body>
</html>
<?php
if($_FILES[‘pix’][‘tmp_name’] == “”)
{
9
echo “<b>File did not successfully upload. File size must be less than 500K.<br>”;
include(“form upload.html”);
exit();
}
if(!ereg(“image”,$_FILES[‘pix’][‘type’]))
{
echo “<b>File is not a picture. Please try another file.</b><br>”;
include(“form upload.inc”);
exit();
}
else
{
$destination = ‘c:\data’.”\\”.$_FILES[‘pix’][‘name’];
$temp_file = $_FILES[‘pix’][‘tmp_name’];
move_uploaded_file($temp_file,$destination);
echo “<p>The file has successfully uploaded: $_FILES[‘pix’][‘name’]
$_FILES[‘pix’][‘size’]”;
}
?>
File Input/Output
10

 Many applications require the long-term storage of information.


 Information can be stored on the server in flat files or in databases.
 Flat files are text files stored in the computer file system.
 You can access and edit these files by using any text editors such as
notepad or gedit.
 The information in the flat file is stored as strings, and the PHP script that
retrieves the data needs to know how the data is stored.
 For example, to retrieve a customer name from a file, the PHP script needs
to know that the customer name is stored in the first 20 characters of every
line.

 Using a database for data storage requires you to install and learn to use
database software, such as MySQL or Oracle.
 The data is stored in the database and can only be accessed by the
database software.
 Databases can store very complex information that you can retrieve easily.
File Input/Output…
11

 You don’t need to know how the data is stored, just


how to interact with the database software.
 The database software handles the storage and
delivers the data, without the script needing to know
exactly where or how the customer name is stored.
File Input/Output…
12

Using Flat Files


 Flat files are also called text files.

 Using a flat file requires three steps:


 Open the file.
 Write data into the file or retrieve data from the file.
 Close the file.

 The first step, before you can write information into or read information
from a file, is to open the file.
 The following is the general format for the statement that opens a file:
$fh = fopen(“filename”,”mode”)

 The variable, $fh, referred to as a file handle, is used in the statements that
write data to or read data from the opened file.
 $fh contains the information that identifies the location of the open file.
File Input/Output…
13

Mode what it means what happens when file does not exist
r read only If the file does not exist, a warning message is
displayed.
r+ reading and writing If the file does not exist, a warning message is
displayed.
w write only If the file does not exist, PHP attempts to create it. If
the file exists, PHP overwrites it.
w+ reading and writing If the file does not exist, PHP attempts to create it. If
the file exists, PHP overwrites it.
a append data at the end If the file does not exist, PHP attempts to create it.
of file
a+ reading and appending If the file does not exist, PHP attempts to create it.
File Input/Output…
14

 You can open the file grade.txt to read the information in the file
with the following statement:
$fh = fopen(“grade.txt”,”r”);

 Based on this statement, PHP looks for grade.txt in the current


directory, which is the directory where your PHP script is located.
 If the file can’t be found, a warning message is displayed.

 A warning condition does not stop the script.


 The script continues to run, but the file isn’t open, so statements that
read or write to the file aren’t executed.
 You probably want the script to stop if the file can’t be opened.
 You can do this with a die statement, as follows:
$fh = fopen(“file1.txt”,”r”) or die(“Can’t open file”);
File Input/Output…
15

Opening files in write mode


 You can open a file in a specified directory to store information by
using the following type of statement:
$fh = fopen(“c:/testdir/happy.txt”,”w”);

 If the file does not exist, it is created in the indicated directory.


 However, if the directory doesn’t exist, the directory is not created,
and a warning is displayed.

 You can also open a file on another Web site by using a statement
such as the following:
$fh = fopen(“http://www.data.com/index.html”,”r”);
 You can use a URL only with a read mode, not with a write mode.
File Input/Output…
16

 To close a file after you have finished reading or writing it, use:
fclose($fh);
 In this statement, $fh is the file handle variable you created when
you opened the file.

Reading from file


 You can read from a file by line by line using the fgets statement,
which has the following general format:
$line = fgets($fh);

 Sometimes you want to read strings of a certain size from a file.


 You can tell fgets to read a certain number of characters:
$line = fgets($fh, n);
 This statement tells PHP to read a string that is n-1 characters long
until it reaches the end of the line or the end of the file.
File Input/Output…
17

 You can check the end of file by using feof function:


feof($fh);
 Example: a program that reads file line by line until end of
file and displays it
<?php
$fh = fopen("test.txt", "r") or die("Can't open file");
while(!feof($fh))
{
$line = fgets($fh);
print (“<br>$line");
}
fclose($fh);
?>
File Input/Output…
18

 Another option is to read a single character at a time from a file.


 You can do this using the fgetc() function.
 We can replace the while loop in our original script with one that
uses fgetc():
while (!feof($fp)) {
$char = fgetc($fp);
echo ($char);
}
 This code reads a single character from the file at a time and stores
it in $char, until the end of the file is reached.

 We can also read the whole file in one go.


 This can be done using readfile().
readfile(“test.txt”);
File Input/Output…
19

Writing to a File
 Writing to a file in PHP is relatively simple.
 You can use either of the functions fwrite() or fputs()
 fputs() is an alias to fwrite().
 We call fwrite() in the following:
fwrite($fp, $outputstring);

 This tells PHP to write the string stored in $outputstring to the file pointed to
by $fp.
 The function fwrite() actually takes three parameters but the third one is
optional.
 The prototype for fwrite() is:
int fwrite(int fp, string str, int [length]);
File Input/Output…
20

 The third parameter, length, is the maximum number of bytes


to write.
 If this parameter is supplied, fwrite() will write string to the file
pointed to by fp until it reaches the end of string or has written
length bytes, whichever comes first.
 Example: write data to file
<?php
$fh = fopen(“test.txt”,”a”);
$data = “This content is written to file \n”;
$data = $data . “This line is also written”;
fwrite($fh, $data);
fclose($fh);
?>
File Input/Output…
21

Getting information about files


 Often you want to know information about a file.

 PHP has functions that allow you to find out file information about the files
from within a script.

 You can find out whether a file exists with the file_exists statement, as
follows:
$result = file_exists(filename);
 After this statement, $result contains either TRUE or FALSE.
 The function is often used in a conditional statement, such as the following:
if(!file_exists(“stuff.txt”))
{
echo “File not found!\n”;
}
Working with Date and Time
22

 PHP's time() function gives you all the information that you
need about the current date and time.
 It requires no arguments and returns an integer.
 For us humans, the returned number is a little hard on the
eyes, but it's extremely useful nonetheless.
echo time();
output:
1060751270
 This represents August 12th, 2003 at 10:07PM
 PHP offers excellent tools to convert a timestamp into a
form that humans are comfortable with.
Working with Date and Time…
23

 There are two ways to get useful information from timestamp:


 Using getdate() function
 Using date() function

 The getdate() function optionally accepts a timestamp and


returns an associative array containing information about the
date.
 If you omit the timestamp, getdate() works with the current
timestamp as returned by time().
 The table lists the elements contained in the associative array
returned by getdate().
Working with Date and Time…
24

Key Description Example


seconds Seconds past the minute (0–59) 28
minutes Minutes past the hour (0–59) 7
hours Hours of the day (0–23) 12
mday Day of the month (1–31) 20
wday Day of the week (0–6) 4
mon Month of the year (1–12) 1
year Year (4 digits) 2000
yday Day of year (0–365) 19
weekday Day of the week (name) Thursday
month Month of the year (name) January
0 Timestamp 948370048
Working with Date and Time…
25

 Example: Acquiring date information with getdate()


<?php
$date_array = getdate(); //no argument passed, today's date used
foreach ($date_array as $key => $val)
echo "$key = $val <br>";
?>
<hr>
<?php
echo "Today's date: ".$date_array['mon']."/".$date_array['mday'].
"/".$date_array['year'];
?>
Working with Date and Time…
26

 The output is:


seconds = 53
minutes = 26
hours = 11
mday = 29
wday = 2
mon = 11
year = 2011
yday = 332
weekday = Tuesday
month = November
0 = 1322555213
Today's date: 11/29/2011

 The main method to format a timestamp is using date($format... [, $timestamp]).


 You pass a series of codes indicating your formatting preferences, plus an
optional timestamp.
date(‘Y-m-d’); //year-month-date
Format Description Example
a am or pm (lowercase) pm
A AM or PM (uppercase) PM
d Day of month (number with leading zeroes) 20
27 D Day of week (three letters) Thu
F Month name January
h Hour (12-hour format—leading zeroes) 12
H Hour (24-hour format—leading zeroes) 12
g Hour (12-hour format—no leading zeroes) 12
G Hour (24-hour format—no leading zeroes) 12
i Minutes 47
j Day of the month (no leading zeroes) 20
l Day of the week (name) Thursday
L Leap year (1 for yes, 0 for no) 1
m Month of year (number—leading zeroes) 09
M Month of year (three letters) Sep
n Month of year (number—no leading zeroes) 9
s Seconds of hour 24
S Ordinal suffix for the day of the month th
r Full date standardized to RFC 822 Mon, 15 Sep 2003
08:25:55 -0700
U Timestamp 1063639555
y Year (two digits) 00
Y Year (four digits) 2003
z Day of year (0–365) 257
Z Offset in seconds from GMT 0
Working with Date and Time…
28

 Example:
<html>
<head>
<title>Formatting a date with date()</title>
</head>
<body>
<?php
$time = time(); //stores the exact timestamp to use in this script
echo date("m/d/y G:i:s", $time);
echo "<br> Today is “.date("j \of F Y, \a\\t g.i a", $time);
?>
</body>
</html>

Output:
11/29/11 11.26:53
Today is 29 of November 2011, at 11.26 am
Working with Date and Time…
29

 You can get information about the current time, but you
cannot yet work with arbitrary dates.
 mktime() returns a timestamp that you can then use with

date() or getdate().
 mktime() accepts up to six integer arguments in the following

order: Hour, Minute, Seconds, Month, Day of month, Year.


 The format is:

$dt = mktime(hour, minute, seconds, month, date, year);

 For example, you would store the date January 15, 2003,
by using the following statement:
$birthdate = mktime(0, 0, 0, 1, 15, 2003);
Working with Date and Time…
30

<?php
// make a timestamp for Aug 23 2003 at 4.15 am
$ts = mktime(4, 15, 0, 8, 23, 2003);
echo date("m/d/y G.i:s", $ts);
echo "<br>";
echo "The date is ";
echo date("j of F Y, \a\\t g.i a", $ts );
?>

 Output:
08/23/03 4.15:00
The date is 23 of August 2003, at 4.15 am
Working with Date and Time…
31

 You might need to accept date information from user input.


 Before you work with a user-entered date or store it in a database,
you should check that the date is valid.
 This can be done using checkdate() that accepts three integers:
month, day, and year.
 checkdate() returns true if the month is between 1 and 12, the day is
acceptable for the given month and year, and the year is between 0
and 32767.

 Be careful, though a date might be valid, it may not be acceptable


to other date functions.
 For example, the following line returns true:
checkdate(4, 4, 1066);
Mathematical Functions
32

 PHP has built-in mathematical constants, and trigonometric,


logarithmic, and base conversion functions.
 PHP constants are:
Constant Description Constant Description
M_PI Pi M_SQRT2 sqrt(2)
M_PI_2 pi/2 M_SQRT1_2 1/sqrt(2)
M_PI_4 pi/4 M_LOG2E log2(e)
M_1_PI 1/pi M_LOG10E log10(e)
M_2_PI 2/pi M_LN2 loge(2)
M_2_SQRTPI 2/sqrt(pi) M_LN10 loge(10)
M_E the constant e
function Behavior
pow() Takes two numerical arguments and returns the first argument raised to the power
of the second. The value of pow($x, $y) is xy.
exp()
33 Takes a single argument and raises e to that power. The value of exp($x) is ex.
log() The “natural log” function. Takes a single argument and returns its base e
logarithm. If ey = x, then the value of log($x) is y.
log10() Takes a single argument and returns its base-10 logarithm. If 10y = x, then the value
of log10($x) is y.
pi() Takes no arguments and returns an approximation of pi (3.1415926535898). Can be
used interchangeably with the constant M_PI.
sin() Takes a numerical argument in radians and returns the sine of the argument as a
double.
cos() Takes a numerical argument in radians and returns the cosine of the argument as a
double.
tan() Takes a numerical argument in radians and returns the tangent of the argument as a
double.
asin() Takes a numerical argument and returns the arcsine of the argument in radians.
Inputs must be between –1.0 and 1.0, otherwise, it will return a result of NAN.
Results are in the range –pi / 2 to pi / 2.
acos() Takes a numerical argument and returns the arccosine of the argument in
radians. Inputs must be between –1.0 and 1.0, otherwise, it will return a result
of NAN. Results are in the range 0 to pi.
34
atan() Takes a numerical argument and returns the arctangent of the argument in
radians. Results are in the range –pi / 2 to pi / 2.
sqrt ($num) Returns square root of a number.
floor($float) Returns the next lowest integer value by rounding down value.
ceil($float) Returns the next highest integer value by rounding up value.
round($val Returns the rounded value of val to specified precision (number of digits after
[,precision]) the decimal point). precision can also be negative or zero (default).
abs($numb) Returns the absolute value of number.
Mathematical Functions….
35

 Example:
echo pow(2, 8); //256
echo log10(100); //2
echo sqrt(9); // 3
echo ceil(4.3); // 5
echo round(3.4); // 3
echo round(3.6); // 4
echo round(1.95583, 2); // 1.96
echo round(1241757, -3); // 1242000
echo pi(); // 3.1415926535898
Mathematical Functions…
36

Function Behavior
bindec() Takes a single string argument representing a binary (base 2)
integer, and returns a string representation of that number in base
10.
decbin() Like bindec(), but converts from base 10 to base 2.
octdec() Like bindec(), but converts from base 8 to base 10.
decoct() Like bindec(), but converts from base 10 to base 8.
hexdec() Like bindec(), but converts from base 16 to base 10.
dechex() Like bindec(), but converts from base 10 to base 16.
base_convert() Takes a string argument (the integer to be converted) and two
integer arguments (the original base, and the desired base).
Returns a string representing the converted number—digits higher
than 9 (from 10 to 35) are represented by the letters a–z. Both the
original and desired bases must be in the range 2–36.
Mathematical Functions…
37

 Example:
function display_bases($val, $first_base) {
for ($new_base = 2; $new_base <= 9; $new_base++)
{
$converted = base_convert($val, $first_base, $new_base);
print(“$val in base $first_base is $converted in base $new_base<BR>”);
}
}
display_bases(“150”, 10);

 Output:
150 in base 10 is 10010110 in base 2
150 in base 10 is 12120 in base 3
150 in base 10 is 2112 in base 4
150 in base 10 is 1100 in base 5
150 in base 10 is 410 in base 6
150 in base 10 is 303 in base 7
150 in base 10 is 226 in base 8
150 in base 10 is 176 in base 9
Reusing Code
38

 One of the goals of software engineers is to reuse code in lieu of writing


new code.
 Reusing existing code reduces costs, increases reliability, and improves
consistency.
 Ideally, a new project is created by combining existing reusable
components, with a minimum of development from scratch.

 PHP provides two very simple, yet very useful, statements to allow you to
reuse any type of code.
 Using include or require statement, you can load a file into your PHP script.
 The file can contain anything you would normally type in a script including
PHP statements, text, HTML tags, etc
//openfile.php
<?php
$fp = fopen($name, $mode);
if($fp)
39 {
echo “Could not open the file.”
return 0;
}
else
return 1;
?>

<?php
$name = “file.txt”;
$mode = “r”;
$result = include(“openfile.php”);
if($result == 1)
{
//continue reading/writing the file
}
?>
Exercise
40

 Write a PHP function that accepts a, b, and c and solve


quadratic equation
41

 Be the digger of

Live For What You Believe!!!!!!!


End of Chapter Three
42

Question
Comment

Thank you!

You might also like