0% found this document useful (0 votes)
6 views

PHP Ch2

IP mwu lecture notes

Uploaded by

amanuel29831
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

PHP Ch2

IP mwu lecture notes

Uploaded by

amanuel29831
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Madda Walabu university

College of Computing
Department of Information
Technology
Internet Programming II

Unit 2: HTML Forms and Server-Side Scripting


2 Contents
Use Conditionals and Operators
Validate Form
Send Values to a Script Manually
Work with Forms and arrays of data
Use For and While Loops
Create a Simple Form using PHP
Use Get or Post
Receive Data from a Form in PHP
Introduction to regular expressions
3 PHP Operators

 PHP divides the operators in the following groups:

 Arithmetic operators

 Assignment operators

 Comparison operators

 Increment/Decrement operators

 Logical operators

 String operators

 Array operators

 Conditional assignment operators


4 PHP Operators Cont’d…

PHP Arithmetic Operators


 The PHP arithmetic operators are used with numeric
values to perform common arithmetical operations, such
as addition, subtraction, multiplication etc.
5 PHP Operators Cont’d…

Assignment Operators
 The assignment operators are used to assign
value to different variables. The basic
assignment operator is "=".
6 PHP Operators Cont’d…

Bitwise Operators
 The bitwise operators are used to perform bit-
level operations on operands. These operators
allow the evaluation and manipulation of
specific bits within the integer.
7 PHP Operators Cont’d…

Comparison Operators
 Comparison operators allow comparing two
values, such as number or string.
8 PHP Operators Cont’d…

Incrementing/Decrementing Operators
 The increment and decrement operators are
used to increase and decrease the value of a
variable.
9 PHP Operators Cont’d…

Logical Operators
 The logical operators are used to perform bit-
level operations on operands.
10 PHP Operators Cont’d…

Array Operators
 The array operators are used in case of array.
11 PHP Conditional Statements

 Conditional Statements are used to perform actions


based on different conditions.
 Sometimes when we write a program, we want to
perform some different actions for different actions.
We can solve this by using conditional statements.
 In PHP we have these conditional statements:

1.if Statement.

2.if-else Statement

3.If-elseif-else Statement

4.Switch statement
12 Conditional Statements Cont’d…

if Statement
 This statement executes the block of code
inside the if statement if the expression is
evaluated as True.
 Syntax

if (condition) {
<?php
// code to be executed if condition is true;
$x = 22;
if ($x < 23) {
} echo “$x is less than 23";
}
 Example: ?>
13 Conditional Statements Cont’d…

PHP If-else Statement


 PHP if-else statement is executed whether
condition isif(condition){
true or false.
//code to be executed if true
 Syntax }else{
//code to be executed if false
}

 Example: <?php
$num=12;
if($num%2==0){
echo "$num is even number";
}else{
echo "$num is odd number";
}
?>
14 Conditional Statements Cont’d…

PHP If-else-if Statement


 The PHP if-else-if is a special statement used to
combine multiple if-else statements.
 Syntax: if (condition1){
//
code to be executed if condition1 is true

} elseif (condition2){
//
code to be executed if condition2 is true

} elseif (condition3){
//
code to be executed if condition3 is true
15 Conditional Statements Cont’d…

 If-else-if Example:
<?php
$num = 4;
if($num > 0){
echo "num is positive";
}
else if($num < 0){
echo "num is negative";
}
else
{
echo "num is zero";
}
?>
16 Conditional Statements Cont’d…

Switch Statement
 This statement allows us to execute different
<?php
blocks of code based on
$i = different conditions.
"2";
switch ($i) {
case 0:
echo "i equals 0";
break;
 Example: case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
default:
echo "i is not equal to 0, 1 or 2";
}
?>
17 PHP Loops

In PHP, there are the following looping


statements:
 while - loops through a block of code as long
as the specified condition is true
 do...while - loops through a block of code
once, and then repeats the loop as long as the
specified condition is true
 for - loops through a block of code a specified
number of times
 foreach - loops through a block of code for
18 PHP Loops Cont’d…

While loop
 The while loop executes a block of code as long as the
specified condition is true.
 Syntax
Example
while (condition is true) { <?php
code to be executed; $x=1;
while($x<=5) {
} echo "The number
is: $x <br>";
$x++;
}
?>
19 PHP Loops Cont’d…

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);
 The example below first sets a variable $x to 1 ($x=1;).
Then, the do while loop will write some output, and then
increment the variable $x with 1. Then the condition is
checked (is $x less than, or equal to 5?), and the loop will
20 PHP Loops Cont’d…

do…while loop Example

<?php
$x=1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x<=5);
?>
21 PHP Loops Cont’d…

PHP for Loops


 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 it evaluates to


TRUE, the loop continues. If it evaluates to FALSE, the loop ends.
 increament counter: Increases the loop counter value
22 PHP Loops Cont’d…

For loop Example

 The example below displays the numbers from

0 to 10:

<?php

for($x=0;$x<=10;$x++){

echo "$x <br>";

?>
23 PHP Loops Cont’d…

The PHP for each Loop


 The for each loop works only on arrays, and is
used to loop through each key/value pair in an
array.
 Syntax

For each ($array as $value) {


code to be executed;
}
 For every loop iteration, the value of the
current array element is assigned to $value
24 PHP Loops Cont’d…

Foreach loop Example

<?php

$colors=array("Red","Yellow","Blue");

foreach($colors as $value){

echo $value;

echo "<br>";

?>
25 PHP Arrays

 Arrays are used to store multiple values in a


single variable.
 An array is a special variable that can hold many
values under a single name, and you can access
the values by referring to an index number or
name.
 Each element in the array has its own ID so that
it can be easily accessed.
26 PHP Arrays Cont’d…

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
27 PHP Arrays Cont’d…

Indexed arrays
 Indexed Arrays We can create these kind of
arrays in two ways shown below:

Example1

<?php

$fruits = array("Banana","Orange","Papaya");

echo $fruits[0].",".$fruits[1].",".$fruits[2];

?>
28 PHP Arrays Cont’d…

Indexed arrays

Example 2

<?php

$names[0] = "Html";

$names[1] = "JavaScript";

$names[2] = "VBScript";

echo $names[0] . "," . $names[1] . " and " .


$names[2]. " are Client Side Scripting Languages";

?> Output
Html,JavaScript and VBScript are Client Side
Scripting Languages
29 PHP Arrays Cont’d…

PHP Associative Arrays


 Associative arrays are arrays that use named
keys that you assign to them.

Example 1
 In this example we use an array to assign ages
to the different persons:

$ages = array("Peter"=>32, "Quagmire"=>30,


"Joe"=>34);
30 PHP Arrays Cont’d…

 PHP Associative Arrays

Example 1

<?php

$ages['Peter'] = "32";

$ages['Quagmire'] = "30";

$ages['Joe'] = "34";

echo "Peter is " . $ages['Peter'] . " years


old.";

?>
31 PHP Arrays Cont’d…

PHP Associative Arrays

Example2

<?php

$age = array("Fabio"=>"20",
"Klevi"=>"16", "John"=>"43");

echo "Fabio is " . $age["Fabio"] . " years


old.";

?>
32 PHP Arrays Cont’d…

PHP 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.
33 PHP Arrays Cont’d…
Example:

<?php

$cars = array (

array("Volvo",22,18),

array("BMW",15,13),

array("Saab",5,2),

array("Land Rover",17,15));

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>";


?>
34 PHP Arrays Cont’d…

The foreach Statement


 The foreach statement is used to loop through
arrays.
 For every loop, the value of the current array
element is assigned to $value (and the array
pointer
Syntaxis moved by one) - so on the next loop,
Example
<?php
foreach
you'll (arrayat
be looking asthe next element. "two",
$arr=array("one",
value) "three");
foreach ($arr as $value)
{ {
code to be echo $value . ",";
executed; }
?>
35 PHP Function

 A function is a block of code that can be executed whenever


we need it.
 Creating PHP functions:

 All functions start with the word "function()"

 Name the function - It should be possible to understand


what the function does by its name. The name can start
with a letter or underscore (not a number)
 Add a "{" - The function code starts after the opening
curly brace • Insert the function code
 Add a "}" - The function is finished by a closing curly
brace
36 PHP Function Cont’d…

Example1

<html>
<body>
<?php
function writeMessage()
{
echo "This is PHP Function";
}
writeMessage();
?>
</body>
</html>
37 PHP Function Cont’d…

Adding parameters
 Our first function (writeMessage()) is a very
simple function. It only writes a static string. To
add more functionality to a function, we can
Example
add parameters. A parameter is just like a
<?php
variable.
function ServerSideScripts($Sname) {
echo $Sname. " " ."is Server Side Scripting
Language"."<br>";
}
ServerSideScripts("PHP");
ServerSideScripts("Python");
ServerSideScripts("ASP");
?>
38 PHP Function Cont’d…

PHP Functions - Return values


 Functions can also be used to return values.

Example
<?php
function add($x,$y)
{
$total = $x + $y;
return $total;
}
echo "Total = " . add(1,16);
?>
39 PHP Forms and User Input

 Forms are the principal means by which substantial amounts


of information can pass from the user to the server.
 Dynamic web sites collect information in html form and
process it on server side.
 The PHP script receives the data from the form and uses it to
perform an action, such as updating the contents of a
database, sending an e-mail, testing the data format, and so
on.
 As PHP code is activated when a page is requested from the
server, user interaction can occur only in a back-and-forth
fashion: the user sends requests to the server, and the
server replies with dynamically generated page.
40 PHP Forms and User Input Cont’d…

 The PHP $_GET and $_POST variables are used to


retrieve information from forms, like user input.
 The example below displays a simple HTML form with
two input fields and a submit button:
Example your own PHP Server

<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
41 PHP Forms Cont’d…

Send Values to a Script Manually


 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.
 To display the submitted data you could simply
<html>
<body>
echo all<?php
Welcome the variables. The "welcome.php"
echo $_POST["name"]; ?><br> looks
Your email address is: <?php echo $_POST["email"];
like
?> this:
</body>
</html>
42 Form Validation

 User input should be validated whenever


possible.
 Client side validation is faster, and will reduce
server load.
 However, any site that gets enough traffic to
worry about server resources, may also need to
worry about site security.
 You should always use server side validation if
the form accesses a database. A good way to
validate a form on the server is to post the form
43 Form validation Cont’d…

Client vs. server-side validation


 Validation can be performed:

 Client-side (before the form is submitted)

 can lead to a better user experience, but not secure


(why not?)
 Server-side (in PHP code, after the form is submitted)

 needed for truly secure validation, but slower

 Both

 best mix of convenience and security, but requires


most effort to program
44 Form Validation Cont’d…

The Following examples are to check that the


field is not empty, takes only alphabet and only
Example 1 Example 2
number
if (emptyrespectively.
($_POST["nam $name = $_POST ["Name"];
e"])) { if (!preg_match ("/^[a-zA-
$errMsg = "Error! You d z]*$/", $name) ) {
idn't enter the Name."; $ErrMsg = "Only alphabets and w
hitespace are allowed.";
echo $errMsg;
echo $ErrMsg;
} else { } else {
$name = $_POST["nam echo $name; }
e"]; Example
} 3
$mobileno = $_POST ["Mobile_no"];
if (!preg_match ("/^[0-
9]*$/", $mobileno) ){
$ErrMsg = "Only numeric value is a
llowed.";
echo $ErrMsg;
} else {
45 Form Validation Cont’d…

 Other Validations.
The below code validates the The below code validates the
email address: of the input:
$email = $_POST ["Email"]; $mobileno = strlen ($_POST ["Mo
$pattern = "^[_a-z0-9-]+(\.[_a- bile"]);
z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-] $length = strlen ($mobileno);
+)*(\.[a-z]{2,3})$^";
if (! if ( $length < 10 && $length > 1
preg_match ($pattern, $email) ) 0) {
{ $ErrMsg = "Mobile must have
$ErrMsg = "Email is not valid." 10 digits.";
; echo $ErrMsg;
echo $ErrMsg; } else {
} else { echo "Your Mobile number is: "
echo "Your valid email address .$mobileno;
is: " .$email; }
}
46 PHP Form Validation Cont’d…

Button Click Validate


 The below code validates that the user click on
submit button and send the form data to the
server one of the following method - get or
if (isset ($_POST['submit']) {
post. echo "Submit button is clicked.";
if ($_SERVER["REQUEST_METHOD"
] == "POST") {
echo "Data is sent using POST
method ";
}
} else {
echo "Data is not submitted";
}
47 PHP Form Validation Cont’d…

 Example
<!DOCTYPE HTML> test_input($_POST["name"]);
<html> }
<head> if (empty($_POST["email"])) {
<style> $emailErr = "Email is required";
.error {color: #FF0000;} } else {
</style> $email =
</head> test_input($_POST["email"]);
<body> }
<?php }
// define variables and set to function test_input($data) {
empty values $data = trim($data);
$nameErr = $emailErr = ""; $data = stripslashes($data);
$name = $email = ""; $data = htmlspecialchars($data);
if ($_SERVER["REQUEST_METHOD"] return $data;
== "POST") { }
if (empty($_POST["name"])) { ?>
$nameErr = "Name is required";
} else {
$name =
48 PHP Form Validation Cont’d…

Example Cont’d…
<h2>PHP Form Validation
Example</h2> <?php
<p><span class="error">* if(isset($_POST['submit'])) {
required field</span></p> if($nameErr == "" && $emailErr
<form method="post" action="<? == "") {
php echo echo "<h3 color = #FF0001>
htmlspecialchars($_SERVER["PHP_ <b>You have sucessfully
SELF"]);?>"> registered.</b> </h3>";
Name: <input type="text" echo "<h2>Your
name="name"> Input:</h2>";
<span class="error">* <?php echo $name;
echo $nameErr;?></span> echo "<br>";
<br><br> echo $email;
E-mail: <input type="text" }
name="email"> else {
<span class="error">* <?php echo "<h3> <b>You didn't
echo $emailErr;?></span> filled up the form correctly.</b>
<br><br> </h3>";
49 Use Get or Post

Get Method
 The get method is used mainly in conjunction with database
searches and has the advantage that you can bookmark a
search result because all the data is in the URL.
 Data sent by the get method are stored in the $_GET array.

 If the form is submitted by get method ,the data is stored in


$_GET[‘inputbox name’].

 Get request is the default form request.

Note: The HTTP GET method is not suitable on large variable


values; the value cannot exceed 100 characters.
50 Use Get or Post Cont’d…

 Post method

The $_POST array contains data sent using the post method.

The $_POST array contains a name/value pair for the submit


button.

If the form is submitted by post method ,the data is stored in


$_POST[‘inputname’].

You can test whether the form has been submitted by creating
a conditional statement and passing $_POST['send'] to isset().

If $_POST['send'] has been defined (set), the form has been


submitted.
// check if the form has been submitted

if (isset($_POST['send'])) //send is the value of name attribute


51 Use Get or Post Cont’d…

 Variables sent with HTTP POST are not shown in


the URL
 Variables have no length limit

 However, because the variables are not


displayed in the URL, it is not possible to
bookmark the page.

PHP Regular Expressions(Assignment)


52 Q and A

Thank you

You might also like