html5 basics, tables, forms it350: web & internet ...4 php •php: php hypertext preprocessor...
Post on 30-Jun-2020
17 Views
Preview:
TRANSCRIPT
1
IT350: Web & Internet Programming
Set 12: CGI and PHP
Things we’ll learn and do
• HTML5 – basics, tables, forms
• Cascading Style Sheets
• JavaScript
• Dynamic HTML
• CGI / PHP
2
Outline
• Three-tier architecture
• CGI basics
• PHP overview
• PHP classes and functions
• PHP files
• PHP arrays
The Three-Tier Architecture
Presentation tier Client Program (Web Browser)
Middle tier Application Server
Database Management
System, File Server
Data management
tier
3
Example 1: Airline reservations
Build a system for making airline reservations
• Database/File System
• Application Server
• Client Program
Technologies
Client Program (Web Browser)
Application Server
Database / File System
HTML, Javascript, XSLT
C++, Cookies, XML,
XPath, web services,
Perl, PHP
SQL, Triggers,
Stored Procedures,
Scripts
4
PHP
• PHP: PHP Hypertext Preprocessor
• Server-side scripting language
• PHP pages require a web server with PHP support
• Competitors:
PHP Strengths
• High performance
• Interface to many different database systems
• Built-in libraries
• Ease of learning and use
• Object-oriented support
• Portability
• Open source
• Free
• Availability of support
5
PHP References
• Online tutorials– http://www.w3schools.com/php/default.asp
– https://www.codecademy.com/learn/php
• Online references– http://www.php.net
• IT350 Textbook: Internet & WWW – How to Program by Deitel, Deitel, and Goldberg.
CGI – What does it all look like?
6
CGI Script Basics
• Common Gateway Interface (CGI)– “Common”: Not specific to any operating system or language
• Output file generated at runtime:1. When a program executed as a CGI script, “standard output”
is redirected to web server
2. Web server then redirects output to client's browser
How can CGI get data from user?
Technique #1: Forms
• User enters data via a form, submits
• Browser requests the CGI file by name specified on form __________
• Web server runs the CGI program with form’s data passed to it
• Script receives data in one of two ways:1. method = “get”
2. method = “post”
Use language-specific method to get these inside CGI program
Technique #2: URL with parameters<a href=“http://www.usna.edu/CS/calendar/view.pl?events=seminars”>
Seminars </a>
7
PHP and CGI
• We will use PHP in this class.– We will not focus on teaching you the language.
– You are expected to pick this up on your own.
• Remember: the goal of a CGI program is to output HTML – The web server will run your program.
– The web server will pipe the output to your browser.
– Your browser only understands HTML
PHP Overview
• PHP tags <?php ?> – Mixed with HTML tags– File extension .php
• Statements– Separated by semicolon – if..else.., while, do, for, switch– echo
• Variables– $varname– Type determined by content; type not declared, variables not declared– Variable names are case sensitive
• Strings– Single quotes – literal string– Double quotes – interpolated string– Use . to concatenate
• Accessing form variables– $_POST[‘age’], $_GET[‘age’], $_REQUEST[‘age’]
8
Exercise #1
• Write PHP code that will, given the URL provided below, generate HTML that looks like the screenshot
http://mope.academy.usna.edu/~adina/it350/ice/set12_ex1.php?maxNumber=5
PHP Objects and Functions
• PHP objects– Java-like inheritance – public, private, or protected attributes and methods– __construct(), __destruct(),– __set(), __get()
• PHP functions– function myFunction($param1, $param2){…return .. }
9
How everything works: Step 1: Input Form – form.html
<!DOCTYPE html>
<html><head><title>IT350 PHP test page</title><meta charset = “utf-8”></head>
<body>
<form action="processPersonInfo.php" method="post">
<p><label>Enter your name: <input type="text" name="name"/></label></p>
<p><label>Enter your age: <input type="text" name="age" /></label></p>
<p><input type="submit" name = "submit" value = "Submit"/></p>
</form></body> </html>
<?php
class Page{
public $content;
private $title;
public function __construct($title){
$this->title = $title;
}
public function __set($name, $value){
$this->$name = $value;
}
public function display(){
?>
<!DOCTYPE html>
<head><title> <?php echo $this->title; ?> </title></head>
<body>
<?php
echo $this->content;
echo "</body></html>";
}
} //end class definition
?>
page.inc.php
10
Step 1 version 2 – getPersonInfo.php
<?php
require('page.inc.php');
$page = new Page("Input person");
$page->content = '<form action = "processPersonInfo.php" method = "post">'.
'<p><label>Enter your name: <input type="text” name="name“/></label></p>’.
‘<p><label>Enter your age: <input type="text" name="age"/></label></p>’.
'<input type = "submit" value = "submit">';
$page->display();
?>
Exercise #2
• Create Person class with method getPersonAttributesAsHTMLInput() that returns
'<p><label>Enter your name: <input type="text” name="name“/></label></p>’.
‘<p><label>Enter your age: <input type="text" name="age"/></label></p>’
• Modify getPersonInfo.php to use the getPersonAttributesAsHTMLInput
method in Person class
11
<?php
/* define a class Person with name and age */
class Person{
private $name;
private $age;
public function __construct(){}
public function __set($varName, $varValue)
{
$varValue = trim($varValue);
$varValue = strip_tags($varValue);
$this->$varName = $varValue;
}
public function __get($varName)
{
return $this->$varName;
}
person.inc.php – part 1
public function processPerson(){
$success = $this->insertToFile();
if ($success){
$confirmation = '<h1>Thank you for registering with our site</h1>'.
'<p>The information recorded is as follows: <br/>'.
"Name: $this->name <br /> Age: $this->age </p>";
}
else{
$confirmation = '<h1>Error: we had problems with your registration (probably some file error - permissions??).
Please try again.</h1>';
}
return $confirmation;
}
person.inc.php – part 2
12
PHP Files
• Files– $handle = fopen($fileName, $mode)– fwrite($handle, $someText)– fclose($handle)– fgets($handle)– feof($handle)
private function insertToFile($fileName="persons.txt")
{
$fp = @fopen($fileName, 'a');
if (!$fp){
return false;
}
else{
$text = "$this->name\t$this->age\n";
fwrite($fp, $text);
fclose($fp);
return true;
}
}
person.inc.php – part 3
13
public static function getAllPersonsInfo($fileName = "persons.txt"){
$fp = @fopen($fileName, 'r');
if (!$fp){
$content = "<p>ERROR! Could not open file $fileName for reading.</p>";
}
else{
$content= '<p>Here is the list: <br>';
$line = fgets($fp);
while( !feof($fp) ){
$content .= $line . '<br>';
$line = fgets($fp);
}
$content .= '</p>';
fclose($fp);
}
return $content;
}
}?>
person.inc.php – part 4
<?php
require('page.inc.php'); require('person.inc.php');
$name = $_POST['name']; $age = $_POST['age'];
$page = new Page("Registration confirmation");
if (empty($name) || empty($age)){
$page->content = '<p> Name or age not entered!! Try again</p>';
$page->display();
exit;
}
$dummy = new Person();
$dummy->name = $name;
$dummy->age = $age;
$page->content = $dummy->processPerson();
$page->display(); ?>
Step 2: processPersonInfo.php
14
<?php
require('page.inc.php');
require('person.inc.php');
if (isset($_GET['filename'])){
$fileName = $_GET['filename'];
}
else{
$fileName = "persons.txt";
}
$page = new Page("Persons list");
$page->content = Person::getAllPersonsInfo($fileName);
$page->display();
?>
Step 3: readPearsonsInfo.php
CGI – Review
15
Arrays<?php require_once('page.inc.php'); require_once('arrayFunctions.inc.php');
$myPage = new Page('Array examples');
$myPage->content = '<p>Working with Arrays</p>';
$array = array('thing1', 'thing2');
$array[2] = 'thing3';
$myPage->content .= '<p>'.displayArray($array) . '</p>';
$prices = array('Tires' => 100, 'Oil' => 10);
$prices[‘Spark plugs'] = 200;
$myPage->content .= '<p>The values in $prices array are <br />’
. displayAssociativeArray($prices) . '</p>';
sort($array); //sort array
$myPage->content .= '<p> Sorted array '.displayArray($array) . '</p>';
ksort($prices); //sort associative array by key
$myPage->content .= '<p>The values in $prices array sorted by key are <br />'
. displayAssociativeArray($prices) . '</p>';
asort($prices); //sort associative array by value
$myPage->content .= '<p>The values in $prices array sorted by value are <br />'
. displayAssociativeArray($prices) . '</p>';
$myPage->display(); ?>
array_functions.inc.php
<?php
//return a string to display an array
function displayArray($array){
$result = ‘<p>';
for($i = 0; $i < count($array); $i++){
$result .= "Element at index $i is $array[$i] <br />";
}
$result .= ‘</p>';
return $result;
}
//return a string to display an associative array
function displayAssociativeArray($array){
$result = ‘<p>';
foreach($array as $key => $value){
$result .= "Element with key $key has value $value <br />";
}
$result .= ‘</p>';
return $result;
}
?>
16
Exercise #3
• Create an array containing the following values: (1900, 2000, 2015, 2016 ).
• Use the array in a “foreach” loop to test if the value is a divisible by 4.
• If it is divisible by 4 print “XXXX is divisible by 4” • Else print “XXXX is not divisible by 4”
17
Variables Scope
• Variables used in functions are visible from first use line to end of function – local variables
• Variables used outside functions are visible from first use line to end of file, but not inside functions – global variables
• Superglobal variables ($_POST, $_SERVER, …) are visible everywhere
• Keyword global makes local variables global – not recommended
Variables Scope Example
<?php
function fn(){
$x = 'content';
}
fn();
echo 'Value of $x is '. $x;
?>
18
Variables Scope Example 2
<?php
$x = 'content 1 <br/>';
echo 'Content of $x after initialization is '. $x . '<br />';
function fn(){
echo 'Content of $x at start of function is '. $x. '<br />';
$x = 'content 2 <br/>';
echo 'Content of $x at end of function is '. $x. '<br />';
}
fn();
echo 'Value of $x after calling fn() is '. $x. ‘<br />';
?>
PHP Summary
• PHP tags <?php ?> – Mixed with HTML tags– File extension .php
• Statements– Separated by semicolon – if..else.., while, do, for, switch, echo
• Variables– $varname– Type determined by content; variables not declared; case sensitive
• Strings– Single quotes – literal string– Double quotes – interpolated string (variables are replaced with their value)
• Arrays– Numerically indexed arrays– Associative arrays– count(), foreach($array as $key => $value)…
• Accessing form variables– $_POST[‘age’], $_GET[‘age’], $_REQUEST[‘age’]
top related