CHAPTER 7 Introduction to PHP5 Part II อ.ยืนยง กันทะเนตร คณะเทคโนโลยีสารสนเทศและการสื่อสาร มหาวิทยาลัยพะเยา 1 Content • • • • • • • • PHP 5 if...else...elseif Statements PHP 5 switch Statement PHP 5 while Loops PHP 5 for Loops PHP 5 Functions PHP 5 Arrays PHP 5 Sorting Arrays PHP 5 Global Variables - Superglobals 2 Content • • • • • PHP 5 Form Handling PHP 5 Form Validation PHP 5 Forms - Required Fields PHP 5 Forms - Validate E-mail and URL PHP 5 Complete Form Example 3 PHP 5 if...else...elseif Statements PHP - The if Statement PHP - The if...else Statement <?php $t = 15; <?php $t = 15; if ($t < 20) { echo "Have a good day!"; } ?> if ($t < 20) { echo "Have a good day!"; }else{ echo "Have a good night!"; } ?> 4 PHP 5 if...else...elseif Statements (cont.) PHP - The if...elseif....else Statement <?php $t = 15; if ($t < 10) { echo "Have a good morning!"; } elseif ($t < 20) { echo "Have a good day!"; } else { echo "Have a good night!"; } ?> 5 PHP 5 switch Statement The PHP switch Statement <?php $favcolor = "red"; switch ($favcolor) { case "red": echo "Your favorite color is red!"; break; case "blue": echo "Your favorite color is blue!"; break; default: echo "Your favorite color is neither red, blue, or green!"; } ?> 6 PHP 5 while Loops The PHP while Loop The PHP do...while Loop <?php $x = 1; <?php $x = 1; while($x <= 5) { echo "The number is: $x <br>"; $x++; } ?> do { echo "The number is: $x <br>"; $x++; } while ($x <= 5); ?> 7 PHP 5 for Loops The PHP for Loop <?php for ($x = 0; $x <= 10; $x++) { echo "The number is: $x <br>"; } ?> The PHP foreach Loop <?php $colors = array("red", "green", "blue", "yellow"); foreach ($colors as $value) { echo "$value <br>"; } ?> 8 PHP 5 Functions Create a User Defined Function in PHP Syntax function functionName() { code to be executed; } Example <?php function writeMsg() { echo "Hello world!"; } writeMsg(); // call the function ?> 9 PHP 5 Functions (cont.) PHP Function Arguments Example <?php function familyName($fname) { echo "$fname br>"; } familyName("Jani"); familyName("Hege"); //output Jani Hege ?> 10 PHP 5 Functions (cont.) PHP Default Argument Value 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); ?> 11 PHP 5 Functions (cont.) PHP Functions - Returning values Example <?php function sum($x, $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); ?> 12 PHP 5 Arrays What is an Array? • An array is a special variable, which can hold more than one value at a time. $cars1 = "Volvo"; $cars2 = "BMW"; $cars3 = "Toyota"; However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300? 13 PHP 5 Arrays (cont.) Create an Array in PHP array(); Example $cars = array("Volvo", "BMW", "Toyota"); or the index can be assigned manually: $cars[0] = "Volvo"; $cars[1] = "BMW"; $cars[2] = "Toyota"; 14 PHP 5 Arrays (cont.) Get The Length of an Array - The count() Function count(); Example <?php $cars = array("Volvo", "BMW", "Toyota"); echo count($cars); ?> //output 3 15 PHP 5 Arrays (cont.) Loop Through an Indexed Array Example <?php $cars = array("Volvo", "BMW", "Toyota"); $arrlength = count($cars); for($x = 0; $x < $arrlength; $x++) { echo $cars[$x]; echo "<br>"; } ?> 16 PHP 5 Arrays (cont.) PHP Associative Arrays Example <?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); echo "Peter is " . $age['Peter'] . " years old."; ?> Loop Through an Associative Array Example <?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); foreach($age as $x => $x_value) { echo "Key=" . $x . ", Value=" . $x_value; echo "<br>"; } ?> 17 PHP 5 Sorting Arrays PHP - Sort Functions For Arrays In this chapter, we will go through the following PHP array sort functions: • 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 18 PHP 5 Sorting Arrays (cont.) Sort Array in Ascending Order - sort() <?php $cars = array("Volvo", "BMW", "Toyota"); sort($cars); ?> Sort Array in Descending Order - rsort() <?php $cars = array("Volvo", "BMW", "Toyota"); rsort($cars); ?> 19 PHP 5 Sorting Arrays (cont.) Sort Array (Ascending Order), According to Value - asort() <?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); asort($age); ?> Sort Array (Ascending Order), According to Key - ksort() <?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); ksort($age); ?> 20 PHP 5 Sorting Arrays (cont.) Sort Array (Descending Order), According to Value - arsort() <?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); arsort($age); ?> Sort Array (Descending Order), According to Key - krsort() <?php $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); krsort($age); ?> 21 PHP 5 Global Variables - Superglobals PHP Global Variables - Superglobals Several predefined variables in PHP are "superglobals", which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special. The PHP superglobal variables are: • $GLOBALS • $_SERVER • $_REQUEST • $_POST • $_GET • $_FILES • $_ENV • $_COOKIE • $_SESSION 22 PHP 5 Global Variables - Superglobals (cont.) PHP $_POST <html> <body> <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> Name: <input type="text" name="fname"> <input type="submit"> </form> <?php if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = $_POST['fname']; if (empty($name)) { echo "Name is empty"; } else { echo $name; } }?> </body> </html> 23 PHP 5 Global Variables - Superglobals (cont.) PHP $_GET //test_get.html <html> <body> <a href="test_get.php?subject=PHP&web=W3schools.com">Test $GET</a> </body> </html> PHP $_GET //test_get.php <html> <body> <?php echo "Study " . $_GET['subject'] . " at " . $_GET['web']; ?> </body> </html> 24 PHP 5 Form Handling The PHP superglobals $_GET and $_POST are used to collect form-data. PHP - A Simple HTML Form $_GET PHP - A Simple HTML Form <html> <body> <html> <body> <form action="welcome_get.php" method=“get"> Name: <input type="text" name="name"><br> E-mail: <input type="text" name="email"><br> <input type="submit"> </form> Welcome <?php echo $_GET["name"]; ?><br> Your email address is: <?php echo $_GET["email"]; ?> </body> </html> </body> </html> // output Welcome name Your email address is name@example.com 25 PHP 5 Form Handling PHP - A Simple HTML Form $_POST PHP - A Simple HTML Form <html> <body> <html> <body> <form action="welcome_post.php" method=“post"> Name: <input type="text" name="name"><br> E-mail: <input type="text" name="email"><br> <input type="submit"> </form> Welcome <?php echo $_POST["name"]; ?><br> Your email address is: <?php echo $_POST["email"]; ?> </body> </html> </body> </html> // output Welcome name Your email address is name@example.com 26 PHP 5 Form Validation 27 PHP 5 Form Validation (cont.) // formValidate.php <?php $name = $email = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = test_input($_POST["name"]); $email = test_input($_POST["email"]); $website = test_input($_POST["website"]); $comment = test_input($_POST["comment"]); $gender = test_input($_POST["gender"]); } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> 28 PHP 5 Form Validation (cont.) // formValidate.php <h2>PHP Form Validation Example</h2> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> Name: <input type="text" name="name"> <br><br> E-mail: <input type="text" name="email"> <br><br> Website: <input type="text" name="website"> <br><br> Comment: <textarea name="comment" rows="5" cols="40"></textarea> <br><br> Gender: <input type="radio" name="gender" value="female">Female <input type="radio" name="gender" value="male">Male <br><br> <input type="submit" name="submit" value="Submit"> </form> 29 PHP 5 Form Validation (cont.) // formValidate.php <?php echo "<h2>Your Input:</h2>"; echo $name; echo "<br>"; echo $email; echo "<br>"; echo $website; echo "<br>"; echo $comment; echo "<br>"; echo $gender; ?> 30 PHP 5 Forms - Required Fields // formValidate.php <?php $nameErr = $emailErr = $genderErr = $websiteErr = ""; $name = $email = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "Name is required"; } else { $name = test_input($_POST["name"]); } if (empty($_POST["email"])) { $emailErr = "Email is required"; } else { $email = test_input($_POST["email"]); } 31 PHP 5 Forms - Required Fields (cont.) // formValidate.php if (empty($_POST["website"])) { $website = ""; } else { $website = test_input($_POST["website"]); } if (empty($_POST["comment"])) { $comment = ""; } else { $comment = test_input($_POST["comment"]); } if (empty($_POST["gender"])) { $genderErr = "Gender is required"; } else { $gender = test_input($_POST["gender"]); } } ?> 32 PHP 5 Forms - Required Fields (cont.) // formValidate.php <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> Name: <input type="text" name="name"> <span class="error">* <?php echo $nameErr;?></span> <br><br> E-mail: <input type="text" name="email"> <span class="error">* <?php echo $emailErr;?></span> <br><br> Website: <input type="text" name="website"> <span class="error"><?php echo $websiteErr;?></span> <br><br> <label>Comment: <textarea name="comment" rows="5" cols="40"></textarea> <br><br> Gender: <input type="radio" name="gender" value="female">Female <input type="radio" name="gender" value="male">Male <span class="error">* <?php echo $genderErr;?></span> <br><br> <input type="submit" name="submit" value="Submit"> </form> 33 PHP 5 Forms - Validate E-mail and URL // formValidate.php PHP - Validate Name $name = test_input($_POST["name"]); if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $nameErr = "Only letters and white space allowed"; } // formValidate.php PHP - Validate E-mail $email = test_input($_POST["email"]); if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid email format"; } 34 PHP 5 Forms - Validate E-mail and URL (cont.) // formValidate.php PHP - Validate URL $website = test_input($_POST["website"]); if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z09+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) { $websiteErr = "Invalid URL"; } 35 PHP 5 Complete Form Example // formValidate.php PHP - Keep The Values in The Form Name: <input type="text" name="name" value="<?php echo $name;?>"> E-mail: <input type="text" name="email" value="<?php echo $email;?>"> Website: <input type="text" name="website" value="<?php echo $website;?>"> Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea> Gender: <input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female <input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male 36 THE END 37