Introduction to PHP – Part.

Chapter 9 from text book


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


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 ◦ with HTML forms

The data is sent in HTTP requests to the server The data is placed into the request as parameters

"Superglobal" Arrays
Array $_GET, $_POST Description Parameters passed to GET and POST requests


"cookies" used to identify the user (seen later in this chapter)

• PHP superglobal arrays contain information about the current request, server, etc.: • These are special kinds of arrays called associative arrays.


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!

Checkpoint 1

What are the changes in the previous example if you use $_POST instead of $_GET?



  
     

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

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


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

Cookies Example
Example 1: Writing Cookies to the client’s machine.  Example 2: The server reads the written cookies from the client’s machine.


Example 1: Writing Cookies (cookies.html)
<html xmlns = "">

<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>

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" ""> <html xmlns = ""> <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>


Example 2: Reading Cookies (readcookies.php)
<html xmlns = ""> <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>

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

<?php // this starts the session session_start(); // this sets variables in the session $_SESSION['test']='testing'; print "Done"; ?>



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

Example : Connecting to a DB (data.html)
<html xmlns = ""> <head> <title>Sample Database Query</title> </head> <body style = "background-color: #F0E68C"> <h2 style = "font-family: arial color: blue“> Querying a MySQL database. <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>



Example : Connecting to a DB (database.php)
<html xmlns = ""> <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() ); } ?>

Example : Connecting to a DB (database.php)
<h3 style = "color: blue"> <?php Search Results</h3> <table border = "1" cellpadding = "3" cellspacing = "2” >

// 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>

Remaining (self study)
Sorting Arrays  my_sql_num_rows()  my_sql_num_fields()  my_sql_num_rows()  my_sql_fetch_array()


Extra Topic


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 MultiTemplate/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)


Sign up to vote on this title
UsefulNot useful