Lecture One
Lecture One
<?php
…
?>
PHP Basics…
# Shell-style comments
/* C-style comments
These can span multiple lines */
PHP Control Structures…..
Operator Meaning
== Is Equal to
!= Not Equal to
< Is less than
<= Is less than or equal to
> Is Greater than
>= Is Greater than or equal to
&& and And
|| or Or
15
Variables in PHP
PHP variables must begin with a “$” sign
Case-sensitive ($Foo != $foo != $fOo)
Global and locally-scoped variables
Global variables can be used anywhere
Local variables restricted to a function or class
Certain variable names reserved by PHP
Form variables ($_POST, $_GET)
Server variables ($_SERVER)
Etc.
Variable usage
<?php
$foo = 25; // Numerical variable
$bar = “Hello”; // String variable
Examples:
http://www.cs.kent.edu/~nruan/form.php
Echo example
<?php
$foo = 25; // Numerical variable
$bar = “Hello”; // String variable
Notice how echo ‘5x5=$foo’ outputs $foo rather than replacing it with 25
Strings in single quotes (‘ ’) are not interpreted or evaluated by PHP
This is true for both variables and character escape-sequences (such as “\
n” or “\\”)
Arithmetic Operations
<?php
$a=15;
$b=30;
$total=$a+$b;
Print $total;
Print “<p><h1>$total</h1>”;
// total is 45
?>
$a - $b // subtraction
$a * $b // multiplication
$a / $b // division
$a += 5 // $a = $a+5 Also works for *= and /=
Concatenation
Hello PHP
Escaping the Character
“Computer Science”
PHP Control Structures
Control Structures: Are the structures within a language that
allow us to control the flow of execution through a program or
script.
Grouped into conditional (branching) structures (e.g. if/else) and
if ($foo == 0) {
echo ‘The variable foo is equal to 0’;
}
else if (($foo > 0) && ($foo <= 5)) {
echo ‘The variable foo is between 1 and 5’;
}
else {
echo ‘The variable foo is equal to ‘.$foo;
}
If ... Else...
If (condition)
{ <?php
If($user==“John”)
Statements;{ Print “Hello John.”;
} }
Else
Else {
Print “You are not John.”;
{ }
?>
Statement;
}
No THEN in PHP
While Loops
<?php
{While (condition) $count=0;
While($count<3)
{
Print “hello PHP. ”;
Statements; $count += 1;
// $count = $count + 1;
} // or
// $count++;
?>
$datedisplay=date(“l, F m, Y”);
Wednesday, April 1, 2009 Print $datedisplay;
# If the date is April 1st, 2009
# Wednesday, April 1, 2009
Functions
Functions MUST be defined before then can be
called
Function headers are of the format
function functionName($arg_1, $arg_2, …, $arg_n)
Note that no return type is specified
Unlike variables, function names are not case
sensitive (foo(…) == Foo(…) == FoO(…))
Functions example
<?php
// This is a function
function foo($arg_1, $arg_2)
{
$arg_2 = $arg_1 * $arg_2;
return $arg_2;
}
34
Arrays….
In the example below, three literal arrays are declared as follows:
1. A numerically indexed array with indices running from 0 to 4.
2. An associative array with string indices.
3. A numerically indexed array, with indices running from 5 to 7.
<?php
$array1 = array(2, 3, 5, 7, 11);
$array2 = array("one" => 1,
"two" => 2,
"three" => 3);
$array3 = array(5 => "five", "six", "seven");
Print ($array1[3], $array2["one"], $array3[6]);
?>
35
Arrays….
From the above example, the indices in the array1 are
implicit, while the indices in array2 are explicit.
When specifically setting the index to a number N with
the =>operator, the next value has the index N+1 by default.
Explicit indices do not have to be listed in sequential order.
You can also mix numerical and string indexes, but it is not
recommended.
Assigning a collection of values to an array variable is
simple using the array() construct:
$colors = array("blue","indigo","yellow");
Or, if you know that you want to create an array $colors but don't yet know what
values to fill it with, create an empty array:
$colors = array();
36
Arrays….
Adding new values to the array is a breeze:
$colors[] = "hunter green";
Now the array $colors contains four values.
Often times, you need to access a single item in an array,
such as for output or a calculation.
To do this, we can output the second color in the array via the
key 1: print $colors[1];
...will output indigo.
Next, it makes sense to use keys which are labels more meaningful
than a mere index (if you describe for example the car):
$colors = array("exterior"=>"blue",
"trim"=>"indigo",
"fabric"=>"yellow",
"dashboard"=>"hunter green");
37
Arrays….
It's now easy to output the fabric color of this car, because fabric is a
key in the list:
print $colors[fabric];
38
Arrays….
In the browser, the above code would output:
exterior: blue
trim: indigo
fabric: yellow
dashboard: hunter green
Simply, use PHP's ksort() function to sort $colors by key,
and then step through the array as before:
ksort ($colors);
while (list($key,$value) = each($colors)) {
print "$key: $value<BR>"; }
39
Arrays….
Include (“footer.php”);
The file footer.php might look like:
setdate.php:
<?php $today=getdate(time());?>
footer.php:
<!-- begin footer --><SMALL>Today is <?php print $today[weekday];?></SMALL>
42
The use of include()…..
Now, we can use PHP's include() function to pull the above
files into our example page:
<?php
include ("setdate.php");
?>
<H2>Today's Headline:</H2>
<P ALIGN="center">
<?php
print "World Peace Declared";
?>
</P><HR>
<?php include ("footer.php");
?>
The most common use for the include() function is,
as seen above, to reuse certain components across
several pages. Files called by include() can have
other extensions like html, php3 and so on.
43
WHY PHP – Sessions ?
Whenever you want to create a website that allows you to store and display
information about a user, determine which user groups a person belongs to,
utilize permissions on your website or you just want to do something cool on
your site, PHP's Sessions are vital to each of these features.
Cookies are about 30% unreliable right now and it's getting worse every day.
More and more web browsers are starting to come with security and privacy
settings and people browsing the net these days are starting to frown upon
Cookies because they store information on their local computer that they do
not want stored there.
PHP has a great set of functions that can achieve the same results of
Cookies and more without storing information on the user's computer. PHP
Sessions store the information on the web server in a location that you chose
in special files. These files are connected to the user's web browser via the
server and a special ID called a "Session ID". This is nearly 99% flawless in
operation and it is virtually invisible to the user.
PHP - Sessions
•Sessions store their identifier in a cookie in the client’s browser
•Every page that uses session data must be proceeded by the
session_start() function
•Session variables are then set and retrieved by accessing the global
$_SESSION[]
•Save it as session.php
<?php
session_start();
if (!$_SESSION["count"])
$_SESSION["count"] = 0;
if ($_GET["count"] == "yes")
$_SESSION["count"] = $_SESSION["count"] + 1;
echo "<h1>".$_SESSION["count"]."</h1>";
?>
<a href="session.php?count=yes">Click here to count</a>
http://www.cs.kent.edu/~nruan/session.php
Avoid Error PHP - Sessions
PHP Example: <?php
echo "Look at this nasty error below:<br />";
session_start();
?>
Error!
http://www.cs.kent.edu/~nruan/session_destroy.php
PHP Overview
Easy learning
Syntax Perl- and C-like syntax. Relatively
easy to learn.
Large function library
Embedded directly into HTML
Interpreted, no need to compile
Open Source server-side scripting language
designed specifically for the web.
PHP Overview (cont.)
Conceived in 1994, now used on +10 million web
sites.
Outputs not only HTML but can output XML,
images (JPG & PNG), PDF files and even Flash
movies all generated on the fly. Can write these
files to the file system.
Supports a wide-range of databases (20+ODBC).
PHP also has support for talking to other services
using protocols such as LDAP, IMAP, SNMP,
NNTP, POP3, HTTP.
First PHP script
Save as sample.php:
<!– sample.php -->
<html><body>
<strong>Hello World!</strong><br />
<?php
echo “<h2>Hello, World</h2>”; ?>
<?php
$myvar = "Hello World";
echo $myvar;
?>
</body></html>
http://www.cs.kent.edu/~nruan/sample.php
PHP Control Structures
<?php
// Conditionals
if ($a) {
print "a is true<BR>\n";
} elseif ($b) {
print "b is true<BR>\n";
} else {
print "neither a or b is true<BR>\n";
}
52
PHP Control Structures….
// Loops
do {
$c = test_something();
} while ($c);
while ($d) {
print "ok<BR>\n";
$d = test_something();
}
for ($i = 0; $i < 10; $i++) {
print "i=$i<BR>\n";
}
?>
53
PHP Control Structures…
IF statement
Normal if..then..else statement
Ex.
if ($a<5) {
$b=$a+10;
}
else {
$b=$a*2;
}
54
PHP Control Structures…..
Operator Meaning
== Is Equal to
!= Not Equal to
< Is less than
<= Is less than or equal to
> Is Greater than
>= Is Greater than or equal to
&& and And
|| or Or
55
PHP Control Structures…..
For loop
Normal for loop: for (starting value;ending
value;increment)
Ex.
56
PHP Control Structures….
some statements
}
Ex.
$i=0;
while ($i<10){
echo $i;
$i++;
}
57
PHP Control Structures….
Again, these are similar to those in C++ / Java
if, while, do, for, switch are virtually identical to those
in C++ and Java
PHP allows for an alternative syntax to designate a
block in the if, while, for and switch statements
Open the block with : rather than {
Close the block with endif, endwhile, endfor, endswitch
Advantage to this syntax is readability
Now instead of seeing a number of close braces, we
see different keywords to close different types of control
structures
58
PHP Expressions and Operators
Similar to those in C++ / Java / Perl
Be careful with a few operators
/ in PHP is always floating point division
To get integer division, we must cast to int
$x = 15;
$y = 6;
echo ($x/$y), (int) ($x/$y), "<BR />";
Output is 2.5 2
59