DYNAMIC WEB DEVELOPMENT
WEEK 3.B: INTRODUCTION TO PHP
Correspond to Ch 2
Dr. Basel Almourad
GOALS
Learn some more PHP Basics and apply these to validating an
HTML form
OUTLINE
1. Creating and handling forms
2. Conditional statements
3. Iteration statements
4. Q & A
PHP CONTROL STRUCTURES-
INTRODUCTION
Control structures determine the flow of program
execution.
Three categories;
• Sequence – default control structure where the statements
are executed in the order they appear in the code.
• Selection – IF and switch case
• Iteration/Loop – while, do while and for loops
SELECTION CONTROL STRUCTURE
In PHP IF statement consist of:
• if statement - use this statement to execute some code only
if a specified condition is true
• if...else statement - use this statement to execute some
code if a condition is true and another code if the condition is
false
• if...elseif....else statement - use this statement to select one
of several blocks of code to be executed
THE IF STATEMENT
The PHP if statement is very similar to other
programming languages use of the if statement.
Example: Think about the decisions you make before
you go to sleep. If you have something to do the next
day, say go to work, school, or an appointment, then
you will set your alarm clock to wake you up.
Otherwise, you will sleep in as long as you like!
The PHP if statement tests to see if a value is true, and
if it is a segment of code will be executed.
The if statement is necessary for most programming,
thus it is important in PHP.
THE IF STATEMENT CONT..
if statement
if_statement.php
if (condition) { <body>
// Do something! <?php
$my_name = "anotherguy";
} if ($my_name == "someguy" )
if (condition) echo "Your name issomeguy!<br />";
?>
code to be executed if condition </body>
is true;
Display
How about A False If
Statement
if_statements_part_1.php
THE IF...ELSE STATEMENT
Use the if....else statement to execute some code if a
condition is true and another code if a condition is false
syntax
<body>
if (condition) { <?php
$grade = 90;
// Do something!
if (grade>=40)
} else { echo “you passed”;
// Do something else! else
} echo “you didn’t pass”;
<?php ?>
$d=date("D"); </body>
if ($d=="Fri")
echo "Have a nice weekend!";
else
echo "Have a nice day!";
?>
IF..ELSEIF…ELSE STATEMENT
Use the if....elseif...else statement to select one of
several blocks of code to be executed.
An elseif clause allows you to add more conditions:
if_statement2.php
if (condition1) { <body>
// Do something! <?php
} elseif (condition2) { $grade = 90;
// Do something else! if (grade>=80)
} else { echo “very well done”,
// Do something different! elseif (grade>=60)
echo “you passed”;
}
else
echo “you didn’t pass”;
?>
</body>
if_statements_part_2.php
CONDITIONAL
STATEMENT
Others:
o True, TRUE, true
always true
o isset($x): returns true
if a value was set for
$x (i.e. different from NULL)
o $var returns true if
$var value is different
from:
0
Empty string
FALSE
NULL
CONDITIONAL STATEMENT
switch statement
switch_statement.php
switch ($variable) { <?php
…
case 'value1’: switch ($gender) {
// Do this. case 'Male':
break; echo "Dear Mr. Doe";
case 'value2’: break;
// Do this instead. case 'Female':
break; echo "Dear Ms. Doe";
default: break;
default:
// Do this then.
echo "Dear Sir/Madam. Doe";
break; break;
} } ?>
switch.php
PHP - LOOPS
Repetitive tasks are always a burden to us. Most often
these repetitive tasks are conquered in the loop.
The idea of a loop is to do something over and over
again until the task has been completed.
PHP support three types of loops:
While loop
do while loop
for loop
PHP WHILE LOOP STATEMENTS
The function of the while loop is to
do a task over and over as long as
the specified conditional statement
is true.
While loop syntax
while (condition) {
// Do something.
}
A flowchart
representation
of how PHP
handles a
while loop.
PHP WHILE LOOP STATEMENTS
How while loop functions
1. The conditional statement is checked.
If it is true, then (2) occurs. If it is false, Example
then (4)occurs. $times = 5;
2. The code within the while loop is
executed. $x = 0;
3. The process starts again at (1).
Effectively "looping" back. while ($x < $times) {
4. If the conditional statement is false,
then the code within is not executed echo "Hello World";
and there is no more looping. The
code following the while loop is then ++$x;
executed like normal.
PHP WHILE LOOP EXAMPLE
$brush_price = 5;
$counter = 10;
echo "<table border=\"1\"
Displays
align=\"center\">";
echo "<tr><th>Quantity</th>"; echo
"<th>Price</th></tr>"; while
( $counter <= 100 ) {
echo "<tr><td>";
echo $counter;
echo "</td><td>";
echo $brush_price * $counter;
echo "</td></tr>";
$counter = $counter + 10;
}
echo "</table>";
FOR LOOP STATEMENTS
The for loop allows you to define these
steps in one easy line of code.
For loop syntax
for (initial expression; condition;
increment counter) {
// Do something.
}
A flowchart
representation
of how PHP
handles a for
PHP FOR LOOP STATEMENTS
How for loop functions
Example
1. Set a counter variable to some initial $brush_price = 5;
value. echo "<table border=\"1\" align=\"center\">";
2. Check to see if the conditional echo "<tr><th>Quantity</th>";
statement is true. echo "<th>Price</th></tr>";
3. Execute the code within the loop. for ( $counter = 10; $counter <= 100; $counter +=
4. Increment a counter at the end of each 10) {
echo "<tr><td>";
iteration through the loop.
echo $counter;
echo "</td><td>";
echo $brush_price * $counter;
echo "</td></tr>";
}
echo "</table>";
PHP - DO WHILE LOOP
A "do while" loop is a slightly modified version of the
while loop.
While Loops the conditional statement is checked
comes back true then the code within the while loop is
executed. If the conditional statement is false then the
code within the loop is not executed.
On the other hand, a do-while loop always executes its
block of code at least once. This is because the
conditional statement is not checked until after the
contained code has been executed.
COMPARISON
while Do while
$cookies = 0; $cookies = 0;
while($cookies > 1){ do {
echo "Mmmmm...I love cookies! echo "Mmmmm...I love
*munch munch munch*"; cookies! *munch
} munch munch*"; }
while ($cookies > 1);
USING PHP WITH HTML FORMS
A very common application of PHP is to have an HTML
form gather information from a website's visitor and
then use PHP to do process that information.
Two steps are involved:
first you create the HTML form itself, and
then you create the corresponding PHP script that will
receive and process the form data
An HTML form is created using the form tags and
various elements for taking input
In terms of PHP, the most important attribute of your
form tag is action, which dictates to which page the
form data will be sent.
The second attribute—method—has its own issues but
post is the value you’ll use most frequently
CREATING AND HANDLING FORMS
Creating an HTML form: example
form.html
<body>
<form action="handle_form.php" method="post">
Name: <input type="text" name="name" size="20" maxlength= "40" /><br />
Gender:<input type="radio" name="gender" value="M" /> Male
<input type="radio" name="gender" value="F" /> Female<br />
Age: <select name="age">
<option value="0-29">Under 30</option>
<option value="30-60">Between 30 and 60</option>
</select><br />
<input type= "submit" name="submit" value="Submit My Information" /><br>
</form>
</body>
Output
form.html
handle_form.php
CREATING AND HANDLING FORMS
Handling an HTML form
input fields are accessible via: $_REQUEST[‘field-name‘].
e.g. $_REQUEST[‘age'].
Element Name Variable Name
name $_REQUEST['name']
Age $_REQUEST['age']
Gender $_REQUEST['gender']
submit $_REQUEST['submit']
$_REQUEST is a special variable type, known as a
superglobal.
It stores all of the data sent to a PHP page
CREATING AND HANDLING FORMS
Handling an HTML form
handle_form.php
<?php
$name = $_REQUEST['name'];
$age = $_REQUEST['age'];
$gender=$_REQUEST['gender'];
// Print the submitted information:
echo "<p>Thank you, <b>$name</b>, for participating to the survey:<br /> "
. "Your age is in the range of: $age <br />and your gender is
<i>$gender</i>.</p>\n";
?>
Output
VALIDATING FORM DATA
Two main goals
a) validate if something was entered or selected in form
elements
o empty() : validate if something was typed into a text input
• empty value = empty string, 0, NULL, or FALSE.
b) validate the input data type and format
o right type; e.g. numeric, string, etc.
o right format; e.g. email has form
[email protected] o acceptable value; e.g. $gender is equal to either M or F
VALIDATING FORM DATA
Example
validate_form1.php
<?php
// Validate the name:
if (!empty($_REQUEST['name'])) {
$name = $_REQUEST['name’];
} else {
$name = NULL;
echo ‘<p style=“color:red”>You forgot to enter
your name!</p>’;
}
?>
form1.html
handle_form1.php
VALIDATING FORM DATA
Some triimportant functions
trim(): eliminates leading and trailing spaces
is_numeric( ) : tests if a submitted value is a number
preg_match( ): indicates whether or not a string matches
a given pattern (e.g. includes ‘@’)
o Pattern should be between single quotation marks
o Pattern need to start and end with delimiter
o Will be using forward slash: /
o If / is part of the patter, use a different delimiter; e.g. !, |,
etc.
BASIC REGULAR EXPRESSIONS
• "/abc/"
• in PHP, regexes are strings that begin and end with /
the simplest regexes simply match a particular substring
the above regular expression matches any string containing
"abc":
• YES: "abc", "abcdef", "defabc", ".=.abc.=.", ... NO:"fedcba","ab
c","PHP",...
form2.html
handle_form2.php
handle_form2.php use regular expression to validate form content
PATTERNS.PHP
patterns.php
Can be used to test the pattern
WILDCARDS: .
• A dot . matches any character except a \n line break "/.oo.y/"
matches "Doocy", "goofy", "LooNy", ...
• A trailing i at the end of a regex (after the closing /) signifies a
case-insensitive match "/mart/i"matches"Marty Stepp","smart
fellow","WALMART",...
SPECIAL CHARACTERS: |, (), ^, \
• | means OR
• "/abc|def|g/" matches "abc", "def", or "g"
• There's no AND symbol. Why not?
• () are for grouping
• "/(Homer|Marge) Simpson/’ matches "Homer Simpson” or
"Marge Simpson"
• ^ matches the beginning of a line; $ the end
• "/^<!--$/" matches a line that consists entirely of "<!--"
• \ starts an escape sequence
• Many characters must be escaped to match them literally. All
the following characters: / \ $ . [ ] ( ) ^ * + ?
"/<br \ / > /” matches lines containing <br />tags
QUANTIFIERS: *, +, ?
• * means 0 or more occurrences
• "/abc*/" matches "ab", "abc", "abcc", "abccc", ...
• "/a(bc)*/"matches "a", "abc", "abcbc", "abcbcbc", ...
• "/a.*a/" matches "aa", "aba", "a8qa", "a!?_a", ...
• + means 1 or more occurrences
• "/a(bc)+/" matches "abc", "abcbc", "abcbcbc", ...
• "/Goo+gle/" matches "Google", "Gooogle",
"Goooogle", ...
• ? means 0 or 1 occurrences
• "/a(bc)?/" matches "a" or "abc"
MORE QUANTIFIERS:
{MIN, MAX}
• {min,max} means between min and max
occurrences (inclusive)
• "/a(bc){2,4}/" matches "abcbc", "abcbcbc", or
"abcbcbcbc"
• min or max may be omitted to specify any number
• {2,} means 2 or more
• {,6} means up to 6
• {3} means exactly 3
CHARACTER SETS: [ ]
• [ ] group characters into a character set; will match any single
character from the set
• "/[bcd]art/" matches strings containing "bart", "cart", and "dart”
• equivalent to "/(b|c|d)art/" but shorter
• inside [ ], many of the modifier keys act as normal characters
• "/what [!*?]*/" matches "what", "what!", "what?**!",
"what??!", ...
• What regular expression matches DNA (strings of A, C, G, or
T)?
• "/[ACGT]+/"
CHARACTER RANGES:
[START - END]
• inside a character set, specify a range of characters with –
• "/[a-z]/" matches any lowercase letter
• "/[a-zA-Z0-9]/" matches any lower- or uppercase letter or digit
• an initial ^ inside a character set negates it
• "/[^abcd]/" matches any character other than a, b, c, or d
• inside a character set, - must be escaped to be matched
• "/[+\-]?[0-9]+/" matches an optional + or -, followed by at least
one digit
• What regular expression matches letter grades such as A, B+,
or D- ?
• "/[ABCDF][+\-]?/"
ESCAPE SEQUENCES
• special escape sequence character sets:
• \d matches any digit (same as [0-9]); \D any non-
digit ([^0-9])
• \w matches any “word character” (same as [a-zA-
Z_0-9]); \W any non-word char
• \s matches any whitespace character ( , \t, \n, etc.);
\S any non-whitespace
• What regular expression matches dollar amounts of
at least $100.00 ?
• "/ \$ \d{3,}\.\d{2}/"
VALIDATING FORM DATA
Examples
preg_match('/a/', 'cat’): checks if the string cat contains
the letter a
preg_match(‘/^a/', 'cat’): checks if the string cat starts
with the letter a
preg_match(‘/a$/', 'cat’): checks if the string cat ends
with the letter a
VALIDATING FORM DATA
Defining patterns
A pattern may include:
Literals: values that are written exactly as they are
interpreted; e.g.
o ‘/ab/’ will match ab
o ‘/rom/’ will match any of cd-rom, writing a roman,
roommate
meta-characters: special symbols that have a
meaning beyond their literal value; e.g.
o The period (.) will match any single character
except for a newline
o ‘/1.99/’ matches 1.99 or 1B99 or 1299
VALIDATING FORM DATA
Defining patterns
A pattern may include:
Quantifiers: metacharacters that specifie number of
occurances; e.g.
o ‘/a*/’ will match zero or more a’s
o ‘/a+/’ will match one or more a’s
o ‘/a?/’ will match zero or one a
o ‘/a{3}/’ will match three a’s, i.e. aaa
o ‘/a{3,}/’ will match three a’s or more
o ‘/a{3,5}/’ will match between three and five a’s
VALIDATING FORM DATA
EXAMPLES
• Match any upper or lower case alpha character:
[A-Za-z]
• Match any lower case vowel character:
[aeiou]
• Match any numeric digit character:
[0-9]
• Match any non-alpha character:
[^A-Za-z]
• Match any non-vowel character:
[^aeiou]
• Match any non-numeric digit:
[^0-9]
PHP - VALIDATE NAME
• The code below shows a simple way to check if the name
field only contains letters and whitespace. If the value of the
name field is not valid, then store an error message:
$name = $_REQUEST['name’];
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
• Note the space between Z and ]
MORE EXAMPLES
• Check Username 5 to 10 lowercase letters?
$name = $_REQUEST['name’];
$pattern = '/^[a-z]{5,10}$/';
if (!preg_match($pattern, $name))
{
echo "<p>$username is invalid.</p>";
}
Check Social Security Number 123-45-6789
$pattern = '/^[0-9]{3}-[0-9]{2}-[0-9]{4}$/';
if (!preg_match($pattern, $ssn))
{
echo "<p>$ssn is invalid.</p>";
}
EMAIL VALIDATION
• The Most Basic common pattern
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]
+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/i",$email))
PRACTICE
Create an html form and a php web page to do the
following:
1. Display a form to the user to enter his/her name and GPA
2. Check if a name was entered and that the GPA is valid (is a
number between 0 and 4)
3. If any of the two conditions is not true
a. print an error message to the user explaining what the error
is (e.g. “the user name should not be empty” and “the GPA
should be a number between 0 and 4”)
b. Allow the user to go back to the form
4. If both conditions are true, Display a message thanking the user;
e.g. “Thank you Noora for sending your request. Your GPA ‘3’ was
recorded. We will contact you soon”
PRACTICE
Steps
1. Display the form (practice.html) send data to practice.php
2. In the practice.php
a) Declare two variables ($name and $gpa) to read the inputs
b) Check the name if empty, display error message stating that “the name
should not be empty”
Should open the form again
echo "<a href='index.html'>click
to restart</a>";
c) If name not empty, check gpa if GPA not valid (i.e. not a number or not
between 0 and 4), display error message stating that “the GPA should be
a number between 0 and 4.”
d) If GPA valid, display a message thanking the user; e.g.
ANY QUESTIONS?
45
REFERENCES
• Book
• “PHP and MySQL for Dynamic Web Sites” 4th edition,
Chapters 2 & 14
• PHP
• https://www.w3schools.com/php/default.asp
• http://php.net/manual/en/langref.php
A Live Regular Expression Tester for PHP
• https://regex101.com
•
46