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

Chapter 3 PHP

A University CEP (Continuing Education Program) Students Payment Management System

Uploaded by

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

Chapter 3 PHP

A University CEP (Continuing Education Program) Students Payment Management System

Uploaded by

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

CHAPTER 3

DATABASE DRIVEN
WEBSITES
3.1 Working with Forms
 We use one of two methods to submit form information.
 The methods pass the form data differently and have
different advantages and disadvantages
 GET method:
 The form data is passed by adding it to the URL that calls
the form-processing script.
 For example, the URL may look like this:
processform.php?lname=Smith&fname=Goliath
 The advantages of this method are simplicity and speed.
 The disadvantages are that
 less data can be passed and
 the information is displayed in the browser, which can be a
security problem in some situations.
3.1 Working with
Forms…
 POST method:
 The form data is passed as a package in a separate
communication with the processing script.
 The advantages of this method are unlimited information
passing and security of the data.
 The disadvantages are the additional overhead and slower
speed.
 The form data is available in the processing script in the PHP
built-in arrays.
 Information from forms that use the POST method is available in
the built-in array called $_POST.
 If your form uses the GET method, the information is available in
the array $_GET.
 Both types of form information are also stored in an array called
$_REQUEST.
 You get information from the array by using the form field name
3.1 Working with
Forms…
 The syntax is:
$_POST[“form element name”]
$_GET[“form element name”]
 For example, suppose that you echo the following field in
your form that uses the POST method:
<input type=’text’ name=’firstName’>;
 The value entered in this textbox can be accessed by
$_POST[‘firstName’]
 This contains the text the user typed into the field.
 If the form uses GET method, the above textbox can be
accessed as
$_GET[“firstName”]
3.1 Database Programming
 PHP is particularly strong in its ability to interact with databases.
 PHP supports pretty much every database out there
 The most commonly used database with PHP is MySQL

 MySQL is a free and open source database that has a lot of users
especially for web applications.
 It can be downloaded from internet freely.

 Whichever database you’re using, the steps to interact with a


database are similar:
1. Connect to the database.
2. Send an SQL query that contains instructions for the database
software.
3. If you retrieved data from the database, process the data.
4. Close the connection to the database.
3.1 Database
Programming…
Connecting to the database
 The first step in a database interaction is connecting to the

database.
 You use a PHP function to connect to the database.

 To make the connection, you need to supply the function with three
things:
 Location:
 The database may not be on the same computer where PHP is installed.
 Therefore, you need to tell the PHP connect function the name of the
computer where the database is located.
 You can supply either a domain name (such as mycompany.com) or an
IP address (such as 172.17.204.2).
 If the database is on the same computer as PHP, you can use localhost
for the hostname.
 Account name: You must provide a valid account name that can be used
to access the database.
 Password: You have to have a valid password to access the database.
3.1 Database
Programming…
 The syntax for creating connection to MySQL
database:
$connect = mysql_connect($host, $account,
ID $password);
FirstName LastName Sex Telephone Status
sam232 John Walter M 4325456342 1
sam543 Samuel David M 5424256345 1
sam534 George Graham M 2634345643 0
sam979 Ana Bush F 3462737485 0

Sample database table used as an


example
3.1 Database
Programming…
 After connecting to the database, the next step is selecting
database.
 An RDBMS can create and maintain many databases, so
you need to tell it which database you want to use.

 The syntax for selecting database is:


$db = mysql_select_db(string database, [int
database_connection] );

 Example:
<?php
$con = mysql_connect("localhost",“root",“vertrigo");
mysql_select_db(“books”);
//other statements
?>
3.1 Database
Programming…
Querying the Database
 To actually perform the query, we can use the

mysql_query() function.
 Before doing this, however, it’s a good idea to set up

the query you want to run:


$query = “select * from books“;

 We can now run the query:


$result = mysql_query($query);

 The mysql_query() function has the following prototype:


int mysql_query(string query, [int dbconnection] );

 You pass it the query you want to run, and optionally,


the database connection created.
3.1 Database
Programming…
 If connection isn’t specified, the function will use the last
opened link.
 If there isn’t one, the function will open the default one as if
you had called mysql_connect().

 You might want to use the mysql_db_query() function instead.


int mysql_db_query(string database, string query, [int
dbconnection] );

 It’s very similar but allows you to specify which database you
would like to run the query on.
 It is like a combination of the mysql_select_db() and
mysql_query() functions.
 Both of these functions return a result identifier that allows
you to retrieve the query results or false on failure.
3.1 Database
Programming…
 Example: executing query
$sql = “SELECT * FROM Product”;
$result = mysql_query($sql, $connect);
 Putting all together:
<?php
$account = “david”;
$password = “gotago”;
$host= “localhost”;
$connect = mysql_connect($host, $account, $password);
$db = mysql_select_db(“Catalog”, $connect);
$sql = “SELECT * FROM Product”;
$result = mysql_query($sql, $connect);
//other code
?>
3.1 Database
Programming…
 Customers table

ID Name Address Sex City income


1 John Walter 23 New Street M New York 43254

2 Samuel David Que street 70 M Montreal 54242


3 George Graham Lamore 32 M Paris 26343
4 Ana Bush Prus street 52 F Berlin 34627
5 Li Xien Tianmen square M Beijing 9056
30
3.1 Database
Programming…
 Create table Customers(
customerid int not null auto_increment primary key,
name varchar(30) not null,
sex varchar(15) not null,
address varchar(40) not null,
city varchar(20) not null,
income int,
);

 Insert into table[(column1, clumn2, column3, …)] values


(value1, value2, value3, …)
 Insert into customers(customerID, name, address, city,
income) values(NULL, “Anna Schmit”, ‘25 Oak Street’,
3.1 Database
Programming…
 Select columname list or *
From tablenames
[Where condition]
[Group By grouptype]
[Having where_definition]
[Order By order_type [ASC|DESC]]
[Limit limit_criteria];

 Select name, city


from Customers

 Select *
from Customers
3.1 Database
Programming…
3.1 Database
Programming…
 Select AVG(income)
From customers

 Select count(*)
From customers

 SELECT column_name(s)
FROM table1LEFT JOIN|RIGHT JOIN|INNER JOIN|JOIN table2
ON table1.columnname=table2.columnname

SELECT *
FROM customer inner join security
on customer.CustomerID=security.userID
3.1 Database
Programming…
SELECT name, city, username
FROM customer left join security
on customer.CustomerID=security.userID

 Update tablename
Set column1=value1, column2=value2,…
[where condition]

 Update customers
Set address=‘250 Olsens Road’, city=‘New York’
Where customerid=‘4’
3.1 Database
Programming…
 Delete from tablename
[Where condition]

 Delete from customers


where customerid=5;

 What does this do?


Delete from table;
3.1 Database
Programming…
 Alter table tablename
ADD|DROP|MODIFY|CHANGE Column

 Alter table customers


Add Column sex varchar(10) not null
After name;

 Alter table customers


Drop city

 Alter table customers


Modify name varchar(50) not null;
3.1 Database
Programming…
 Drop table tablename
Drop table customers

 Drop database databasename


Drop database lab
3.1 Database
Programming…
 Example: executing query
$sql = “SELECT * FROM Product”;
$result = mysql_query($sql, $connect);
 Putting all together:
<?php
$account = “david”;
$password = “gotago”;
$connect = mysql_connect($host, $account, $password);
$db = mysql_select_db(“Catalog”, $connect);
$sql = “SELECT * FROM Product”;
$result = mysql_query($sql, $connect);
//other code
?>
3.1 Database
Programming…
Processing Data
 To process the data returned from database, you need

to get it from the temporary table where it is placed


when the SQL query is executed.
 We use PHP database functions to get the data from

the temporary table.

 The data is stored in the temporary table in rows and


columns.
 You can use PHP functions to retrieve one row from
the table and store it in an array
 The array has the field names as the array keys.
 For MySQL, the statement is as follows:
$row = mysql_fetch_array($result);
3.1 Database
Programming…
 It requires one of the mysql_fetch functions to
make the data fully available to PHP.
 The fetching functions of PHP are as follows:
 mysql_fetch_array: returns rows as associative or
numbered array
 mysql_fetch_assoc: returns rows as associative array
 mysql_fetch_row: returns row as an enumerated array
 mysql_fetch_object: returns row as an object
 mysql_result: returns one cell of data
 The difference between the three main fetching
functions is small.
3.1 Database
Programming…
 The most useful fetching function, mysql_fetch_array, offers
the choice of results as an associative or an enumerated array
or both
 The default is returning as both (index or key).
 This means you can refer to outputs by database field name
rather than number:
$query = “SELECT ID, LastName, FirstName FROM users WHERE Status = 1”;
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
echo “$row[‘ID’], $row[‘LastName’], $row[‘FirstName’]<BR>\n”;
}
3.1 Database
Programming…
 mysql_fetch_array can also be used with
numerical identifiers rather than field names.
 If you want to specify index or field name rather
than making both available, you can do it like
this:
$offset_row = mysql_fetch_array($result, MYSQL_NUM);
$associative_row = mysql_fetch_array($result,
MYSQL_ASSOC);

 It’s also possible to use MYSQL_BOTH as the


second value.
$both = mysql_fetch_array($result, MYSQL_BOTH);
3.1 Database
Programming…
 The mysql_fetch_assoc function returns an associative array
that corresponds to the fetched row.
 It returns FALSE if there are no more rows.
 mysql_fetch_assoc() is equivalent to calling mysql_fetch_array()
with MYSQL_ASSOC for the optional second parameter.
 It only returns an associative array.

$query = “SELECT ID, LastName, FirstName FROM users WHERE Status =


1”;
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result))
{
echo “$row[‘ID’], $row[‘LastName’], $row[‘FirstName’]<BR>\n”;
}
3.1 Database
Programming…
 The function mysql_fetch_object performs much the same
task
 But the row is returned as an object rather than an array.
 Obviously, this is helpful for those among those who utilize
the object-oriented notation:
$query=“SELECT ID, LastName, FirstName FROM users WHERE
Status = 1”;
$result = mysql_query($query);
while ($row = mysql_fetch_object($result))
{
echo $row->ID;
echo $row->FirstName;
echo $row->LastName<BR>\n”;
}
3.1 Database
Programming…
 The most general one is mysql_fetch_row, which
can be used something like this:
$query = “SELECT ID, LastName, FirstName FROM users WHERE
Status = 1”;
$result = mysql_query($query);
while ($name_row = mysql_fetch_row($result))
{
print(“$name_row[0] $name_row[1] $name_row[2]<BR>\n”);
}
 This code will output the specified rows from the
database, each line containing one row or the
information associated with a unique ID.
3.1 Database
Programming…
 In early versions of PHP, mysql_fetch_row was considered to be
faster than mysql_fetch_object and mysql_fetch_array, but this is
no longer an issue.
 The PHP group now recommends use of mysql_fetch_array over
mysql_fetch_row because it offers increased functionality and
choice.

 Last and least of the fetching functions is mysql_result().


 Use this function only in situations where you are positive you
need only one piece of data to be returned from MySQL.
$query = “SELECT count(*) FROM users”;
$db_result = mysql_query($query);
$datapoint = mysql_result($db_result, 0, 0);

 The mysql_result function takes three arguments: result identifier,


row identifier, and field.
 Field can take the value of the field offset as above, or its name as
 Example: a program that retrieves data from database and
display in table
<?php
$con = mysql_connect("localhost","root","vertrigo");
mysql_select_db(“customers”);
$query = “SELECT * FROM users”;
$result = mysql_query($query);
echo(“<TABLE border=’1’>”);
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo('<TD> '.$row["ID"].' </TD> ');
echo('<TD>'. $row["firstname"] . '</TD> ');
echo('<TD> '.$row["lastname"] .'</TD> ');
echo('<TD> '.$row["sex"].' </TD> ');
echo "</tr>";
}
echo(“</TABLE><BR>\n”);
?>
3.1 Database
Programming…
Inserting Data into Database
 Inserting new items into the database is

remarkably similar to getting items out of


the database.
 You follow the same basic steps

 make a connection,
 send a query, and
 check the results.
 In this case, the query you send will be an
INSERT rather than a SELECT.
3.1 Database
Programming…
3.1 Database
Programming…
<HTML>
<HEAD>
<TITLE>Processing HTML forms with PHP</TITLE>
</HEAD>
<BODY>
<H1>Newsletter sign-up form</H1>
<P> Please, fill the form to be our registered customer</P>
<FORM METHOD=”post” ACTION=”customer.php”>
ID: <INPUT TYPE=”text” NAME=”ID”> <BR>
First name: <INPUT TYPE=”text” NAME=”FirstName”> <BR>
Last name: <INPUT TYPE=”text” NAME=”LastName”> <BR>
Sex: <INPUT TYPE=”text” NAME=”Sex”> <BR>
Telephone: <INPUT TYPE=”text” NAME=”Telephone”> <BR><BR>
<INPUT TYPE=”submit” NAME=”submit” VALUE=”Submit”>
</FORM>
</BODY>
The customer.php file that process the data collected by the above form is the
following:
<?php
// Open connection to the database
$con = mysql_connect(“localhost”, “phpuser”, “sesame”) or
die(“Failure to connect to database”);
mysql_select_db(“customers”);

$ID = $_POST[“ID”]);
$fn = $_POST[“FirstName”];
$ln = $_POST[“LastName”];
$sx = $_POST[“Sex”];
$tl = $_POST[“Telephone”];
$st = “1”;

$query = “INSERT INTO users VALUES($ID, $fn, $ln, $sx, $tl, $st)”;
$result = mysql_query($query);
if (mysql_affected_rows($result) >= 1)
echo ‘<P>Your information has been saved.</P>’;
else
echo ‘<P>Something went wrong with your signup attempt.</P>’;
?>
3.1 Database
Programming…
 In addition to insertion, you can do many other operations on database
using SQL
 SELECT item_list FROM table_list WHERE search_condition;
select lname, fname, balance from account where balance > 10000
 CREATE TABLE table-name (column-name data-type, .... )
Create table customer(lname varchar(20), fname varchar(20), branch
varchar(30), balance number);
 INSERT INTO table_name(column_names) VALUES (value_list)
INSERT INTO account (lname, fname, branch, balance) VALUES ('john',
'smith', 101, 10000)
 DELETE FROM table_name WHERE search_condition
DELETE FROM account where fname = 'john' and lname = 'smith'
 UPDATE table_name SET column_names expression WHERE condition
UPDATE account SET balance = balance * 1.06 where balance > 1000
3.1 Database
Programming…
Closing the connection
 Any open database connections are closed when
the script ends.
 However, it is good programming practice to
close the connections in the script to avoid any
possible problems.
 You close database connections with a PHP
function
 For example, for MySQL, use the following
function to close a database connection:
mysql_close($connect);
Other PHP-Database Functions

 mysql_affected_rows () — Get number of affected rows in


previous MySQL operation.
 It helps you to know how many rows have been deleted,
inserted, modified, etc. by the last mysql_query() operation.
int mysql_affected_rows ( [resource link_identifier])

 mysql_affected_rows() returns the number of rows affected by


the last INSERT, UPDATE or DELETE query associated with
link_identifier.

 mysql_create_db () — Create a MySQL database. The syntax is:


bool mysql_create_db (string databasename [, resource link_identifier]);
 mysql_create_db() attempts to create a new database on the
server associated with the specified link identifier.
Other PHP-Database
Functions…
 mysql_drop_db — Drop (delete) a MySQL database
 mysql_drop_db() attempts to drop (remove) an entire database
from the server associated with the specified link identifier.
bool mysql_drop_db (string database_name [, resource
link_identifier])

 mysql_num_rows — Get number of rows in result.


 The syntax is:
int mysql_num_rows (resource result);
 mysql_num_rows() returns the number of rows in a result set.
 This command is only valid for SELECT statements.
 To get rows affected by INSERT, UPDATE or DELETE query, use
mysql_affected_rows().

 mysql_num_fields — Get number of fields in result. The syntax is:


int mysql_num_fields (resource result);
Other PHP-Database
Functions…
 mysql_field_name — Get the name of the specified field in a
result.
string mysql_field_name (resource result, int field_index)
 mysql_field_name() returns the name of the specified field index.
 field_index is the numerical offset of the field.
 Note that field_index starts at 0.

 mysql_list_tables — List tables in a MySQL database.


resource mysql_list_tables (string database [, resource link_identifier])
 mysql_list_tables() takes a database name and returns a result
pointer much like the mysql_query() function.
 You can use the mysql_tablename() function to extract the actual
table names from the result pointer, or any other result table
function such as mysql_fetch_assoc().
Other PHP-Database
Functions…
<?php
$link = mysql_connect('localhost', 'root', 'vertrigo');
$db_list = mysql_list_dbs($link);
while ($row = mysql_fetch_row($db_list)) {
echo $row[0] . "<br>";
}

$tn = mysql_list_tables(“lab", $link);


while($row = mysql_fetch_array($tn, MYSQL_NUM))
{
echo $row[0]."<br>";
}
?>
Using ODBC
 PHP can also connect to databases by using ODBC.
 There are the functions you can use for such purpose.

odbc_connect ( string datasourcename, string user, string


password [, int cursor_type])
 This function returns an ODBC connection id or 0 on error.

 The connection id returned by this functions is needed by other

ODBC functions.
 You can have multiple connections open at once.

 The optional fourth parameter sets the type of cursor to be used


for this connection.
 This parameter is not normally needed, but can be useful.
 The following constants are defined for cursortype:
 SQL_CUR_USE_IF_NEEDED
 SQL_CUR_USE_ODBC
 SQL_CUR_USE_DRIVER
Using ODBC…
odbc_exec (resource connection_id, string
query_string)
 This returns an ODBC result identifier if the SQL
command was executed successfully.
 odbc_exec() will send an SQL statement to the
database server specified by connection_id.
 This parameter must be a valid identifier returned by
odbc_connect().

odbc_do (resource conn_id, string query)


 This will execute a query on the given connection just
like odbc_exec.
Using ODBC…
 odbc_fetch_array ( resource result [, int rownumber])
 This fetches a result row as an associative array

 odbc_fetch_object (resource result [, int rownumber])


 This fetches a result row as an object

 odbc_fetch_row ( resource result_id [, int row_number])


 odbc_fetch_row() fetches a row of the data that was
returned by odbc_do() / odbc_exec().
 After odbc_fetch_row() is called, the fields of that row can
be accessed with odbc_result().
 If row_number is not specified, odbc_fetch_row() will try
to fetch the next row in the result set.
Using ODBC…
 odbc_commit ( resource connection_id)
 All pending transactions on connection_id
are committed.
 It returns TRUE on success, FALSE on
failure.
 odbc_close ( resource connection_id)
 odbc_close() will close down the
connection to the database server
associated with the given connection
identifier.
Using ODBC…
<?php
$con = odbc_connect(“registrar", “root", “vertrigo") or
die("Connecting to databse failed.");
$sql = "select * from student where ID='" . $_POST['ID'].
"'";
$rs = odbc_exec($con, $sql);

while(($row = odbc_fetch_array($rs,
ODBC_ASSOC_ARRAY)) != NULL)
{
print("&nbsp;". $row['fullname']. "<BR>");
print("&nbsp;". $row['birth_date']. "<BR>");
print("&nbsp;". $row['email']. "<BR>");
}
odbc_close($con);
Classes in PHP
 The basic elements of object-oriented programs are objects.
It’s easiest to understand objects as physical objects.
 For example, a car is an object.
 A car has properties, such as color, model, engine, and
tires, also called attributes.
 A car has things it can do, too, such as move forward, move
backward, park, roll over, and play dead (well, mine does
anyway).

 A class is the script that serves as the template that is used


to create an object.
 The class defines the properties, the attributes, of the
object.
 It also defines the things the object can do — its
responsibilities.
Classes in PHP…
Defining a Class
 A minimal class definition looks as follows:

class classname
{
//code
}
 In order to be useful, our classes need attributes and

operations.
 We create attributes by declaring variables within a class

definition using the keyword var.


 The following code creates a class called car with two

attributes, $name and $speed.


 We create operations by declaring functions within the class

definition.
 The following code will create a class named car with two

operations.
Classes in PHP…
class car
{
var $name;
var $speed;
function moveforward()
{
//code here
}
function reverse($param1, $param2)
{
//code here
}
}
Classes in PHP…
Constructors
 Most classes will have a special type of operation called a
constructor.
 A constructor is called when an object is created, and
 performs useful initialization tasks such as setting attributes
to sensible starting values or
 creating other objects needed by this object.

 A constructor is declared in the same way as other operations,


but has the same name as the class.
 We can manually call the constructor
 But its main purpose is to be called automatically when an
object is created.
 In PHP 5 and later, constructors are named __construct().
Classes in PHP…
class car
{
function car($param)
{
echo “Constructor called with parameter $param
<br>”;
}
function __construct()
{
echo “another constructor”;
}
}
Classes in PHP…
Instantiation of Class
 After we have declared a class, we need to create an
object to work with
 Object is a particular individual that is a member of
the class.
 This is also known as creating an instance or
instantiating a class.
 We create an object using the new keyword.
 We need to specify what class our object will be an
instance of, and provide any parameters required by
our constructor.
Classes in PHP…
class person
{
var $name;
function person($param)
{
echo “Constructor called with parameter $param <br>”;
}
}
$a = new person(“First”); //instantiation
$b = new person(“Second”); //another instantiation
$c = new person(); //yet another instantiation

 To access a class method or property, we must use the “->”


operator.
 The keyword “this” tells PHP that the property or method
<?php
class automobile
{
var $color; //the color of the car
var $max_speed; //the maximum speed
var $price; //the price of the car, in dollars
function is_cheap()
{
$this->display();
return ($this->price < 5000); //returns TRUE if the price is smaller than 5000
}
function display()
{
echo "The price is $this->price<br>";
}
function automobile()
{
}
}

$carobject = new automobile();


$carobject->color = "red";
$carobject->price = 6000;

$cheap = $carobject->is_cheap(); //call is_cheap() method of the class


if($cheap)
print "This car is cheap!";
else
print "This car is expensive!";
Classes in PHP…
 Making Properties and Methods Private
 Properties and methods can be public or private.

 Public means that methods or properties inside the class can

be accessed by the script that is using the class or from


another class.
 For example, the following class has a public attribute and a

public method as shown:


class Car
{
var $gas = 0;
function addGas($amount)
{
$this->gas = $this->gas + $amount;
echo “$amount gallons added to gas tank”;
}
Classes in PHP…
 You can prevent access to properties by making them
private.
 PHP provides two options for making properties and methods
private, as follows:
 private: No access from outside the class.
 protected: No access from outside except from a class inherits
current class.

 Example:
class Car {
private $gas = 0;
function addGas($amount)
{
$this->gas = $this->gas + $amount;
echo “$amount gallons added to gas tank”;
}
Classes in PHP…
 In the following code, line 2 and 3 generates
error because $gas is private:
$mycar = new Car();
$gas_amount = $mycar->gas;
$mycar->gas = 20;
Classes in PHP…
Implementing Inheritance in PHP
 If our class is to be a subclass of another, you can use the extends keyword to
specify this.
class A
{
var $attribute1;
function operation1()
{
//code here
}
}
class B extends A
{
var $attribute2;
function operation2()
{
//code here
}
Classes in PHP…
 All the following accesses to operations and attributes of an
object of type B would be valid:
$b = new B();
$b->operation1();
$b->attribute1 = 10;
$b->operation2();
$b->attribute2 = 10;

 Because class B extends class A, we can refer to


operation1() and $attribute1that were declared in class A.
 As a subclass of A, B inherits all the functionality and data.
 In addition, B has declared an attribute and an operation of
its own.
3.2 Working with Files
3.2.1 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>
3.2 Working with Files…
 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.
 MAX_FILE_SIZE in your form need to consider two size settings in
php.ini
 upload_max_filesize: The MAX_FILE_SIZE you send in your upload
form can’t be larger than the value of upload_max_filesize. If you are
uploading a larger file than the current value of upload_max_filesize
(2MB by default), you need to increase that value by editing php.ini.
 post_max_size: The total amount of information you send in a POST
form can’t be larger than the value of post_max_size (8MB by
default). You can increase this value if necessary by editing your
php.ini file.
3.2 Working with Files…
 The value for MAX_FILE_SIZE must be sent before the file is
uploaded if you want the file size limit to apply to the
uploading file.

 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.
 You can use phpinfo() to see where the temporary files are
stored.
 If you don’t like the location of the temporary directory, you
can change it by changing upload_tmp_dir in the php.ini file.
 If no directory is specified in php.ini, a default temporary
3.2 Working with Files…
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.
 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
3.2 Working with Files…
 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:
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.
3.2 Working with Files…
 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.
 By default, PHP stores the temporary
uploaded file in your temp directory on
Windows or /tmp on Unix/Linux.
 You can change the location of temporary
files by setting php.ini.
 Look in your php.ini file for the following line:
upload_tmp_dir =
3.2 Working with Files…
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’);
3.2 Working with Files…
 The destination directory (in this case, c:\data) must exist
before the file can be moved to it.
 This statement doesn’t create the destination directory.

 Security can be an issue when uploading files.


 Allowing strangers to load files onto your computer is risky;
malicious files are possible.
 So, check the files for as many factors as possible after they
are uploaded, using conditional statements to check file
characteristics, such as checking for the expected file type
and for the size.
 In some cases, for even more security, it may be a good idea
to change the name of the file to something else so users
don’t know where their files are or what they’re called.
<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’] == “”)
{
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
 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…
 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.

 Flat files have some advantages over databases:


 Available and versatile: You can create and save data in any operating
system’s file system. You don’t need to install any extra software.
 Additionally, text data stored in flat files can be read by a variety of
software programs, such as word processors or spreadsheets.
 Easy to use: You don’t need to do any extra preparation, such as install
database software, design a database, create a database, and so on.
 Just create the file and store the data with statements in your PHP script.
 Smaller: Flat files store data by using less disk space than databases.
File Input/Output…
 Databases have advantages as well:
 Security: A database provides a security layer of its own, in
addition to the security provided by the operating system.
 A database protects the data from outside intrusion better than
a flat file.
 Accessibility of data: You can store data in a database by
using a very complex data structure, specifying data types and
relationships among the data.
 The organization of the data makes it easy to search the data
and retrieve what you need.
 Ability to handle multiple users: When many users store or
access data in a single file, such as a file containing names and
addresses, a database ensures that users take their turn with
the file to avoid overwriting each other’s data.
File Input/Output…
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…

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…
 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…
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…
 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…
 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…
 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…
 A call to the readfile() function opens the file, echoes the content
to standard output (the browser), and then closes the file.
 The prototype for readfile() is
int readfile(string filename, int [use_include_path]);
 The optional second parameter specifies whether PHP should
look for the file in the include_path.

 The final way we can read from a file is using the fread() function
to read an arbitrary number of bytes from the file.
 This function has the following prototype:
string fread(int fp, int length);
 It reads up to length bytes or to the end of file, whichever comes
first.
File Input/Output…
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…
 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…
Seeking in File
 The function fseek() can be used to set the file pointer to

some point within the file.


 It moves the file pointer, depending on the parameters.

fseek($fh, int offset, mode);

 The value specified in offset is the character location to


move the pointer to. You can set mode to:
 SEEK_SET (moves to char in position offset),
 SEEK_CUR (moves offset characters forward from current
position), or
 SEEK_END (moves offset characters back from the last
character).

 The rewind() function is equivalent to calling the fseek()


function with an offset of zero.
File Input/Output…
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”;
}
File Input/Output…
Function What It Does Output
is_file(“stuff.txt”) Tests whether the file is a regular file, rather than TRUE or FALSE
a directory or other special type of file
is_dir(“stuff.txt”) Tests whether the file is a directory TRUE or FALSE
is_executable(“do.txt”) Tests whether the file is executable TRUE or FALSE
is_writable(“stuff.txt”) Tests whether you can write to the file TRUE or FALSE
is_readable(“stuff.txt”) Tests whether you can read the file TRUE or FALSE
filesize(“stuff.txt”) Returns the file size in bytes Integer or FALSE
basename(“/t1/do.txt”) Returns the filename from the path do.txt
dirname(“/t1/do.txt”) Returns the directory name from the path /t1
copy(oldfile, newfile) Copy an existing file into a new file TRUE or FALSE
rename(oldname,newname) renames a file oldname to newname TRUE or FALSE
unlink(“badfile.txt”) deletes an unwanted file TRUE or FALSE
File Input/Output…
 Example:
if(!file_exists(“library.txt”))
copy(“book.txt”, ”library.txt”);
else
echo “File already exists!\n”;
readfile(“library.txt”);
Working with Date and Time

 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
Working with Date and
Time…
 The integer returned by time() represents the number
of seconds elapsed since midnight GMT on January 1,
1970.
 This moment is known as the Unix epoch, and the
number of seconds that have elapsed since then is
referred to as a timestamp.
 PHP offers excellent tools to convert a timestamp into
a form that humans are comfortable with.

 Even so, isn't a timestamp a needlessly convoluted


way of storing a date? In fact, the opposite is true.
 From just one number, you can extract enormous
amounts of information.
 Even better, a timestamp can make date arithmetic
Working with Date and
Time…
 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
Working with Date and
Time…
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…
 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…
 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
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…
 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
Working with Date and
Time…
 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…
<?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…
 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);
Working with Date and
Time…
 If you were to attempt to build a date with
mktime() using these values, you'd end up
with a timestamp of -1.
 As a rule of thumb, don't use mktime() with
years before 1902
 Also be cautious of using date functions with
any date before 1970, as negative numbers
are not valid dates.
 Because the epoch began January 1, 1970,
anything before that is an invalid (negative)
timestamp.
Mathematical Functions
 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() Takes a single argument and raises e to that power. The value of exp($x) is e x.
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 10 y = 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.

atan() Takes a numerical argument and returns the arctangent of the argument in
radians. Results are in the range –pi / 2 to pi / 2.

atan2() A variant of atan() that takes two arguments. Atan($y, $x) is identical to
atan($y/$x) when $x is positive, but the quadrant of atan2’s result depends on
the signs of both $y and $x. Range of the result is from –pi to pi.

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….
 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…
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…
 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

You might also like