0% found this document useful (0 votes)
2 views38 pages

PHP Chapter 2 HTML Forms and Server Side Scripting

Chapter 2 covers HTML forms and server-side scripting using PHP, focusing on conditionals, validation, data handling, and arrays. It explains how to create forms, validate user inputs, and manage data through various PHP functions and loops. Additionally, the chapter introduces different types of arrays and their manipulation in PHP.

Uploaded by

ararsojaleto5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views38 pages

PHP Chapter 2 HTML Forms and Server Side Scripting

Chapter 2 covers HTML forms and server-side scripting using PHP, focusing on conditionals, validation, data handling, and arrays. It explains how to create forms, validate user inputs, and manage data through various PHP functions and loops. Additionally, the chapter introduces different types of arrays and their manipulation in PHP.

Uploaded by

ararsojaleto5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CHAPTER 2

HTML Forms and


Server-Side Scripting
1
outline
2.1. Use Conditionals and Operators
2.2. Validate Form
2.3. Send Values to a Script Manually
2.4. Work with Forms and arrays of data
2.5. Use For and While Loops
2.7. Create a Simple Form using PHP
2.8. Use Get or Post
2.9. Receive Data from a Form in PHP
2.10. Introduction to regular expressions

2
2.1. Use Conditionals and Operators
◼ Conditional statements are used to perform different actions
based on different conditions. They are used to perform
different actions for different conditions.
◼ PHP conditional statements:

 if statement - executes some code if one condition is true


 if...else statement - executes some code if a condition is true
and another code if that condition is false
 if...elseif....else statement - executes different codes for more
than two conditions
 switch statement - selects one of many blocks of code to be
executed
a. The if Statement - Syntax if (condition) {
code to be executed if condition is true;
}

3
1a. Example b. if...else Statement - Syntax
<?php
$dt = date("H"); if (condition) {
if ($dt < "1") { code to be executed if condition is true;
echo "The first day of the } else {
Month!"; code to be executed if condition is false;
} }
?>
c. The if...elseif....else
Statement - Syntax
1b. Example
if (condition) {
<?php
code to be executed if this condition is
$item = 10; // Set this to a number greater
true;
than 5!
} elseif (condition) {
if ($items > 5)
code to be executed if this condition is
{ echo "Discount is 10%!";
true;
} else ($items <= 5)
} else {
{ echo "Discount is 5%!"
code to be executed if all conditions are
}?>
false;
}
4
1c. Example d. The PHP switch Statement
The switch statement is used to select one of
. <?php
many blocks of code to be executed.
$dt = date("D");
if($dt == "Sat") Syntax
{ echo "The first Weekend!"; switch (n) {
} elseif($dt == "Sun") case label1:
{ echo "The last day of the // code to be executed if n=label1;
week!"; break;
} else case label2:
{ echo "It is weekday!"; // 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;
}

5
1d. Example
<?php
$myDay = date("D");
break;
switch($myDay){
case "Sat":
case "Mon":
echo "Today is Sixth day!";
echo "Today is the first day!";
break;
break;
case "Sun":
case "Tue":
echo "Today is Seventh day!";
echo "Today is second day!";
break;
break;
default:
case "Wed":
echo "None!";
echo "Today is third day!";
break;
break;
}
case "Thu":
?>
echo "Today is Fourth day!";
break;
case "Fri":
echo "Today is Fifth day!";

6
2.2. Validate Form Data
◼ Validation of form data helps to implement some
basic security feature to the user's input so that
users cannot insert potentially harmful data that
compromise the website security or might break
the application.
This can be done by:
◼ Passing all variables through PHP's
htmlspecialchars() function.
◼ When we use the htmlspecialchars() function;
then if a user tries to submit a script code it will be
translated as HTML code.
7
Example 1:
<script>[Link]('[Link]

❖ would be saved as HTML escaped code, like this:


&lt;script&gt;[Link]('[Link]

Example 2:
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>"> Will be saved as
<form method="post"
action="test_form.php/&quot;&gt;&lt;script&gt;alert('hacked')&lt;/script&gt;">
 Asking the users to enter comments about the website.
 Displaying the contact form and process the submitted form data.
 Sanitizing and validating user inputs. Redisplays the form with an error message
if any required field is missing or due to incorrect inputs.
 Remembering which fields, the user has already filled in, and prefills those fields
when the form redisplayed due to validation error.

8
Cont’d….
 Send an email to the website administrator and display a success message to the
user if the data is successfully submitted and accepted.
. can also do two more things when the user submits the form:
We
1. Strip unnecessary characters (extra space, tab, newline) from the user input
data (with the
PHP trim() function)
2. Remove backslashes (\) from the user input data (with the PHP stripslashes()
function) <p><b>Name: <input type="text" name="name">
Simple HTML Form <sup>*</sup></p>
<html> <p>E-mail: <input type="text" name="email" required>
<head> <sup>*</sup></p>
</head> <center><p> <Input type="submit" name="submit"
<body> value="Send"></p></center>
<table border ="1"> </form>
<tr><td> </td></tr>
<center><p><b>Simple Registration Form </table>
</b></p></center> </body>
<form method="post" action="[Link]"> </html>

9
PHP Code to validate user Inputs to the form
Syntax:
if(!preg_match("/^[a-zA-Z ]*$/",$name)) //Returns true if pattern exists
 ^ and $ - require the whole string match
 [] - is a character class - any character inside is allowed.
 a-zA-Z - Range that the character class understands
 \d - is a number. Checking Valid Emails
Example: Syntax:
<?php (!filter_var($email,
} FILTER_VALIDATE_EMAIL))
function validate(){ Example:
$name = $_POST["name"]; <?php
$name = stripslashes($name); function validate(){
$name = htmlspecialchars($name); $email = $_POST["email"];
if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $email = stripslashes($email);
$email = htmlspecialchars($email);
$nameErr = "Only letters and white space allowed"; if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo $nameErr; $emailErr = "Invalid email format";
} validate(); echo $emailErr;
?> }} validate();
?>

10
2.3. Send Values to a Script Manually
◼ One can pass data to a PHP script by creating an HTML form that uses the
GET method. But you can also use the same idea to send data to a PHP
page without the use of the form - by creating links like: <a
href="[Link]?id=22">Some Link</a>
◼ The link, which could be dynamically generated by PHP, will pass the
value 22 to [Link], accessible in $_GET['id'].
Example: (File name - [Link]) Creating the PHP script as [Link]:
Creating the Form
<html>
<html>
<head>
<body>
<title>Greetings!</title>
<div><p>Click the following link:</p>
</head>
<ul>
<body>
<li><a href="[Link]? name=Abebe"> Abebe </a></li>
<?php
<li><a href="[Link]? name=Bekele"> Bekele </a></li>
$name = $_GET['name'];
<li><a href="[Link]? name=Tolesa"> Tolesa </a></li>
print "<p>Hello, <span style=\"font-weight:
<li><a href="[Link]? name=Ayantu"> Ayantu </a></li>
bold;\">$name</span>!</p>";
</ul>
?>
</div>
</body>
</body>
</html>
</html>

11
2.4. Work with Forms and arrays of data
◼ An array is a special variable that stores multiple values in one single variable:

Creating an Array

◼ The formal method of creating an array is to use the array() function.


Syntax:

$list = array ('apples', 'bananas', 'oranges'); // Index not specified

Example:
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

In PHP, there are three types of arrays:


• Indexed arrays - Arrays with a numeric index
• Associative arrays - Arrays with named keys
• Multidimensional arrays - Arrays containing one or more arrays

12
a. Indexed arrays
◼ There are two ways to create indexed arrays:
◼ The index can be assigned automatically (index always starts at 0), like this:

$cars = array("Volvo", "BMW", "Toyota");

◼ or the index can be assigned manually:


$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
▪ Index can also be assigned as:

$list = array (1 => 'apples', 2 => 'bananas', 3 => 'oranges');


◼ The count() Function
◼ The count() function is used to return the length (the number of elements) of an array:
<?php
Example: $mamal = array(“Dog", “Cat", “Rat");
echo count($mamal);
?>

13
Looping through an Indexed Array
❖ A for loop can be used to loop through and print all the values of an
indexed array.
Example
<?php
$departments = array(“IT", “SC", “IS", “SE");
$deptcnt = count($ departments);
for($i = 0; $i < $ deptcnt; $i++) {
echo $ departments[$i];
echo "<br>";
}
?>

b. PHP Associative Arrays


Associative arrays are arrays that use named keys that you assign to them. There are
two ways to create an associative array:

14
Cont’d…
The two ways to create an associative array:

$age = array("Abebe"=>"35", "Tolesa"=>"37", "Ajyet"=>"43");


or:
$age['Abebe'] = "35";
$age['Tolesa'] = "37";
$age['Ajyet'] = "43";

Example 1:
<?php
$age = array("Abebe"=>"35", "Tolesa"=>"37", "Ajyet"=>"43");
echo "Ajyet is " . $age['Ajyet'] . " years old.";
?>

15
Example 2:
<html>
<head> <title>Food Menu!</title> </head>
<body>
<h1>Our Weekly Menu </h1>
<?php
$fdmenu = array ('Monday' => 'Clam Chowder', 'Tuesday' => 'White Chicken Chili',
'Wednesday' => 'Vegetarian');
print "<p>$fdmenu </p>";
print_r ($fdmenu);
?>
</body>
</html>
Looping through an Associative Array:
foreach loop can be used to loop through and print all the values of an associative
array. Example
<?php
$age = array("Abebe"=>"35", "Tolesa"=>"37", "Ayantu"=>"43");
foreach($age as $i => $i_value)
{ echo "Key=" . $i . ", Value=" . $i_value;
echo "<br>";
}
?> 16
Multidimensional Arrays
◼ A multidimensional array is an array containing one or
more arrays. The dimension of an array indicates the
number of indices you need to select an element.
 For a two-dimensional array you need two indices to
select an element
 For a three-dimensional array you need three indices to
select an element
Two-dimensional Arrays
◼ A two-dimensional array is an array of arrays as shown
below:

17
Cont’d…
◼ The data in the above table can be stored in a two dimensional array
as:
$cars = array(array("Volvo",22,18), array("BMW",15,13), array("Ford",5,2),
array("Land Rover",17,15));
◼ Now the two-dimensional $cars array contains four arrays, and it has
two indices: row and column. To get access to the elements of the
$cars array we must point to the row and column:
Example 1:
<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>
▪ We can also put for loop inside another for loop to get the elements of the $cars array
(we still have to point to the two indices):

18
Example

for ($i = 0; $i < 4; $i++) //Rows


{
echo "<p><b>Car number $i</b></p>";
echo "<ul>";
for ($j = 0; $j < 3; $j++) //Columns
{
echo "<li>".$cars[$i][$j]."</li>";
}
echo "</ul>";
}

The elements in an array can be sorted in alphabetical or numerical order, descending or


ascending.
Sort Functions for Arrays
 sort() - sort arrays in ascending order
 rsort() - sort arrays in descending order
 asort() - sort associative arrays in ascending order, according to the value
 ksort() - sort associative arrays in ascending order, according to the key
 arsort() - sort associative arrays in descending order, according to the value
 krsort() - sort associative arrays in descending order, according to the key
19
Cont’d…
.
Example 1:
<?php
$cars = array("Volvo", "BMW", "Toyota"); sort($cars); // Sorting in ascending order
rsort($cars); // Sorting in descending order
?>
Example 2:
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
asort($age); //Sorting an associative array in ascending order, according to the value:
ksort($age); //Sorting an associative array in ascending order, according to the key
arsort($age); //Sorting an associative array in descending order, according to the value:
krsort($age); //Sorting an associative array in descending order, according to the key
?>

20
2.5. For and While Loops
2.5.1. The for Loop
PHP for loops execute a block of code a specified number of times. 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;
}

Parameters:
➢ init counter: Initialize the loop counter value
➢ test counter: Evaluated for each loop iteration. If true, the loop continues otherwise the loop ends.
➢ increment counter: Increases the loop counter value

Example
<?php
for ($i = 0; $i <= 10; $i++)
{
echo $i;
} ?>

21
2.5.2. The foreach Loop
◼ The foreach loop works only on arrays, and is used to loop through each key or
value pair in an array.
Syntax
foreach ($array as $value)
{
code to be executed;
}

▪ For every iteration the value of the current array element is assigned to $value
and the array pointer is moved by one, until it reaches the last array element.
Example:
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value)
{
echo "$value <br>";
}
?>

22
The 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
$n = 1;
while($n <= 5)
{
echo $n <br>";
$n++;
}
?>

23
2.5.3. The do...while Loop
◼ In a do while loop the condition is tested after executing the statements
within the loop.
◼ This means that the do while loop would execute its statements at least
once, even if the condition is false the first time.
◼ It will then check the condition and repeat the loop while the specified
condition is true.
Syntax
Do
Example 1:
{ <?php
code to be executed;
} while (condition is true);
$n = 1;
code to be executed; do {
} while (condition is true);
echo $n <br>";
$n++;
} while ($n <= 5);
?>

24
2.6. Use Get or Post
▪ The PHP superglobals $_GET and $_POST are used to collect
form-data.
Example:
<html>
<body>
<form action="[Link]" method="post"> Name: <input
type="text" name="name"><br> E-mail: <input type="text"
name="email"><br>
<input type="submit">
</form>
</body>
</html>

▪ When the user fills out the form above and clicks the submit button, the form data
is sent for processing with the HTTP POST method to a PHP file named
"[Link]".

25
Cont’d…
. The [Link] script file:
<html>
<body>
Hello <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>

▪ The same thing can be done by using the Using the GET method:
Example:
<html>
<body>
<form action="[Link]" method="get"> Name: <input type="text"
name="name"><br> E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>

26
cont’d…
The “[Link]" Script file:
<html>
<body>
Hello <?php echo $_GET["name"]; ?><br>
Your email address is: <?php echo $_GET["email"]; ?>
</body>
</html>

Both GET and POST create an array - array (key => value, key2 => value2 ...). This array
holds key/value pairs where:-
 Keys are the names of the form controls.
 Values are the input data from the user.
Both GET and POST are treated as $_GET and $_POST. These are superglobals (they are
always accessible, regardless of scope and can be accessed from any function, class or file
without having to do anything special.)
 $_GET is an array of variables passed to the current script via the URL parameters.
 $_POST is an array of variables passed to the current script via the HTTP POST method.

27
When to use GET?
◼ Information sent from a form with the GET method is visible to everyone (all variable names
and values are displayed in the URL).
◼ GET also has limits on the amount of information to send. (About 2000 characters.)
◼ However, because the variables are displayed in the URL, it is possible to bookmark the
page which can be useful in some cases.
◼ GET may be used for sending non-sensitive data.
◼ GET should NEVER be used for sending passwords or other sensitive information!

When to use POST?


◼ Information sent with the POST method is invisible to others (all names/values are
embedded within the body of the HTTP request)
◼ POST has no limits on the amount of information to send.
◼ POST supports advanced functionality such as support for multi-part binary input while
uploading files to server.
◼ It is not possible to bookmark the page. (Because the variables are not displayed in the URL)
◼ Developers prefer POST for sending form data.

28
2.7. Receive Data from a Form in PHP
2.7.1. Retrieving form data sent via GET
◼ When submitting a form through the GET method, PHP provides a superglobal
variable, called $_GET. PHP uses this $_GET variable to create an associative
array with keys to access all the sent information. The key is created using the
element's name attribute values.
Example:
Form with the GET Method
<form action="[Link]" method="get">
<input type="text" name="firstname" placeholder="First Name" />
<input type="text" name="lastname" placeholder="Last Name" />
<input type="submit" name="send" />
</form>
The $_GET Method Script

if (isset($_GET['send'])) //Check if the form is submitted.


{
//Retrieve the form data by using the element's name attributes value as key
$firstname = $_GET['firstname'];
$lastname = $_GET['lastname'];
//Display the results
echo 'Your name is ' . $lastname . ' ' . $firstname;
exit
29
}
Cont’d….
◼ Firstly, the isset() function checks if the form has been submitted by using the element's
name attribute value "send" as key and pass it to the $_GET[] superglobal variable.

◼ Then the form data, (first name and last name) are retrieved by using the same method,
passing their respective name attribute values into the $_GET['name as key'] array
parameter, and each is assigned to a variable name that was used to display the results.

30
2.7.2. Using the POST
▪ The form POST method sends information via HTTP header. All
name/value pairs sent through this method is invisible to anyone
else since all the information are embedded within the body of the
HTTP request.
◼ When you submit a form to a server through the POST method,
PHP provides a superglobal variable called $_POST. The $_POST
variable is used by PHP to create an associative array with an
access key ($_POST['name as key']). The key is created
automatically by PHP when the form is submitted. PHP uses the
form field element name attribute (name="unique-name- here") to
create the key.

31
2.10. Introduction to Regular Expressions
◼ A regular expression (or regex) is a sequence of characters that
forms a search pattern. It is used to find, match, or manipulate text
in strings.
◼ In PHP, regular expressions are powerful tools for:
❑ Validating user input (e.g., email, phone number, password)
❑ Searching for specific patterns in strings
❑ Extracting information from text
❑ Replacing unwanted characters
◼ For example, you can use a regular expression to check if a user’s
email address is valid before submitting a form.
Regular Expression Syntax
◼ In PHP, regular expressions are usually written between forward
slashes /pattern/, and special characters (called metacharacters) are
used to define the pattern.

32
Cont’d….
◼ If you double click on a HTML file (files with .html or .htm extension), it would open on your web
browser. But same won’t happen if you double clicked on a PHP file (probably it would open in an
editor). The reason is PHP files first need be processed in a web server before sending their output to
the web browser.
Common Metacharacters:
Symbol Meaning Example Matches
. Any single character a.b acb, a1b, a_b
^ Start of a string ^a Strings starting with “a”
$ End of a string t$ Strings ending with “t”
* Zero or more occurrences ab* a, ab, abb, abbb
+ One or more occurrences ab+ ab, abb
? Zero or one occurrence ab? a, ab
[] Character set [abc] a, b, or c
` ` OR operator `cat
() Grouping (abc)+ abc, abcabc, etc.
\d Any digit (0–9) \d+ 123, 45
\w Any word character \w+ hello, user123
\s Whitespace \s space, tab, newline

33
PHP Functions for Regular Expressions
◼ PHP provides Perl-compatible regular expressions (PCRE) with functions that start with
preg_.
Function Description
Checks if a pattern exists in a string
preg_match()
(returns 1 if match found)

preg_match_all() Finds all matches of a pattern in a string

Replaces matched text with something


preg_replace()
else

34
Example 1: Validating an Email Address
. <?php
$email = "user@[Link]";
$pattern = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-z]{2,}$/";
if (preg_match($pattern, $email)) {
echo "Valid email address.";
} else {
echo "Invalid email address.";}?>

Explanation:
✓ ^ and $ ensure the pattern starts and ends correctly.
✓ [a-zA-Z0-9._%+-]+ allows username characters.
✓ @ is required between username and domain.
✓ \. matches the dot in the domain.
✓ [a-z]{2,} allows a minimum of 2 letters for domain extensions (e.g., .com).

35
Example 2: Finding All Numbers in a String
. <?php
$text = "My phone number is 0912345678 and my code is 1234.";
$pattern = "/\d+/"; // \d+ matches one or more digits
if (preg_match_all($pattern, $text, $matches)) {
print_r($matches[0]);
}
?>

Output: Array ( [0] => 0912345678 [1] => 1234 )

Example 3: Replacing Characters


<?php Output:
$text = "Hello#World@2025!";
$pattern = "/[^a-zA-Z0-9 ]/"; // matches any character that is not a HelloWorld2025
letter, digit or space
$cleanText = preg_replace($pattern, "", $text);
echo $cleanText;
?>

36
Practical Uses in Web Applications
▪ Form validation: Check emails, phone numbers,
passwords, etc.
▪ Input sanitization: Remove special characters to
prevent security issues.
▪ Data extraction: Extract numbers, dates, or keywords
from text.
▪ String formatting: Replace or clean unwanted text
patterns.

37
End of Chapter 2!

38

You might also like