WD Unit 4,5,6 PHP
WD Unit 4,5,6 PHP
PHP
By Pradish Dadhania
PHP
Introduction to Ser ver-Side Programming
Request to a Static Site
Server:
1. Homepage
lookup
2. Send as HTTP
HTTP Request: GET www.xkcd.com
Response
String functions
Length: strlen()
Position of substring: strpos()
More on string functions:
http://www.w3schools.com/php/php_ref_string.asp
PHP
Syntax: Conditional and Looping Statements
Conditional Statements
if (condition / boolean expression) {
statements
}
else if (another condition) {
statements
}
// there may be more than one else if block
else {
statements
}
$x = 5;
if ($x echo
== 5)‘The
{ variable x has value 5!’;
}
The while loop
while (condition) {
statements
}
$x = 2;
while ($x
echo< $x
1000) {
. “n”; // \n is newline character
} $x = $x * $x;
Value of $x $x< 1000? Result
2 prints 2
TRUE
4 TRUE prints 4
16 TRUE prints 16
256 TRUE
prints 256
FALSE
65536
exits loop
The do-while loop
The code within the loop is executed at least once,
regardless of whether the condition is true
do {
statements
} while (condition);
equivalent to:
statements
while (condition) {
statements
}
The for loop
for (init; condition; increment) {
statements
}
equivalent to:
init
while (condition) {
statements
increment
}
Prints the first 10 positive integers and their
squares:
for ($i = 1; $i <= 10; $i++) {
echo $i . “:” . ($i * $i) . “\n”;
}
PHP
Syntax: Functions and Global Variables
Defining your own functions
function function_name ($arg1, $arg2) {
function code function parameters
} return $var // optional
print_r($colors)
Array( gives:
[0] => red
[1] => blue
[2] => green
[3] => black
Tur ns out all[4]
arrays in PHP
=> yellow are associative arrays
In the
) example above, keys were simply the index into the
list
Each element in an array will have a unique k ey,
whether you specify it or not.
Specifying the key/index
Thus, we can add to a list of elements with any
arbitrary index
Using an index that already exists will overwrite the
value
$colors = array(‘red’, ‘blue’, ‘green’, ‘black’, ‘yellow’);
$colors[5] = ‘gray’; // the next element is gray
$colors[8] = ‘pink’;// not the next index, works anyways
$colors[7] = ‘orange’ // out of order works as well
Array functions
isset($array_name[$key_value]) tells whether a mapping
exists AND is non-null
unset($array_name[$key_value]) removes the key-value
mapping associated with $key_value in the array
The unset() function does not “re-index” and will leave
gaps in the indices of a list of elements since it simply
removes the key-value pairing without touching any other
array_keys($array_name) and
elements
array_values($array_name) returns lists of the keys and
values of the array
Adding elements without specifying the
key
Recall that we did not specify the key when adding to a list of
elements:
$colors = array('red', 'blue', 'green', 'black',
'yellow');
PHP automatically
$colors[] takes the largest integer key that has ever been
= 'purple';
in the array, and adds 1 to get the new key
$favorite_colors = array(“Joe” => “blue”, “Elena”
=> “green”, “Mark” => “brown”, “Adrian” =>
“black”, “Charles” => “red”);
$favorite_colors[] = 'new color 1'; // key is 0
$favorite_colors[7] = 'another new color';
$favorite_colors[] = 'color nine'; // key is 9, the old
$favorite_colors[] = 'yet another color'; // key is 8
// maximum is 8 even though it no longer exists!
unset($favorite_colors[8]);
The for-eac h loop
The for-eac h loops allow for easy iteration over all
elements of an array.
foreach ($array_name as $value) {
code here
}
foreach ($array_name as $key => $value) {
code here
}
foreach ($colors as $color) {
echo $color; // simply prints each color
}
foreach ($colors as $number => color) {
// $colors[$number]
echo = $new_color;
“$number => $color”; // prints color with index
PHP
HTTP Requests and Forms
Superglobals
A few special associative arrays that can be
accessed from anywhere in a PHP file
Always $_ALLCAPS
The $_SERVER superglobal gives information about
$_SERVER[‘REMOTE_ADDR’] client IP
$_SERVER[‘HTTP_USER_AGENT’] client OS and
browser
Passing information to the ser ver
Sometimes, we require additional values be passed
from client to ser ver
Login: username and password
Form information to be stored on ser ver
http://www.yourdomain.com/yourpage.php?firstparam
=firstvalue&secondparam=secondvalue
GET request: pass information via the URL
Access values server-side using $_GET superglobal
$_GET[‘secondparam’]
$_GET[‘firstparam’]
=>=> ‘secondvalue’
‘firstvalue’
When to use $_GET vs. $_POST
GET requests are sent via the URL, and can thus be
cached, bookmarked, shared, etc
GET requests are limited by the length of the URL
POST requests are not exposed in the URL and
should be used for sensitive data
There is no limit to the amount of information
passed via POST
Dealing with for ms
Forms are generally used to collect data, whether
the data needs
(registration) or to be stored
c hecked on thetheserserver
against ver
2(login)
components to a form:
The HTML generating the form itself
The server-side script that the form data is sent to (via
GET or POST), taking care of the processing involved
Server should respond appropriately, redirecting the user to
the appropriate destination or generating the appropriate
page
Forms: client-side
<html>
<head>
<title> A Form Example </title>
</head><body>
<form action="welcome.php" method="post">
Name: <br /> <input type="text" name="name" /><br />
Phone Number: <br /> <input type="text" name="phone" /><br />
<input type="submit" value="Submit">
</form>
form action – where to send the form data
</body>
method – how to send the data (GET or POST)
</html>
Name attributes become the keys used to access the
corresponding fields in the $_GET or $_POST arrays
Forms: ser ver-side
<html>
<head><title>This is welcome.php</title></head>
<body>
The name that was submitted was:
<?php echo $_POST['name']; ?><br />
The phone number that was submitted was:
<?php echo $_POST['phone']; ?><br />
</html>
</body>
A simple PHP file that displays what was entered into
the form
Can do many other things server-side depending on the
situation
Note the use of $_POST
Unit 5
Session and State Management
using PHP
(Cookies and Sessions)
Need of session ma na ge me nt,
Va rious techniques for s tate and
session management like: Hidden Fields,
Query S tring, Cookie and Session
Cookies and sessions
HTTP is stateless – it does not keep track of the
client between requests
But sometimes we need to keep track of this
information
Shopping cart
“Remember me” on login sites
2 solutions to this issue
Cookies – small file stored client-side
Sessions – relevant data stored on the ser ver
Cookies
Cookies are stored on the user’s browser, and are
sent to the ser ver on every relevant request
The $_COOKIE superglobal makes a cookie a key-
value pairing
Store user information as a value with a known key
Neverassume a cookie has been set. Always check with
isset($_COOKIE[$cookie_name])before trying to use
the cookie’s value
The setcookie() function
To set a cookie in PHP:
setcookie(name, value, expire, path, domain);
Name and value correspond to $_COOKIE[$name] =
$value
Expiration – cookie will no longer be read after the
expiration
Useful to use time in seconds relative to the present:
time() + time in seconds until expiration
Path and domain refer to where on the site the cookie is
valid
Usually ‘/’ for path and the top-level domain (yoursitename.com)
To delete a cookie, set a new cookie with same arguments
but expiration in the past
Setting cookies
Cookies are set via the HTTP header
Must be sent before the body – before any HTML, CSS,
JS, etc.
This code will not work:
if(isset($_COOKIE["6470"])) {
$value = $_COOKIE['6470'];
} echo "Cookie is set to $value";
else {
$value = 0;
}
// after echo statement: will not work!
setcookie("6470", $value+1, time()+60*60);?>
Example of cookie usage
First visit: form with a text field for user’s name
Subsequent visits: Welcome message with the name
Key: “name”;
Store the namevalue:
field the
in auser’s name input into the form
cookie:
Remember: when a cookie is set (the setcookie
function call is made), the cookie can only be
accessed on the next request
Contents of the HTTP request/response
CLIENT HTTP request: GET cookie.php SERVER
isset($_COOKIE[“name”])? NO
isset($_GET[“name”])? NO
NO HTTP reponse: HTML form
COOKIES respond with HTML form
HTTP request: GET name=“username” isset($_COOKIE[“name”])? NO
isset($_GET[“name”])? YES
HTTP response: set cookie
set cookie on client
HTTP request: cookie “name” = “username” welcome message based on
COOKIES isset($_COOKIE[“name”])?
user input YES
SET HTTP response: updated cookie isset($_GET[“name”])? NO
update cookie on client
welcome message based on
Case 1: cookies already set
if(isset($_COOKIE["name"])) {
$cookie_exp = time()+60*60; // one hour
$name = $_COOKIE["name"];
setcookie("name", $name, $cookie_exp);
if (isset($_COOKIE["visits"])) {
echo "Welcome $name!
$num_visits ";
= $_COOKIE["visits"]+1;
if (isset($_COOKIE["visits"])) {
setcookie("visits", $num_visits, $cookie_exp);
echo "You've visited $num_visits times";
}
} }
Cases 2&3: first and second visits
// case 2: upon submission of form
else if (isset($_GET["name"])) {
$name = $_GET["name"];
setcookie("name", $name, $cookie_exp);
setcookie("visits", 2, $cookie_exp);
// case
echo 3: first visit:
"Welcome $name! need
This to
is show
your form
second visit.";
else {
} <form action="<?php $_SERVER["PHP_SELF"] ?>" method="get">
Enter your name here: <input type="text" name="name" />
</form>
<br /><input type="submit" />
}
Sessions
Two main disadvantages of cookies
Limited in size by browser
Stored client-side can be tampered with
Sessions
Cannotstore user data
be modified on the ser ver
by users
A potential downside
Limited only by servertospace
sessions is that they expire
when the browser is closed
Sessions are identified by a session id: often a small
randompass’ OR ‘1=1
as the password?
SELECT PHONE FROM userinfo WHERE
Resulting query:
USER=‘username’ and PASSWORD=‘randompass’
‘1=1’ always true. We can get the ser ver to give the
OR ‘1=1’
phone number regardless of username/password!
Fix: must pass ALL user input through the function
mysql_real_escape_string()
Retrieving information from a query
Loop over the returned $result resource, row by row
mysql_fetch_assoc() function: turns a row of the
ASP.NET
Python
PHP’s extensive documentation:
http://www.php.net/manual/en
GOOD LUCK!