Diese Präsentation wurde erfolgreich gemeldet.
Die SlideShare-Präsentation wird heruntergeladen. ×

Working with data.pptx

Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Anzeige
Nächste SlideShare
Introduction to PHP.pptx
Introduction to PHP.pptx
Wird geladen in …3
×

Hier ansehen

1 von 74 Anzeige
Anzeige

Weitere Verwandte Inhalte

Aktuellste (20)

Anzeige

Working with data.pptx

  1. 1. Working with data Unit 3
  2. 2. PHP HTML FORMS • An HTML form is a collection of HTML elements embedded within a page. By adding different types of elements, you can create different form fields, such as text fields, pull-down menus, checkboxes, and so on. • All Web forms start with an opening <form> tag, and end with a closing </form> tag:
  3. 3. Form Attributes • There are two attributes within the opening <form> tag: • action - tells the browser where to send the form data. This should either be an absolute URL or a relative URL. • method - tells the browser how to send the form data. • You can use two methods: GET is for sending small amounts of data and makes it easy for the user to resubmit the form, and POST can send much larger amounts of form data.
  4. 4. PHP GET and POST • To read the data from a form, we can use the following three superglobal variables. • Each of these three superglobal arrays contains the field names from the sent form as array keys, with the field values themselves as array values.
  5. 5. Difference between GET and POST • GET sends its variables in the URL. It easy to see what was sent with GET. And user can change what was sent There is usually a low limit on the number of characters that can be sent in a URL. If we try to send long variables using GET, we may lose some of them. • POST sends its variables behind the scenes and has a much higher limit. It limit is usually several megabytes. • Browsers will not automatically resend post data if your user clicks the Back button, you may get a message like "The data on this page needs to be resent". This does not happen with GET, browsers will just resend data as needed through URL.
  6. 6. Name it as index.php
  7. 7. Form Elements The following table lists HTML elements in forms. If the form is created with the get method. This means that the form field names and values will be sent to the server in the URL. Meanwhile, the empty action attribute tells the browser to send the form back to the same page. Field names and field values as being similar to the keys and values of an associative array.
  8. 8. Form handling with Get() • If we specify the form method to be GET, then the form-data is sent to the server using the HTTP GET method. • Example • <?php // getting the value of name field $name = $_GET["name"]; // getting the value of the email field $email = $_GET["email"]; echo "Hi, ". $name . "<br>"; echo "Your email address: ". $email ."<br>"; ?>
  9. 9. • In case of GET method, form-data is submitted as URL parameters, i.e. all the values entered in the form fields by the user are sent to the action script, appended in the URL. • Example • <html> <body> <form action="form-handler.php" method="GET"> Name: <input type="text" name="name"> <br/> Age: <input type="text" name="age"> <br/> <input type="submit"> </form> </body> </html> • We have two input fields in above form, one is name and the other one is age. When we click on submit, we will be redicrected to the following URL, • form-handler.php?name=Sample&age=5, with the form-data appended to the URL.
  10. 10. Post Method • When we use the POST method, the array of key-value pair(the form-data), coming from the HTML form are sent as part of the HTTP request, hence they are invisible to the user. Also, there is no character limit for the information/data being transmitted. POST method also supports multipart form-data upload which is used for file upload. • Simple HTML FORM code with POST Method • <html> <body> <form action="form-handler.php" method="POST"> Name: <input type="text" name="name"> <br/> Age: <input type="text" name="age"> <br/> <input type="submit"> </form> </body> </html>
  11. 11. REQUEST VARIABLE • PHP $_REQUEST is a PHP super global variable which is used to collect data after submitting an HTML form. • It can catch the data which is sent using both POST & GET methods.
  12. 12. • HTML FORM • <html> <body> <form action="form-handler.php" method="POST"> Name: <input type="text" name="name"> <br/> Email: <input type="text" name="email"> <br/> About Me:<br/> <textarea name="aboutme"></textarea> <br/> Gender: <input type="radio" name="gender" value="female"> Female <input type="radio" name="gender" value="male"> Male <br/> <input type="submit" name="submit" value="Submit"> </form> </body> </html>
  13. 13. • PHP Code to fetch values • <?php // getting the value of name field $name = $_POST["name"]; // getting the value of the email field $email = $_POST["email"]; // getting the value of the aboutme field $aboutme = $_POST["aboutme"]; // getting the value of the radio buttons $gender = $_POST["gender"]; ?>
  14. 14. PHP Form Validation • The validation rules for the form above are as follows:
  15. 15. The HTML CODE • The name, email, and website fields are text input elements, and the comment field is a textarea. The HTML code looks like this: • The gender fields are radio buttons and the HTML code looks like this:
  16. 16. • The Form Element • The HTML code of the form looks like this: • When the form is submitted, the form data is sent with method="post". • What is the $_SERVER["PHP_SELF"] variable? The $_SERVER["PHP_SELF"] is a super global variable that returns the filename of the currently executing script. • So, the $_SERVER["PHP_SELF"] sends the submitted form data to the page itself, instead of jumping to a different page. This way, the user will get error messages on the same page as the form. • What is the htmlspecialchars() function? The htmlspecialchars() function converts special characters to HTML entities. This means that it will replace HTML characters like < and > with &lt; and &gt;. This prevents attackers from exploiting the code by injecting HTML or Javascript code (Cross-site Scripting attacks) in forms.
  17. 17. The $_SERVER["PHP_SELF"] variable can be used by hackers! If PHP_SELF is used in your page then a user can enter a slash (/) and then some Cross Site Scripting (XSS) commands to execute.
  18. 18. Validate Form Data With PHP • The first thing we will do is to pass all variables through PHP's htmlspecialchars() function. • When we use the htmlspecialchars() function; then if a user tries to submit the following in a text field: • <script>location.href('http://www.hacked.com')</script> • - this would not be executed, because it would be saved as HTML escaped code, like this: • &lt;script&gt;location.href('http://www.hacked.com')&lt;/script&gt; • The code is now safe to be displayed on a page or inside an e-mail.
  19. 19. Validation on PHP required fields • From the validation rules table on the previous page, we see that the "Name", "E- mail", and "Gender" fields are required. These fields cannot be empty and must be filled out in the HTML form. • In the following code we have added some new variables: $nameErr, $emailErr, $genderErr, and $websiteErr. These error variables will hold error messages for the required fields. • We have also added an if else statement for each $_POST variable. This checks if the $_POST variable is empty (with the PHP empty() function). If it is empty, an error message is stored in the different error variables, and if it is not empty, it sends the user input data through the test_input() function:
  20. 20. Validate Name , Email,URL • The next step is to validate the input data, that is "Does the Name field contain only letters and whitespace?", and "Does the E-mail field contain a valid e-mail address syntax?", and if filled out, "Does the Website field contain a valid URL?". • PHP VALIDATE NAME • The code below shows a simple way to check if the name field only contains letters, dashes, apostrophes and whitespaces. If the value of the name field is not valid, then store an error message: • The preg_match() function searches a string for pattern, returning true if the pattern exists, and false otherwise.
  21. 21. • PHP - Validate E-mail • The easiest and safest way to check whether an email address is well-formed is to use PHP's filter_var() function. The function is filter_var($email, FILTER_VALIDATE_EMAIL), • The filter_var() function returns true for a valid email address and returns false for an invalid email address. • PHP - Validate URL • The code below shows a way to check if a URL address syntax is valid (this regular expression also allows dashes in the URL). If the URL address syntax is not valid, then store an error message:
  22. 22. PHP - Keep The Values in The Form • To show the values in the input fields after the user hits the submit button, we add a little PHP script inside the value attribute of the following input fields: name, email, and website. In the comment textarea field, we put the script between the <textarea> and </textarea> tags. The little script outputs the value of the $name, $email, $website, and $comment variables. • We also need to show which radio button that was checked. For this, we must manipulate the checked attribute (not the value attribute for radio buttons):
  23. 23. Built in String functions • The PHP string functions are part of the PHP core. No installation is required to use these functions. • Strings in PHP are also a collection of alphanumeric characters, enclosed in single quotes for simple string data and double quotes for complex string data. • <?php $srt1 = "This is a String"; $str2 = 'This is also a String'; ?>
  24. 24. • chr() • The chr() function returns a character from the specified ASCII value. • The ASCII value can be specified in decimal, octal, or hex values. Octal values are defined by a leading 0, while hex values are defined by a leading 0x. • Syntax • chr(ascii) • Parameter Values • Return Value ascii Required. An ASCII value Return Value: Returns the specified character <?php echo chr(52) . "<br>"; // Decimal value echo chr(052) . "<br>"; // Octal value echo chr(0x52) . "<br>"; // Hex value ?>
  25. 25. • ord() • The ord() function returns the ASCII value of the first character of a string. • Syntax • ord(string) • Parameters Values • Return Values string Required. The string to get an ASCII value from Return Value: Returns the ASCII value as an integer <?php echo ord("h")."<br>"; echo ord("hello")."<br>"; ?>
  26. 26. • strtolower() • <?php echo strtolower("Hello WORLD."); ?> • The strtolower() function converts a string to lowercase. • Syntax • Strtolower(string) • Parameter Values • Return Value String Required. Specifies the string to convert Return Value: Returns the the lowercased string
  27. 27. • strtoupper() • <?php echo strtoupper("Hello WORLD!"); ?> • The strtoupper() function converts a string to uppercase. • Syntax • strtoupper(string) • Parameter Values • Return Value string Required. Specifies the string to convert Return Value: Returns the the uppercased string
  28. 28. • strlen() • <?php echo strlen("Hello"); ?> • The strlen() function returns the length of a string. • Syntax • strlen(string) • Parameter Value • Return Value string Required. Specifies the string to check Return Value: Returns the length of a string (in bytes) on success, and 0 if the string is empty
  29. 29. • trim() • The trim() function removes whitespace and other predefined characters from both sides of a string. • Related functions: • ltrim() - Removes whitespace or other predefined characters from the left side of a string • rtrim() - Removes whitespace or other predefined characters from the right side of a string • Syntax • trim(string,charlist) • Parameter Values Parameter Description string Required. Specifies the string to check charlist •Optional. Specifies which characters to remove from the string. If omitted, all of the following characters are removed:"0" - NULL •"t" - tab •"n" - new line •"x0B" - vertical tab •"r" - carriage return •" " - ordinary white space
  30. 30. • <?php $str = "Hello World!"; echo $str . "<br>"; echo trim($str,"Hed!"); ?> • Output • Hello World! llo Worl
  31. 31. • substr() • The substr() function returns a part of a string. • <?php echo substr("Hello world",6); ?> • Output • world • Syntax • str(string,start,length)
  32. 32. • <?php echo substr("Hello world",0,10)."<br>"; echo substr("Hello world",1,8)."<br>"; echo substr("Hello world",0,5)."<br>"; echo substr("Hello world",0,-1)."<br>"; echo substr("Hello world",-10,-2)."<br>"; echo substr("Hello world",0,-6)."<br>"; ?> • Output • Hello worl ello wor Hello Hello worl ello wor Hello
  33. 33. Math Functions • Abs() • The abs() function returns the absolute (positive) value of a number. • Syntax • abs(number); • Parameter Value Parameter Description number Required. Specifies a number. If the number is of type float, the return type is also float, otherwise it is integer
  34. 34. • <?php echo(abs(6.7) . "<br>"); echo(abs(-6.7) . "<br>"); echo(abs(-3) . "<br>"); echo(abs(3)); ?> Output 6.7 6.7 3 3
  35. 35. • Ceil() • The ceil() function rounds a number UP to the nearest integer, if necessary. • Syntax • ceil(number); • Parameter Values number Required. Specifies the value to round up
  36. 36. <?php echo(ceil(0.60) . "<br>"); echo(ceil(0.40) . "<br>"); echo(ceil(5) . "<br>"); echo(ceil(5.1) . "<br>"); echo(ceil(-5.1) . "<br>"); echo(ceil(-5.9)); ?> Output 1 1 5 6 -5 -5
  37. 37. • Floor() • The floor() function rounds a number DOWN to the nearest integer, if necessary, and returns the result. • Syntax • floor(number); • Parameter Values • <?php echo(floor(0.60) . "<br>"); echo(floor(0.40) . "<br>"); echo(floor(5) . "<br>"); echo(floor(5.1) . "<br>"); echo(floor(-5.1) . "<br>"); echo(floor(-5.9)); ?> number Required. Specifies the number to round down Output 0 0 5 5 -6 -6
  38. 38. • Round() • The round() function rounds a floating-point number. • Syntax • round(number,precision,mode); • Parameter Value number Required. Specifies the value to round precision Optional. Specifies the number of decimal digits to round to. Default is 0 mode •Optional. Specifies a constant to specify the rounding mode:PHP_ROUND_HALF_UP - Default. Rounds number up to precision decimal, when it is half way there. Rounds 1.5 to 2 and -1.5 to -2 •PHP_ROUND_HALF_DOWN - Round number down to precision decimal places, when it is half way there. Rounds 1.5 to 1 and -1.5 to -1 •PHP_ROUND_HALF_EVEN - Round number to precision decimal places towards the next even value •PHP_ROUND_HALF_ODD - Round number to precision decimal places towards the next odd value
  39. 39. • <?php echo(round(0.60) . "<br>"); echo(round(0.50) . "<br>"); echo(round(0.49) . "<br>"); echo(round(-4.40) . "<br>"); echo(round(-4.60)); ?> Output 1 1 0 -4 -5
  40. 40. • Fmod() • The fmod() function returns the remainder (modulo) of x/y. • Syntax • fmod(x,y); • Parameter Values x Required. Specifies the dividend y Required. Specifies the divisor
  41. 41. <?php echo(fmod(20, 4) . "<br>"); echo(fmod(20, 3) . "<br>"); echo(fmod(15, 6) . "<br>"); echo(fmod(-10, 3) . "<br>"); echo(fmod(0, 0)); ?> Output 0 2 3 -1 NAN
  42. 42. • Min() • The min() function returns the lowest value in an array, or the lowest value of several specified values. • Syntax • min(array_values); or min(value1,value2,...); • Parameter Values array_values Required. Specifies an array containing the values value1,value2,... Required. Specifies the values to compare (must be at least two values)
  43. 43. • <?php echo(min(2,4,6,8,10) . "<br>"); echo(min(22,14,68,18,15) . "<br>"); echo(min(array(4,6,8,10)) . "<br>"); echo(min(array(44,16,81,12))); ?> Output 2 14 4 12
  44. 44. • Max() • The max() function returns the highest value in an array, or the highest value of several specified values. • Syntax • max(array_values); or max(value1,value2,...); • Parameter Values array_values Required. Specifies an array containing the values value1,value2,... Required. Specifies the values to compare (must be at least two values)
  45. 45. • <?php echo(max(2,4,6,8,10) . "<br>"); echo(max(22,14,68,18,15) . "<br>"); echo(max(array(4,6,8,10)) . "<br>"); echo(max(array(44,16,81,12))); ?> Output 10 68 10 81
  46. 46. • Pow() • The pow() function returns x raised to the power of y. • Syntax • pow(x,y); • Parameter Values • Return Values • <?php echo(pow(2,4) . "<br>"); echo(pow(-2,4) . "<br>"); echo(pow(-2,-4) . "<br>"); ?> Return Value: x raised to the power of y Return Type: Integer if possible, Float otherwise Output 16 16 0.0625 x Required. Specifies the base to use y Required. Specifies the exponent
  47. 47. • Sqrt() • The sqrt() function returns the square root of a number. • Syntax • sqrt(number); • Parameter Values • Return Values number Required. Specifies a number Return Value: The square root of number, or NAN for negative numbers
  48. 48. • Rand() • The rand() function generates a random integer. • If you want a random integer between 10 and 100 (inclusive), use rand (10,100). • Syntax • rand(); or rand(min,max); • Parameter Values • Return Value min Optional. Specifies the lowest number to return. Default is 0 max Optional. Specifies the highest number to return Return Value: A random integer between min (or 0) and max
  49. 49. • <?php echo(rand() . "<br>"); echo(rand() . "<br>"); echo(rand(10,100)); ?> Output 512549293 1132363175 79
  50. 50. Array Functions • The array functions allow you to access and manipulate arrays. • Count() • The count() function returns the number of elements in an array. • Syntax • count(array, mode) • Parameter Values array Required. Specifies the array mode •Optional. Specifies the mode. Possible values:0 - Default. Does not count all elements of multidimensional arrays •1 - Counts the array recursively (counts all the elements of multidimensional arrays)
  51. 51. • <?php $cars=array ( "Volvo"=>array ( "XC60", "XC90" ), "BMW"=>array ( "X3", "X5" ), "Toyota"=>array ( "Highlander" ) ); echo "Normal count: " . count($cars)."<br>"; echo "Recursive count: " . count($cars,1); ?> Normal count: 3 Recursive count: 8
  52. 52. • List() • The list() function is used to assign values to a list of variables in one operation. • list — Assign variables as if they were an array • Syntax • list(var1, var2, ...) • <?php $info = array('coffee', 'brown', 'caffeine'); // Listing all the variables list($drink, $color, $power) = $info; echo "$drink is $color and $power makes it special.n"; // Listing some of them list($drink, , $power) = $info; echo "$drink has $power.n"; // Or let's skip to only the third one list( , , $power) = $info; echo "I need $power!n"; • ?> var1 Required. The first variable to assign a value to var2,... Optional. More variables to assign values to
  53. 53. • In_array() • The in_array() function searches an array for a specific value. • Syntax • in_array(search, array, type) • Parameter Values • Return Value search Required. Specifies the what to search for array Required. Specifies the array to search type Optional. If this parameter is set to TRUE, the in_array() function searches for the search-string and specific type in the array. Return Value: Returns TRUE if the value is found in the array, or FALSE otherwise
  54. 54. • <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); if (in_array("Glenn", $people)) { echo "Match found"; } else { echo "Match not found"; } ?>
  55. 55. • Current() • The current() function returns the value of the current element in an array. • Every array has an internal pointer to its "current" element, which is initialized to the first element inserted into the array. • This function does not move the arrays internal pointer. • Syntax • current(array) • <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); echo current($people) . "<br>"; ?>
  56. 56. • end() - moves the internal pointer to, and outputs, the last element in the array • next() - moves the internal pointer to, and outputs, the next element in the array • prev() - moves the internal pointer to, and outputs, the previous element in the array • reset() - moves the internal pointer to the first element of the array • each() - returns the current element key and value, and moves the internal pointer forward
  57. 57. • <?php $people = array("Peter", "Joe", "Glenn", "Cleveland"); echo current($people) . "<br>"; // The current element is Peter echo next($people) . "<br>"; // The next element of Peter is Joe echo current($people) . "<br>"; // Now the current element is Joe echo prev($people) . "<br>"; // The previous element of Joe is Peter echo end($people) . "<br>"; // The last element is Cleveland echo prev($people) . "<br>"; // The previous element of Cleveland is Glenn echo current($people) . "<br>"; // Now the current element is Glenn echo reset($people) . "<br>"; // Moves the internal pointer to the first element of the array, which is Peter echo next($people) . "<br>"; // The next element of Peter is Joe • ?> Peter Joe Joe Peter Cleveland Glenn Glenn Peter Joe
  58. 58. • sort() • The sort() function sorts an indexed array in ascending order. • Syntax • sort(array, sorttype) • Parameter Values • <?php $cars=array("Volvo","BMW","Toyota"); sort($cars); ?> array Required. Specifies the array to sort sorttype •Optional. Specifies how to compare the array elements/items. Possible values: •1 = SORT_NUMERIC - Compare items numerically •2 = SORT_STRING - Compare items as strings
  59. 59. • rsort() • The rsort() function sorts an indexed array in descending order. • Syntax • rsort(array, sorttype) • <?php $cars=array("Volvo","BMW","Toyota"); rsort($cars); ?>
  60. 60. print_r function • The print_r() function prints the information about a variable in a more human- readable way. • Syntax • print_r(variable, return); • Parameter Values • Return Values variable Required. Specifies the variable to return information about Return Value: If variable is integer, float, or string, the value itself will be printed. If variable is array or object, this function returns keys and elements. If the return parameter is set to TRUE, this function returns a string
  61. 61. • <?php $a = array("red", "green", "blue"); print_r($a); echo "<br>"; $b = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43"); print_r($b); ?> Array ( [0] => red [1] => green [2] => blue ) Array ( [Peter] => 35 [Ben] => 37 [Joe] => 43 )
  62. 62. User Defined Functions • PHP has a large number of built-in functions such as mathematical, string, date, array functions etc. It is also possible to define a function as per specific requirement. Such function is called user defined function. • A function is a reusable block of statements that performs a specific task. This block is defined with function keyword and is given a name that starts with an alphabet or underscore. This function may be called from anywhere within the program any number of times. • //define a function • function myfunction($arg1, $arg2, ... $argn) • { • statement1; • statement2; • .. • .. • return $val; • } • //call function • $ret=myfunction($arg1, $arg2, ... $argn);
  63. 63. • Function may be defined with optional but any number of arguments. However, same number of arguments must be provided while calling. • Function's body can contain any valid PHP code i.e. conditionals, loops etc. (even other functions or classes may be defined inside a function). • After executing statements in the block, program control goes back to the location from which it was invoked irrespective of presence of last statement of function block as return. • An expression in front of return statement returns its value to calling environment.
  64. 64. User Defined Function Example • <?php • //function definition • function sayHello(){ • echo "Hello World!"; • } • //function call • sayHello(); • ?> Hello World
  65. 65. Function with arguments • <?php • function add($arg1, $arg2){ • echo $arg1+$arg2 . "n"; • } • add(10,20); • add("Hello", "World"); • ?> 30 PHP Warning: A non-numeric value encountered in line 3 In second call, two string values are given as function arguments. Since PHP doesn't support + operator for strings, a warning is emitted.
  66. 66. Function Return • <?php • function add($arg1, $arg2){ • return $arg1+$arg2; • } • $val=add(10,20); • echo "addition:". $val. "n"; • $val=add(“20","20"); • echo "addition: $val"; • ?> addition:30 addition:40
  67. 67. Function with default argument value • While defining a function , a default value of argument may be assigned. If value is not assigned to such argument while calling the function, this default will be used for processing inside function. In following example, a function is defined with argument having default value. • <?php • function welcome($user="Guest"){ • echo "Hello $usern"; • } • //overrides default • welcome("admin"); • //uses default • welcome(); • ?> Hello admin Hello Guest
  68. 68. Function with variable number of arguments • It is possible to define a function with ability to receive variable number of arguments. The name of formal argument in function definition is prefixed by ... token. • Following example has add() function that adds a list of numbers given as argument. • <?php • function add(...$numbers){ • $ttl=0; • foreach ($numbers as $num){ • $ttl=$ttl+$num; • } • return $ttl; • } • $total=add(10,15,20); • echo "total= $totaln"; • echo "total=". add(1,2,3,4,5). "n"; • ?> Total=45 Total=15
  69. 69. • It is also possible to obtain a list of arguments passed to a function with the help of func_get_args() function. We can run a PHP loop to traverse each value in the list of arguments passed. In that case the function definition doesn't have a formal argument. • <?php • function add(){ • $numbers=func_get_args(); • $ttl=0; • foreach ($numbers as $num){ • $ttl=$ttl+$num; • } • return $ttl; • } • $total=add(10,15,20); • echo "total= $totaln"; • echo "total=". add(1,2,3,4,5). "n"; • ?> Total=45 Total=15
  70. 70. Function within another function • A function may be defined inside another function's body block. However, inner function can not be called before outer function has been invoked. • <?php • function hello(){ • echo "Hellon"; • function welcome(){ • echo "Welcome to TutorialsPointn"; • } • } • welcome(); • hello(); • welcome(); • ?>
  71. 71. 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: • <?php • function add_five(&$value) { • $value += 5; • } • $num = 2; • add_five($num); • echo $num; • ?>

Hinweis der Redaktion

  • Absolute address : full website address like http://site.com/images/img.php
    Relative address : partial address like images/img.php

×