Server Side Programming with
PHP and MySQL
• What is PHP?
– PHP stands for PHP Http Processor. It is developed from a
project called Personal Home Page tools.
• Introduction of PHP Programming Language
–
–
–
–
–
–
Simple PHP program
PHP variables
PHP functions
PHP Operators
PHP sessions
PHP examples
• http://136.148.4.7/~yourusername
• In the windows console window, use ftp 136.148.4.7 to
upload your programs to the folder public_html
A page including PHP codes
<html>
•
<head> <title>Hello in PHP</title>
</head>
•
<body>
<h1>Hello in PHP</h1>
<?php
•
print "Hello, world!";
phpInfo();
//This comment only last for a single
line
/*
This comment spans more
Than one line
*/
?>
•
</body>
</html>
The PHP instructions are placed
inside special HTML tags.
The inclusion of PHP within HTML
files is called escaping in the PHP
documentation.
There is four different methods are
provided for escaping form HTML:
– <? echo(“<h1>Hello</h>”); ?>
– <?php echo(“<h1>Hello</h>”); ?>
– <script language=“php”>
echo(“<h1>Hello</h>”);
</script>
– <% echo(“<h1>Hello</h>”); %>
The second method is the most
legible
PHP variables
•
•
•
•
•
$a_variable;
$name = “Tony Blair”;
$age = 10;
$height = 1.666;
PHP variables can reference other variables so that both
names point to the same piece of memory. Changing the
value of tone variable changes the value of both. The
name of the variable which is being referenced is
preceded with an ampersand, &.
– $alias = &$name;
– echo “$name is also $allias”;
DATA types
• Numbers
–
–
–
–
–
$positiveInt = 14;
$negativeInt = -35;
$octalInt = 023;
$floatNum = 23.11;
$biggerNum = 4.5e9;
• Boolean
– 0, 0.0, an empty string, a string contains just “0”, an array of
length zero, NULL all the FALSE, everything else is TRUE
• String
–
–
–
–
$str1 = “ Have a Nice”;
$str2 = “Day \n”;
$str3 = $str1 . “ ”;
$str3 .= $str2 ;
Arrays
• The basic array: arrays operations are exactly
the same as those found in JavaScript and Perl.
• Associate Arrays: It is like Perl’s Hash variable.
The key must be a unique string.
• Multidimensional Arrays
–
–
–
–
–
–
$array[0][0]=“str1”;
$array[0][]=“str2”; //$array[0][1]=“str2”;
$array[0][]=“str3”; //$array[0][2]=“str3”;
$array[0][0]=“str4”;
$array[0][]=“str5”;
$array[0][]=“str6”;
Accessing HTTP Data
• PHP automatically creates a number of global
arrays.
– For get method the array of returned data is $_GET
– For post method the array of returned data is $_POST
• Program Control
– Program control is provided through a set of branching
and looping constructs.
– PHP provides the same set as many other languages
– Very special one: foreach ($array as $value) which
put next element of the array into $value on each loop.
The foreach has a rather strange syntax when working
with an associative array:
foreach( $array as $key => $value)
Processing Form using PHP
<html>
<head> <title>PHP test</title> </head>
<body>
<h1>Your Form Data Processed by PHP </h1>
<table border=10 frame=box rules=all width=80% align=center>
<?php
foreach ($_GET as $key => $value){
echo '<tr>';
echo '<td>'. $key.'<td>'.$value ;
}
?>
</table>
</body>
</html>
Build-in Functions
• PHP includes thousands of useful pieces of
code in functions and libraries
– Output: echo, print, printf, sprintf
– String function: strlen(string), trim(string[,character
set]), substr(string, start[,length]), ucfrist(string),
ucwords(string), str_replace(serch, replacement,
source), split(pattern, string), explode(token, sring),
implode(join character, array)
– HTML Character Functions: strip_tags(string, allowed),
urlencode(string), urldecode(string)
– Math Fuctions: abs(number) etc..
– Dates and Times: date(format[,timestamp]),
getdate([timestamp])
Regular Expression in PHP
• A regular expression, which may also be
called a regex or regexp, is a string which
denotes a search pattern. The search
pattern is applied to text strings inside your
script.
– preg_match(pattern, string[,matches])
– preg_match_all(pattern, string)
– preg_replace(pattern, replacement, string)
– preg_split(pattern, string)
Example preg_split();
<html>
<head><title> Regexes </title></head>
<body>
<h1>Using Regexes </h1>
<?php
$test = “name::ID::email::tel”;
$parts = preg_split(“/::/”, $test);
echo ”ul”;
while(list($key, $val) = each($parts)) {
echo “<li>$val</li>”;
}
echo “</ul>”;
?>
</body>
</html>
Using Files
• $data = fopen(/home/user/data/test.data);
• $data =
fopen(“ftp://user:[email protected]
);
• copy($source, $dest);
• fclose($fp), feof($fp), fget($fp,length),
fputs($fp, string[, length]), flock($fp,
operation), etc..
Example: open and write to a file
<html>
<head><title> Regexes </title></head>
<body>
<h1>Regexes and File Operation</h1>
<?php
//open and write to a file
$fp = fopen("filetext.dat", "a+");
foreach ($_GET as $key => $value){
fputs($fp, "$key::$value\n");
}
fclose($fp);
//open and read from a file.
$fp = fopen("filetext.dat", "r");
echo "<ul>";
while(!feof($fp)){
$row = fgets($fp, 1024);
//echo $row;
$fields = preg_split("/::/", $row);
trim($fields);
echo "<li>$fields[0] : $fields[1]</li>";
}
fclose($fp);
echo "</ul>";
?>
</body>
</html>
Tracking Users
• Cookies
• Sessions
– A session is a way of preserving information
between page and across page accesses.
– The PHP session gives each visitor a unique
ID. This is either added to the URL of each
that they request within your site or is stored
in a cookie on their browser.
Implementing Simple Sessions
• The Basic steps of using sessions are
– Starting a session
session_start();
You can also check session variable by using
issest(), Unseting by unset() function.
– Registering session variables
– Using session variables
– Deregistering variables and destroying the
session
session_destroy();
Examples: Validating Form
PHP part
• Webpage structure:
– Index.php : The entry point for this webpage
– Index_top.php: Define the function used for form creating
– Validate.css: CSS file to define the classes used for the webpage formation
– Validate.js: JavaScript file to process the XHR request etc.
<?php
require_once ('index_top.php');
?>
<html>
<head>
<title>Practical AJAX: Form Validation</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="validate.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="validate.js"></script>
</head>
<body>
Form declaration part
</body>
</html>
Validate.css
body
{
font-family: Arial, Helvetica, sans-serif;
font-size: 0.8em;
color: #000000;
}
.
.txtFormLegend
{
color: #777777;
font-weight: bold;
font-size: large;
}
label
{
float: left;
width: 150px;
font-weight: bold;
}
.txtSmall
{
color: #999999;
font-size: smaller;
}
input, select
{
margin-bottom: 3px;
}
.hidden
{
display: none;
}
.button
{
font-size: 2em;
}
left
{
margin-left: 150px;
}
.error
{
display: block;
margin-left: 150px;
color: #ff0000;
}
Index.top.php
<?php
// enable PHP session
session_start();
// initialize gender options array
$genderOptions = array("0" => "[Select]",
"1" => "Male",
"2" => "Female");
// Build HTML <option> tags
function buildOptions($options, $selectedOption) // initialize month options array
{
$monthOptions = array("0" => "[Select]",
foreach ($options as $value => $text)
"1" => "January",
{
"2" => "February",
if ($value == $selectedOption)
"3" => "March",
{
"4" => "April",
echo '<option value="' . $value .
"5" => "May",
'" selected="selected">' . $text . '</option>';
"6" => "June",
}
"7" => "July",
else
"8" => "August",
{
"9" => "September",
echo '<option value="' . $value . '">' . $text .
"10" => "October",
'</option>';
"11" => "November",
}
"12" => "December");
}
?>
}
Form part source code
<fieldset>
<legend class="txtFormLegend">New User Registration Form</legend>
<br />
<form name="frmRegistration" method="post"
action="validate.php?validationType=php">
<!-- Name -->
<label for="txtName">Your name:</label>
<input id="txtName" name="txtName" type="text"/>
<br />
<!-- Gender -->
<label for="selGender">Gender:</label>
<select name="selGender" id="selGender" >
<?php buildOptions($genderOptions, $_SESSION['values']['selGender']); ?>
</select>
Form part cont’d
<!-- Birthday -->
<label for="selBthMonth">Birthday:</label>
<!-- Month -->
<select name="selBthMonth" id="selBthMonth"> <?php buildOptions
($monthOptions, $_SESSION['values']['selBthMonth']); ?>
</select>
&nbsp;-&nbsp;
<!-- Day -->
<input type="text" name="txtBthDay" id="txtBthDay" maxlength="2"
size="2" />
&nbsp;-&nbsp;
<!-- Year -->
<input type="text" name="txtBthYear" id="txtBthYear" maxlength="4"
size="2" />
<br />
Descargar

Server Side Programming with PHP and MySQL