PHP Programming PDF
PHP Programming PDF
Charles Liu
Request to a Static Site
Server:
1. Homepage
lookup
2. Send as HTTP
Response
HTTP Request: GET www.xkcd.com
Charles Liu
What is PHP?
Charles Liu
Variables
Store values for future reference, use variable name
to refer to the value stored in it
$x = 42; // store the value 42 in $x
echo $x; // prints 42
echo $x+1; // prints 43, value of $x is still 42
$x = ‘hello!’ // type of $x can change
String functions
Length: strlen()
Position of substring: strpos()
Charles Liu
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 == 5) {
echo ‘The variable x has value 5!’;
}
The while loop
while (condition) {
statements
}
$x = 2;
while ($x < 1000) {
echo $x . “n”; // \n is newline character
$x = $x * $x;
}
Value of $x $x < 1000? Result
2 TRUE prints 2
4 TRUE prints 4
16 TRUE prints 16
256 TRUE prints 256
65536 FALSE 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
}
Charles Liu
Defining your own functions
function function_name ($arg1, $arg2) {
function code function parameters
return $var // optional
}
function function1() {
… // some code
function3(); // makes function call to function3()
}
function function2() { // this function is never called!
… // some code
}
function function3() {
… // some code
}
?>
Variable scope
Variables declared within a function have local scope
Can only be accessed from within the function
<?php
function function1() {
… // some code
$local_var = 5; // this variable is LOCAL to
// function1()
echo $local_var + 3; // prints 8
}
… // some code
function1();
echo $local_var; // does nothing, since $local_var is
// out of scope
?>
Global variable scope
Variables declared outside a function have global
scope
Must use global keyword to gain access within functions
<?php
function function1() {
echo $a; // does nothing, $a is out of scope
global $a; // gain access to $a within function
echo $a; // prints 4
}
… // some code
$a = 4; // $a is a global variable
function1();
?>
PHP
Syntax: Arrays
Charles Liu
Arrays as a list of elements
Use arrays to keep track of a list of elements using
the same variable name, identifying each element by
its index, starting with 0
$colors = array(‘red’, ‘blue’, ‘green’, ‘black’, ‘yellow’);
Charles Liu
All arrays are associative
Take our example of a list:
$colors = array(‘red’, ‘blue’, ‘green’, ‘black’, ‘yellow’);
print_r($colors) gives:
Array(
[0] => red
[1] => blue
[2] => green
[3] => black
[4] => yellow
)
Turns out all arrays in PHP are associative arrays
In the example above, keys were simply the index into the
list
Each element in an array will have a unique key,
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
elements
array_keys($array_name) and
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');
$colors[] = 'purple';
PHP automatically takes the largest integer key that has ever been
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[] = 'yet another color'; // key is 8
unset($favorite_colors[8]);
$favorite_colors[] = 'color nine'; // key is 9, the old
// maximum is 8 even though it no longer exists!
The for-each loop
The for-each 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
}
Charles Liu
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 and client
$_SERVER[‘SERVER_ADDR’] server IP
$_SERVER[‘REMOTE_ADDR’] client IP
<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 />
</body>
</html>
Charles Liu
Cookies and sessions
if(isset($_COOKIE["name"])) {
$cookie_exp = time()+60*60; // one hour
$name = $_COOKIE["name"];
setcookie("name", $name, $cookie_exp);
if (isset($_COOKIE["visits"])) {
$num_visits = $_COOKIE["visits"]+1;
setcookie("visits", $num_visits, $cookie_exp);
}
echo "Welcome $name! ";
if (isset($_COOKIE["visits"])) {
echo "You've visited $num_visits times";
}
}
Cases 2&3: first and second visits
COOKIES SESSIONS
Where is data stored? Locally on client Remotely on server
Expiration? Variable – determined Session is destroyed
when cookie is set when the browser is
closed
Size limit? Depends on browser Depends only on server
(practically no size
limit)
Accessing information? $_COOKIE $_SESSION
General use? Remember small things Remembering varying
about the user, such as amount of data about
login name. Remember the user in one
things after re-opening browsing “session”
browser
PHP
MySQL
Charles Liu
Databases and MySQL
Login page
Check username and password
If already logged in (use sessions!), welcome the user
by name
Link to register page
Register page
Form for registration
If registration is successful, confirm the username
Link back to login page
Connecting to database
$db= mysql_connect(location, username, password)
mysql_select_db(db_name, $db)
Making a query
$result = mysql_query(query_string, $db)
Getting results of query
while($row = mysql_fetch_assoc($result))
Sanitizing user input
$username =
mysql_real_escape_string($_POST[“username”])
PHP
Conclusion
Charles Liu
What we’ve talked about…
Python