Internet Programming II
Chapter: 2
PHP Statements and Form Creations
Outline
PHP Conditional Statements
PHP Operators
PHP Loops
PHP Functions
PHP Arrays
PHP GET and POST Methods
PHP Form Handling
PHP error handling
PHP form validation
PHP Regular Expressions
2
PHP Conditional Statements
PHP - The if Statement
̶ The if statement executes some code if one condition is
true.
̶ Syntax:
if (condition) {
code to be executed if condition is true;
}
̶ Example:
<?php
$t = date("H"); //H means hour of the system
if ($t < "20") {
echo "Have a good day!";
}
?>
3
Cont’d
PHP - The if...else Statement
̶ The if...else statement executes some code if a condition is true and
another code if that condition is false.
̶ Syntax:
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
̶ Example:
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
4
Cont’d
PHP - The if...elseif...else Statement
̶ The if...elseif...else statement executes different codes for
more than two conditions.
̶ Syntax:
if(condition) {
code to be executed if this condition is true;
}elseif (condition) {
code to be executed if first condition is
false and this condition is true;
} else {
code to be executed if all conditions are
false;
}
5
Cont’d
̶ Example:
<?php
$t=date("H");
if($t<"10") {
echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
6
Cont’d
The PHP switch Statement
̶ Use the switch statement to select one of many blocks of
code to be executed.
̶ Syntax:
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
7 }
Cont’d
̶ Example:
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favourite colour is neither red, blue, nor green!";
}
?>
8
PHP Operators
Operators are used to perform operations on variables and
values.
PHP Arithmetic Operators:
̶ The PHP arithmetic operators are used with numeric values to
perform common arithmetical operations, such as addition,
subtraction, multiplication etc.
9
Cont’d
PHP Assignment Operators
̶ The PHP assignment operators are used with numeric
values to write a value to a variable.
10
Cont’d
PHP Comparison Operators
̶ The PHP comparison operators are used to compare two values
(number or string).
11
Cont’d
PHP Increment / Decrement Operators
̶ The PHP increment operators are used to increment a
variable's value.
̶ The PHP decrement operators are used to decrement a
variable's value.
12
Cont’d
PHP Logical Operators
̶ The PHP logical operators are used to combine
conditional statements.
13
Cont’d
PHP String Operators
̶ PHP has two operators that are specially designed for strings.
PHP Conditional Assignment Operators
̶ The PHP conditional assignment operators are used to set a value
depending on conditions:
14
PHP Loops
Loops are used to execute the same block of code again and again, as
long as a certain condition is true.
The PHP while Loop
̶ The while loop executes a block of code as long as the specified
condition is true.
̶ Syntax:
while (condition is true) {
code to be executed;
}
Example:
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
15
Cont’d
The PHP do...while Loop
̶ The do...while loop will always execute the block of code once,
it will then check the condition, and repeat the loop while the
specified condition is true.
̶ Syntax:
do {
code to be executed;
} while (condition is true);
̶ Example
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
16
Cont’d
The PHP for Loop
̶ The for loop is used when you know in advance how
many times the script should run.
̶ Syntax:
for (init counter; test counter;increment counter) {
code to be executed for each iteration;
}
̶ Example
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
17
Cont’d
The PHP foreach Loop
̶ The foreach loop works only on arrays, and is used to loop through
each key/value pair in an array.
̶ Syntax:
foreach ($array as $value) {
code to be executed;
}
̶ Example:
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
18
Cont’d
PHP Break
̶ The break statement can also be used to jump out of a loop.
̶ Example:
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
break;
}
echo "The number is: $x <br>";
}
?>
PHP Continue
̶ The continue statement breaks one iteration (in the loop), if a specified condition
occurs, and continues with the next iteration in the loop.
̶ Example:
<?php
for ($x = 0; $x < 10; $x++) {
if ($x == 4) {
continue;
}
echo "The number is: $x <br>";
}
?>
19
PHP Functions
A function is a block of statements that can be used repeatedly in a
program.
A function will not execute automatically when a page loads.
A function will be executed by a call to the function.
A user-defined function declaration starts with the word function:
Syntax:
function functionName() {
code to be executed;
}
Example:
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg(); // call the function
?>
20
Cont’d
PHP Function Arguments
̶ Information can be passed to functions through arguments.
̶ An argument is just like a variable.
̶ Arguments are specified after the function name, inside the
parentheses.
̶ You can add as many arguments as you want, just separate them with
a comma.
̶ Example
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
21
?>
Cont’d
̶ To let a function return a value, use the return statement.
̶ Example:
<?php declare(strict_types=1);// strict requirement
function sum(int $x, int $y) {
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5, 10) . "<br>";
echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?>
22
Cont’d
Passing Arguments by Reference
̶ In PHP, arguments are usually passed by value, which means
that a copy of the value is used in the function and the variable
that was passed into the function cannot be changed.
̶ When a function argument is passed by reference, changes to
the argument also change the variable that was passed in.
̶ To turn a function argument into a reference, the & operator is
used.
Example
<?php
function add_five(&$value) {
$value += 5;
}
$num = 2;
add_five($num);
echo $num;
?>
23
Cont’d
Setting Default Values for Function Parameters:
We can set a parameter to have a default value if the function's caller
doesn't pass it.
Example:
<?php
function setHeight($minheight = 50)
{
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
24
PHP Date and Time
The PHP date()function formats a timestamp to a more
readable date and time.
Syntax: date(format,timestamp)
Example
<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo "Today is " . date("Y.m.d") . "<br>";
echo "Today is " . date("Y-m-d") . "<br>";
echo "Today is " . date("l");
?>
PHP - Automatic Copyright Year
̶ Use the date() function to automatically update the copyright year on
your website:
̶ Example
© 2010-<?php echo date("Y");?>
25
PHP Math
PHP has a set of math functions that allows you to perform
mathematical tasks on numbers.
̶ The pi() function returns the value of PI:
Example:
<?php
echo(pi());// returns 3.1415926535898
?>
̶ The min() and max()functions can be used to find the
lowest or highest value in a list of arguments:
Example:
<?php
echo(min(0,150,30,20,-8,-200)); // returns -200
echo(max(0,150,30,20,-8,-200)); // returns 150
?>
26
Cont’d
̶ The abs()function returns the absolute (positive) value of a number.
Example:
<?php
echo(abs(-6.7)); // returns 6.7
?>
̶ The sqrt()function returns the square root of a number.
Example:
<?php
echo(sqrt(64)); // returns 8
?>
̶ The round()function rounds a floating-point number to its nearest
integer.
Example:
<?php
echo(round(0.60)); // returns 1
echo(round(0.49)); // returns 0
?>
27
PHP Arrays
An array is a special variable, which can hold more than one
value at a time.
In PHP, the array()function is used to create an array.
The count()function is used to return the length (the
number of elements) of an array.
Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
28
Cont’d
In PHP, there are three types of arrays:
Numeric Array
̶ These arrays can store numbers, strings and any object
but their index will be represented by numbers.
̶ By default array index starts from zero.
̶ Following is the example showing how to create and
access numeric arrays.
̶ There are two ways to create numeric arrays:
The index can be assigned automatically (index always starts at 0)
the index can be assigned manually:
29
Cont’d
<?php
// First method to create array.
$numbers = array( 1, 2, 3, 4, 5);
//accessing array values using loops
foreach( $numbers as $value ) {
echo "Value is $value <br />";
}
// Second method to create array.
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
//accessing array values using loops
foreach( $numbers as $value ) {
echo "Value is $value <br />";
}
30 ?>
Cont’d
Associative Arrays
̶ Associative array will have their index as string .
̶ each ID key is associated with a value .
̶ For example, to store the salaries of employees in an array,
we could use the employees names as the keys in our
associative array, and the value would be their respective
salary.
31
Cont’d
<?php
// First method to create associative array.
$salaries = array("mohammad"=> 2000,"qadir"=>1000,"zara"=>500);
//accessing values using loops
foreach($salaries as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
// Second method to create array.
$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";
//accessing the values
echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";
echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
?>
32
Cont’d
Multidimensional Arrays
̶ A multidimensional array is an array containing one or more arrays.
̶ Example:
<?php
$marks = array( "mohammad" => array ( "physics" => 35, "maths" => 30, "chemistry" => 39 ),
"qadir" => array ( "physics" => 30, "maths" => 32, "chemistry" => 29 ),
"zara" => array ( "physics" => 31, "maths" => 22, "chemistry" => 39 ) );
// Accessing multi-dimensional array values
echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";
echo "Marks for qadir in maths : ";
echo $marks['qadir']['maths'] . "<br />";
echo "Marks for zara in chemistry : " ;
echo $marks['zara']['chemistry'] . "<br />";
?>
33
Cont’d
We can access multidimensional array using loops
<?php
foreach ( $marks as $val )
{
foreach ( $val as $key=>$final_val )
{
print "$key : $final_val <br>";
}
print "<br>";
}
?>
34
Cont’d
PHP array functions
PHP comes with different functions that allow us to add or remove
elements from the beginning or end of an array:
The array_unshift() function adds an element to the beginning
of an array
The array_shift() function removes the first element of an array;
The array_push() function adds an element to the end of an
array
The array_pop() function removes the last element of an array.
The above array functions should be used only with numerically
indexed arrays and not with associative arrays.
The sort() function sort arrays in ascending order
The rsort() function sort arrays in descending order
35
Cont’d
Example:
<?php
// define array
$movies = array('The Lion King', 'Cars', 'A Bug\'s Life');
// sort the array in ascending order
sort($cars);
// remove element from beginning of array
array_shift($movies);
// remove element from end of array
array_pop($movies);
// add element to end of array
array_push($movies, 'Ratatouille');
// add element to beginning of array
array_unshift($movies, 'The Incredibles');
// print array
print_r($movies);//output:('The Incredibles','Cars','Ratatouille')
?>
36
Cont’d
Assigning a Range of Values in arrays:
We use the range( ) function to create an array of
consecutive integer or character values between the two
values we pass to it as arguments.
Example:
$numbers = range(2, 5); // $numbers = array(2, 3, 4, 5);
$letters = range('a', 'z'); // $numbers holds the alphabet
$reversed_numbers = range(5, 2); // $numbers = array(5, 4, 3, 2);
37
Cont’d
Getting the Size of an Array:
Use the count( ) and sizeof( ) functions interchangeably.
Example:
$family = array('Fred', 'Wilma', 'Pebbles');
$size = count($family); // $size is 3
Extracting Multiple Values:
To copy all of an array's values into variables, use the list()
functions like
list($variable, ...)
Example: $array=(“google”,”facebook”);
list($first, $second)=$array;
38
PHP GET and POST Methods
There are two ways the browser client can send information
to the web server. The GET Method and The POST Method.
The GET Method:-
̶ It has restriction to send to server/ database (upto 1024
characters only).
̶ It can't be used to send binary data, like images or word
documents.
̶ The information sent from a form with the GET method is
visible to everyone (it will be displayed in the browser's
address bar)
̶ The $_GET variable is used to collect values from a form
with method="get".
39
Cont’d
Example:
<?php
if( isset($_GET[“n"]) || isset($_GET["age"] ))
{ echo "Welcome ". $_GET[n']. "<br />";
echo "You are ". $_GET['age']. " years old.";
exit(); }
?>
<html>
<body>
<form action= " welcome.php" method="GET">
Name: <input type="text" name=“n" /> <br><br>
Age: <input type="text" name="age" /> <br><br>
<input type="submit" />
</form>
</body>
40
</html>
Cont’d
The POST Method:
̶ It does not have restrictions on data size
̶ Secured(Variables sent with HTTP POST are not shown
in the URL)
̶ It can be used to send ASCII as well as binary data
̶ The $_POST variable is used to collect values from a form
with method="post".
̶ The data sent by POST method goes through HTTP
header is secured enough on HTTP protocol.
41
Cont’d
Example:
<?php
if( isset($_POST["name"]) || isset($_POST["age"] ))
{ echo "Welcome ". $_POST['name']. "<br />";
echo "You are ". $_POST['age']. " years old.";
exit();
}
?>
<html>
<body>
<form action= " welcome.php" method="POST">
Name: <input type="text" name="name" /><br><br>
Age: <input type="text" name="age" /><br><br>
<input type="submit" />
</form>
</body>
</html>
42
Cont’d
The $_REQUEST variable:
̶ The PHP $_REQUEST variable contains the contents of $_GET, $_POST, and
$_COOKIE variables
̶ This variable can be used to get the result from form data sent with both the GET
and POST methods.
̶ Example:-
<?php
if( isset($_REQUEST["name"]) || isste($_REQUEST["age"] ))
{
echo "Welcome ". $_REQUEST['name']. "<br />";
echo "You are ". $_REQUEST['age']. " years old.";
exit(); }
?>
<html>
<body>
<form action="<?php $_PHP_SELF ?>" method="POST">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
43
</body> </html>
PHP Form Handling
Form is a Document that containing black fields, that the
user can fill the data or user can select the data.
Casually the data will store in the data base.
It works as follows:
44
Cont’d
The syntax could be written as:
<form action= "url to submit the form filled "
method="get" or "post" or "request" >
<!–- form contents -->
</form>
Where
̶ action=“…” is the page that the form should submit its data to, and
̶ method=“…” is the method by which the form data is submitted.
If the method is get the data is passed in the url string,
if the method is post it is passed as a separate file.
45
Cont’d
The example below displays a simple HTML form with two input fields
and a submit button.
When the user fills out the form above and clicks the submit button, the
form data is sent for processing to a PHP file named "welcome.php".
The form data is sent with the HTTP POST method.
<html> welcome.php
<body> <html>
<form action="welcome.php" method="post"> <body>
Name: <input type="text" name="name"><br> Welcome <?php echo $_POST["name"]; ?>
E-mail: <input type="text" name="email"><br> <br>
<input type="submit"> Your email address is:
</form>
<?php
</body>
echo $_POST["email"];
</html>
?>
</body>
</html>
46
PHP Form Validation
We can use JavaScript for validating form fields.
Validations can also be done with simple PHP if statements as shown
below.
Validate String:
The code below checks that the field will contain only alphabets and
whitespace, for example - name.
If the name field does not receive valid input from the user, then it will
show an error message.
$name = $_POST ["Name"];
if (!preg_match ("/^[a-zA-z]*$/", $name) ) {
$ErrMsg = "Only alphabets and whitespace are allowed.";
echo $ErrMsg;
} else {
echo $name;
47 }
Cont’d
Validate Number:
The below code validates that the field will only contain a numeric value.
For example - Mobile no. If the Mobile no field does not receive numeric
data from the user, the code will display an error message.
$mobileno = $_POST ["Mobile_no"];
if (!preg_match ("/^[0-9]*$/", $mobileno) ){
$ErrMsg = "Only numeric value is allowed.";
echo $ErrMsg;
} else {
echo $mobileno;
}
48
Cont’d
Validate Email:
A valid email must contain @ and . symbols.
PHP provides various methods to validate the email address.
Here, we will use regular expressions to validate the email
address.
The below code validates the email address provided by the user
through HTML form. If the field does not contain a valid email
address, then the code will display an error message:
$email = $_POST ["Email"];
$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^";
if (!preg_match ($pattern, $email) ){
$ErrMsg = "Email is not valid.";
echo $ErrMsg;
} else {
echo "Your valid email address is: " .$email;
49 }
Cont’d
Input Length Validation:
The input length validation restricts the user to provide the value
between the specified range, for Example - Mobile Number. A
valid mobile number must have 10 digits.
The given code will help you to apply the length validation on user
input:
$mobileno = strlen ($_POST ["Mobile"]);
$length = strlen ($mobileno);
if ( $length < 10 or $length > 10) {
$ErrMsg = "Mobile must have 10 digits.";
echo $ErrMsg;
} else {
echo "Your Mobile number is: " .$mobileno;
}
50
Cont’d
Validate URL:
The below code validates the URL of website provided by
the user via HTML form. If the field does not contain a valid
URL, the code will display an error message, i.e., "URL is
not valid".
$websiteURL = $_POST["website"];
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-
9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "URL is not valid";
echo $websiteErr;
} else {
echo "Website URL is: " .$websiteURL;
}
51
PHP Error Handling
Error handling is the process of catching errors raised by the
program and then taking appropriate action.
Using die() function:
While writing PHP program, we should check all possible error
condition before going ahead and take appropriate action when
required.
Example:
<?php
if(!file_exists("/tmp/test.txt")) {
die("File not found");
}
else {
$file=fopen("/tmp/test.txt","r");
print "Opend file sucessfully";
}
// Test of the code here.
52 ?>
PHP Regular Expressions
Regular expressions are commonly known as regex.
A regular expression is a sequence of characters that forms
a search pattern.
When you search for data in a text, you can use this search
pattern to describe what you are searching for.
A regular expression can be a single character, or a more
complicated pattern.
Regular expressions can be used to perform all types of text
search and text replace operations.
By default, regular expressions are case sensitive.
53
Cont’d
Regular Expression Functions:
PHP provides a variety of functions that allow you to use regular
expressions.
The preg_match(),preg_match_all() and preg_replace()
functions are some of the most commonly used ones:
54
Cont’d
Regular Expression Modifiers:
̶ Modifiers can change how a search is performed.
Regular Expression Patterns:
̶ Brackets are used to find a range of characters:
55
Cont’d
Metacharacters:
̶ Metacharacters are characters with a special meaning:
56
Cont’d
Quantifiers:
̶ Quantifiers define quantities.
57
Some Operators in Regular Expression
58
Questions?
59