You are on page 1of 32

Introduction to PHP – Part.

2
Chapter 9 from text book

1
Outline
 Form Handling
 Files
 Cookies
 Session Tracking
 Database Accesses using PHP and MySQL
(13.5)
 Content management system

2
Submitting data to a web server
 Though browsers mostly retrieve data,
sometimes you want to submit data to a
server
◦ Hotmail: Send a message
◦ Flickr: Upload a photo
◦ Google Calendar: Create an appointment
 The data is sent in HTTP requests to the
server
◦ with HTML forms
 The data is placed into the request as
parameters

3
"Superglobal" Arrays
Array Description

$_GET, $_POST Parameters passed to GET and POST requests

$_SESSION, "cookies" used to identify the user (seen later in this


$_COOKIE chapter)

• PHP superglobal arrays contain information about


the current request, server, etc.:
• These are special kinds of arrays called
associative arrays.

4
Using $_GET
<form action="welcome.php" method="get">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
• If the user enters his information then clicks the "Submit"
button, the URL sent to the server could look something like
this:
-http://~~~/welcome.php?fname=Deema&age=3

• Processing data in "welcome.php" file:


Welcome <?php print $_GET["fname"]; ?>.<br />
You are <?php echo $_GET["age"]; ?>years old!
5
Checkpoint 1

 What are the changes in the previous


example if you use $_POST instead of
$_GET?

6
Files
 PHP can:
◦ Deal with any files on the server
◦ Deal with any files on the Internet, using either http or ftp
 PHP associates a variable with a file, called the file variable (for
program reference)
 A file has a file pointer (where to read or write)
◦ $fptr = fopen(filename, use_indicator)
 Use indicators:
 r read only, from the beginning
 r+ read and write, from the beginning
 w write only, from the beginning (also creates the file, if necessary)
 w+ read and write, from the beginning (also creates the file, if necessary)
 a write only, at the end, if it exists (creates the file, if necessary)
 a+ read and write, read at the beginning, write at the end
Reading files
1) Read all or part of the file into a string variable
$str = fread(file_var, #bytes)
 To read the whole file, use filesize(file_name) as the second
parameter

2) Read all of the lines of the file into an array


@file_lines = file(file_name)
 Need not open or close the file

3) Read one line from the file


$line = fgets(file_var, #bytes)
 Reads characters until eoln, eof, or #bytes- characters have been
read
4) Read one character at a time
$ch = fgetc(file_var)
Writing to files
 $bytes_written = fwrite(file_var, string)
◦ fwrite returns the number of bytes it wrote

 Files can be locked (to avoid interference


from concurrent accesses) with flock
Cookies
 HTTP is a stateless protocol, that is, the server
treats each request as completely separate from any
other
 The mechanism of cookies can be used to help
maintain state by storing some information on the
browser system
 A cookie is a key/value pair that is keyed to the
domain of the server
◦ This key/value pair is sent along with any request made
by the browser of the same server
 A cookie has a lifetime which specifies a time at
which the cookie is deleted from the browser
10
Cookies
PHP Support for Cookies
 PHP provides the setcookie function to
set a cookie in a response
◦ The first parameter is the cookie’s name
◦ The second, optional, parameter gives the cookie’s
value
◦ The third, optional, parameter gives the expiration
 The cookie must be set before setting content
type and before providing any other output
 The $_COOKIES array provides access to
cookies in the HTTP request
12
Cookies Example
 Example 1: Writing Cookies to the client’s
machine.
 Example 2: The server reads the written
cookies from the client’s machine.

13
Example 1: Writing Cookies
(cookies.html)
<html xmlns = "http://www.w3.org/1999/xhtml">
<head> <title>Writing a cookie to the client computer</title> </head>
<body style = "font-family: arial, sans-serif; background-color: #99CCFF">
<h2>Click Write Cookie to save your cookie data.</h2>
<form method = "post" action = "cookies.php“>
<strong>Name:</strong><br />
<input type = "text" name = "NAME" /><br />
<strong>Height:</strong><br />
<input type = "text" name = "HEIGHT" /><br />
<strong>Favorite Color:</strong><br />
<input type = "text" name = "COLOR" /><br />
<input type = "submit" value = "Write Cookie"
style = "background-color: #F0E86C; color: navy; font-weight: bold"
/></p>
</form> </body></html> 14
Example 1: Writing Cookies
(cookies.php)
<?php
extract( $_POST );
// write each form field’s value to a cookie and set the cookie’s expiration date
setcookie( "Name", $NAME, time() + 60 * 60 * 24 * 5 );
setcookie( "Height", $HEIGHT, time() + 60 * 60 * 24 * 5 );
setcookie( "Color", $COLOR, time() + 60 * 60 * 24 * 5 );
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head> <title>Cookie Saved</title> </head>
<body style = "font-family: arial, sans-serif">
<p>The cookie has been set with the following data:</p>
<br /><span style = "color: blue">Name:</span>
<?php print( $NAME ) ?><br />
<span style = "color: blue">Height:</span>
<?php print( $HEIGHT ) ?><br />
<span style = "color: blue">Favorite Color:</span>
<span style = "color: <?php print( "$COLOR\">$COLOR" ) ?> </span><br />
<p>Click <a href = "readCookies.php">here</a> to read the saved cookie.</p>
</body> </html> 15
Example 2: Reading Cookies
(readcookies.php)
<html xmlns = "http://www.w3.org/1999/xhtml">
<head><title>Read Cookies</title></head>
<body style = "font-family: arial, sans-serif">
<p>
<strong> The following data is saved in a cookie on your computer. </strong>
</p>
<table border = "5" cellspacing = "0" cellpadding = "10">
<?php
// iterate through array $_COOKIE and print name and value of each cookie
foreach ( $_COOKIE as $key => $value )
print( "<tr>
<td bgcolor=\"#F0E68C\">$key</td>
<td bgcolor=\"#FFA500\">$value</td>
</tr>" );
?>
</table> </body> </html>
16
Sessions
 Some applications need to keep track of a session
 Sessions are represented internally in PHP with a session id
◦ A session consists of key/value pairs
 A session can be initialized or retrieved by using the
session_start function
◦ This function retrieves $_SESSION, an array containing the
key/value pairs for each session in the current request
 Example:

<?php
// this starts the session
session_start();
// this sets variables in the session
$_SESSION['test']='testing';
print "Done";
?>
17
Sessions
Example
 Set a session variable using $_SESSION
array.
Checkpoint 2
 What is the difference between Sessions
and Cookies?
 Can we use Sessions and Cookies in the
same PHP program?
Database Accesses using PHP and
MySQL
 To access data stored in a MySQL database:
1. Create a Connection to a MySQL DBMS
$con = mysql_connect(servername,username,password);

2. Select a specific DB:


mysql_select_db(DB_name, $con);

3. Send your query to MySQL to execute it:


$result = mysql_query(your_SQL_stmt);

4. Iterate through the returned array:


$row = mysql_fetch_row($result)
5. Close the connection to MySQL
Mysql_close($con);
21
Example : Connecting to a DB
(data.html)
<html xmlns = "http://www.w3.org/1999/xhtml">
<head> <title>Sample Database Query</title> </head>
<body style = "background-color: #F0E68C">
<h2 style = "font-family: arial color: blue“> Querying a MySQL database. </h2>
<form method = "post" action = "database.php">
<p>Select a field to display:
<!-- add a select box containing options for SELECT query -->
<select name = "select">
<option selected = "selected">*</option>
<option>ID</option>
<option>Title</option>
<option>Category</option>
<option>ISBN</option>
</select> </p>
<input type = "submit" value = "Send Query"
style = "background-color: blue; color: yellow; font-weight: bold" />
</form> </body></html>
22
Example : Connecting to a DB
(database.php)
<html xmlns = "http://www.w3.org/1999/xhtml">
<head> <title>Search Results</title> </head>
<body style = "font-family: arial, sans-serif">
<?php
extract( $_POST );
// build SELECT query
$query = "SELECT " . $select . " FROM Books";
// Connect to MySQL
if ( !( $database = mysql_connect( "localhost",
"root", "" ) ) )
die( "Could not connect to database" );
// open Products database
if ( !mysql_select_db( "Products", $database ) )
die( "Could not open Products database" );
// query Products database
if ( !( $result = mysql_query( $query, $database ) ) ) {
print( "Could not execute query! <br />" );
die( mysql_error() );
}
?>
23
Example : Connecting to a DB
(database.php)
<h3 style = "color: blue"> Search Results</h3>
<table border = "1" cellpadding = "3" cellspacing = "2” >
<?php
// fetch each record in result set
for ( $counter = 0;
$row = mysql_fetch_row( $result ); s $counter++ ){
// build table to display results
print( "<tr>" );
foreach ( $row as $key => $value )
print( "<td>$value</td>" );
print( "</tr>" );
}
mysql_close( $database );
?>
</table> <br />Your search yielded <strong>
<?php print( "$counter" ) ?> results.<br /><br /></strong>
</body> </html>
24
Remaining (self study)
 Sorting Arrays
 my_sql_num_rows()
 my_sql_num_fields()
 my_sql_num_rows()
 my_sql_fetch_array()

25
Extra Topic

CONTENT
MANAGEMENT
SYSTEMS (CMS)
What is CMS?
 A Web Content
Management System
(WCMS) is a software system
which provides website
authoring, collaboration and
administration tools designed to
allow users with little
knowledge of web programming
languages or markup languages
to create and manage the site's
content with relative
ease.(Wikipedia, 2010)
What functionalities do CMSs
provide?
 WYSIWYG editor for
content
 Easily editable content
 Multilingual front end
 Multi-
Template/Themes.
 Seamless Database
connectivity
 Scalable feature sets
 …. And much more!!
How do I choose a CMS?
 Understanding Your Web Content
 Determining and documenting "business"
requirements
 OS that runs on
 Type of Database
 Extendibility
 User Friendly
 Provides templating that is completely
customizable and Supports XHTML and
CSS templates
Example (Joomla)
Example (Drupal)
THE END

You might also like