1 / 41

PHP

PHP. Chapter 6 Processing forms. Problems with submitting data. <form action=" print_params.php "> <div> <label><input type="radio" name="cc" /> Visa</label> <label><input type="radio" name="cc" /> MasterCard</label> < br /> Favorite Star Trek captain:

halil
Download Presentation

PHP

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. PHP Chapter 6 Processing forms

  2. Problems with submitting data <form action="print_params.php"> <div> <label><input type="radio" name="cc" /> Visa</label> <label><input type="radio" name="cc" /> MasterCard</label> <br /> Favorite Star Trek captain: <select name="startrek"> <option>James T. Kirk</option> <option>Jean-Luc Picard</option> </select> <br /> <input type="submit" /> </div> </form> print_params.php <?php foreach ($_REQUEST as $param => $value) : ?> <p><?= $param ?> : <?= $value ?></p> <?php endforeach; ?> <pre> <?phpprint_r($_REQUEST); ?> </pre> • Submit to our handy print_params.php tester • the form may look correct, but when you submit it... • [cc] => on, [startrek] => Jean-Luc Picard

  3. The value attribute <form action="print_params.php"> <div> <label><input type="radio" name="cc" value="visa"/> Visa</label> <label> <input type="radio" name="cc" value="mastercard“ /> MasterCard </label> <br /> Favorite Star Trek captain: <select name="startrek"> <option value="kirk">James T. Kirk</option> <option value="picard">Jean-Luc Picard</option> </select> <br /> <input type="submit" /> </div> </form> • valueattribute sets what will be submitted if a control is selected • [cc] => visa, [startrek] => picard

  4. URL-encoding • certain characters are not allowed in URL query parameters: • examples: " ", "/", "=", "&" • when passing a parameter, it is URL-encoded (reference table) • "Marty's cool!?" → "Marty%27s+cool%3F%21” • you don't usually need to worry about this: • the browserautomatically encodes parameters before sending them • the PHP $_REQUEST array automatically decodesthem

  5. Submitting data to a web server • Though browsers mostly retrieve data, sometimes you want to submit data to a server • the data is sent in HTTP requests to the server • with HTML forms • with Ajax (seen later) • the data is placed into the request as parameters

  6. HTTP GET vs. POST requests • GET : asks a server for a page or data • if the request has parameters, they are sent in the URL as a query string • POST : submits data to a web server and retrieves the server's response • if the request has parameters, they are embedded in the request's HTTP packet, not the URL • For submitting data, a POST request is more appropriate than a GET • GETrequests embed their parameters in their URLs • URLs are limited in length (~ 1024 characters) • URLs cannot contain special characters without encoding • private data in a URL can be seen or modified by users

  7. Form POST example <form action="http://foo.com/app.php" method="post"> <div> Name: <input type="text" name="name" /> <br /> Food: <input type="text" name="meal" /> <br /> <label>Meat? <input type="checkbox" name="meat" /></label> <br /> <input type="submit" /> <div> </form> • Using method = "post"appends form data to the browser request that contains the protocol and the requested resource’s URL. • Scripts located on the web server’s machine can access the form data sent as part of the request.

  8. GET or POST? if ($_SERVER["REQUEST_METHOD"] == "GET") { # process a GET request ... } elseif ($_SERVER["REQUEST_METHOD"] == "POST") { # process a POST request ... } • some PHP pages process both GET and POST requests • to find out which kind of request we are currently processing, look at the global $_SERVER array's "REQUEST_METHOD" element

  9. The htmlspecialchars function $text = "<p>hi 2 u & me</p>"; $text = htmlspecialchars($text); # "&lt;p&gt;hi 2 u &amp; me&lt;/p&gt;" • text from files / user input / query paramsmight contain <, >, &, etc. • we could manually write code to strip out these characters • better idea: allow them, but escape them

  10. "Superglobal" arrays • Superglobalarrays are associative arrays predefined by PHP • hold variables acquired from user input, the environment or the web server • are accessible in any variable scope. • The array $_GETretrieves information sent to the server by HTTP get requests. • The array $_POSTretrieves information sent to the server by post requests. • Function extractcreates a variable/value pair corresponding to each key/value pair in the associative array passed as an argument.

  11. Uploading files <form action= "print_params.php" method="post" enctype="multipart/form-data"> Upload an image as your avatar: <input type="file" name="avatar" /> <input type="submit" /> </form> • add a file upload to your form as an input tag with type of file • must also set the enctypeattribute of the form

  12. Processing an uploaded file in PHP • uploaded files are placed into global array $_FILES, not $_REQUEST • each element of $_FILES is itself an associative array, containing: • name      : the local filename that the user uploaded • type      : the MIME type of data that was uploaded, such as image/jpeg • size      : file's size in bytes • tmp_name  : a filename where PHP has temporarily saved the uploaded file • to permanently store the file, move it from this location into some other file example: if you upload borat.jpg as a parameter named avatar, $_FILES["avatar"]["name"] will be "borat.jpg" $_FILES["avatar"]["type"] will be "image/jpeg" $_FILES["avatar"]["tmp_name"] will be something like "/var/tmp/phpZtR4TI"

  13. Uploading files: example <form action="upload.php" enctype="multipart/form-data" method="post"> <fieldset> <label>Name: <input type="text" name="name" /></label> <br /> <label>Meal: <input type="text" name="meal" /></label> <br /> Your picture: <input type="file" name="pic" size="60" /> <br /> <input type="submit" value="Submit Preferences" /> </fieldset> </form>

  14. Processing an uploaded file in PHP upload.php <pre> <?php print "\ncontents of FILES array:\n"; print_r($_FILES); ?> </pre> contents of FILES array: Array ( [pic] => Array ( [name] => nouradam.jpg [type] => image/jpeg [tmp_name] => C:\wamp\tmp\phpC7A6.tmp [error] => 0 [size] => 1222397 ) )

  15. Processing uploaded file, example • functions for dealing with uploaded files: • is_uploaded_file(filename) returns TRUE if the given filename was uploaded by the user • move_uploaded_file(from, to) moves from a temporary file location to a more permanent file • proper idiom: check is_uploaded_file, then do move_uploaded_file $username = $_REQUEST["username"]; if (is_uploaded_file($_FILES["avatar"]["tmp_name"])) { move_uploaded_file($_FILES["avatar"]["tmp_name"], "$username/avatar.jpg"); print "Saved uploaded file as $username/avatar.jpg\n"; } else { print "Error: required file not uploaded"; }

  16. (review) Printing an associative array $blackbook = array("marty" => "206-685-2181", "stuart" => "206-685-9138", "jenny" => "206-867-5309"); print_r($blackbook); Array ( [jenny] => 206-867-5309 [stuart] => 206-685-9138 [marty] => 206-685-2181 ) • print_r function displays all keys/values in the array • var_dump function is much like print_r but prints more info • unlike print, these functions require parentheses

  17. Associative array functions if (isset($blackbook["marty"])) { print "Marty's phone number is {$blackbook['marty']}\n"; } else { print "No phone number found for Marty Stepp.\n"; }

  18. (review)A form that submits to itself <form action="" method="post"> ... </form> • a form can submit its data back to itself by setting the action to the page's own URL (or blank) • benefits • fewer pages/files (don't need a separate file for the code to process the form data) • can more easily re-display the form if there are any errors

  19. What is form validation? • validation: ensuring that form's values are correct • some types of validation: • preventing blank values (email address) • ensuring the type of values • integer, real number, currency, phone number, Social Security number, postal address, email address, date, credit card number, ... • ensuring the format and range of values (ZIP code must be a 5-digit integer) • ensuring that values fit together (user types email twice, and the two must match)

  20. A real form that uses validation

  21. 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 • 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

  22. Basic server-side validation code <form action="http://foo.com/foo.php" method="get"> <div> City: <input name="city" /> <br /> State: <input name="state" size="2" maxlength="2" /> <br /> ZIP: <input name="zip" size="5" maxlength="5" /> <br /> <input type="submit" /> </div> </form> • Let's validate this form's data on the server...) $city = $_REQUEST["city"]; $state = $_REQUEST["state"]; $zip = $_REQUEST["zip"]; if (!$city || strlen($state) != 2 || strlen($zip) != 5) { print "Error, invalid city/state/zip submitted."; } • basic idea:examine parameter values, and if they are bad, show an error message and abort. • But: How do you test for integers vs. real numbers vs. strings? • How do you test for a valid credit card number? • How do you test that a person's name has a middle initial?

  23. Regular expressions /^[a-zA-Z_\-]+@(([a-zA-Z_\-])+\.)+[a-zA-Z]{2,4}$/ • How do you test whether a given string matches a particular complex format? • regular expression ("regex"): a description of a pattern of text • can test whether a string matches the expression's pattern • can use a regex to search/replace characters in a string • regular expressions are extremely powerful but tough to read • the above regular expression matches email addresses • in PHP, regexes are strings that begin and end with / • the simplest regexes simply match a particular substring • "/abc/" regular expression matches any string containing "abc": • YES: "abc", "abcdef", "defabc", ".=.abc.=.", ... • NO: "fedcba", "ab c", "PHP", ...

  24. Regular expressions in PHP • regex syntax: strings that begin and end with /, such as "/[AEIOU]+/“ • preg_match uses regular expressions to search a string for a specified pattern. • preg_match(regex, string) • returns the number of times regex matches • which evaluates truein a boolean context if string matches regex

  25. PHP form validation w/ regexes $state = $_REQUEST["state"]; if (!preg_match("/^[A-Z]{2}$/", $state)) { print "Error, invalid state submitted."; } • preg_match and regexes help you to validate parameters • Anchors: ^ and$ • The caret ^metacharactermatches the beginning of a string, • The dollar sign $matches the end of a string. • Character ranges:[A-Z] matches any uppercase letter • Quantifiers: {2} means exactly 2

  26. Wildcards: . • A dot . matches any character except a \nline break • "/.oo.y/" matches "Doocy", "goofy", "LooNy", ... • A trailingiat the end of a regex (after the closing /) signifies a case-insensitive match • "/mart/i" matches "Marty Stepp", "smart fellow", "WALMART",

  27. Special characters: |, (), \ • | means OR • "/abc|def|g/" matches "abc", "def", or "g " • () are for grouping • "/(Homer|Marge) Simpson/" matches "Homer Simpson" or "Marge Simpson“ • \ starts an escape sequence • many characters must be escaped to match them literally: / \ $ . [ ] ( ) ^* + ? • "/<br \/>/" matches lines containing <br /> tags

  28. Quantifiers: *, +, ?, {min,max} • * means 0 or more occurrences • "/abc*/" matches "ab", "abc", "abcc","abccc", ... • "/a(bc)*/" matches "a", "abc", "abcbc", "abcbcbc", ... • "/a.*a/" matches "aa", "aba", "a8qa", "a!?_a", ... • + means 1 or more occurrences • "/a(bc)+/" matches "abc", "abcbc", "abcbcbc", ... • "/Goo+gle/" matches "Google", "Gooogle", "Goooogle", ... • ? means 0 or 1 occurrences • "/a(bc)?/" matches "a" or "abc“ • {min,max} means between minandmax occurrences (inclusive) • "/a(bc){2,4}/" matches "abcbc", "abcbcbc", or "abcbcbcbc" • min or max may be omitted to specify any number • {2,} means 2 or more • {,6} means up to 6 • {3} means exactly 3

  29. Anchors: ^ and $ • ^ represents the beginning of the string or line; • $ represents the end • /Jess/ matches all strings that contain Jess; • /^Jess/ matches all strings that start withJess; • /Jess$/ matches all strings that end withJess; • /^Jess$/ matches the exact string "Jess" only • /^Mart.*Stepp$/ matches "MartStepp", "Marty Stepp", "Martin D Stepp", ... • but NOT"Marty Stepp stinks" or "I H8 Martin Stepp" • (on the other slides, when we say, /PATTERN/ matches "text", we really mean that it matches any string that contains that text)

  30. Character sets: [] • [] group characters into a character set; will match any single character from the set • "/[bcd]art/" matches strings containing "bart", "cart", and "dart" • equivalent to "/(b|c|d)art/" but shorter • inside [], many of the modifier keys act as normal characters • "/what[!*?]*/" matches"what", "what!", "what?**!", "what??!", ... • What regular expression matches DNA (strings of A, C, G, or T)? • "/[ACGT]+/"

  31. Character ranges: [start-end] • inside a character set, specify a range of characters with - • "/[a-z]/" matches any lowercase letter • "/[a-zA-Z0-9]/" matches any lower- or uppercase letter or digit • an initial ^ inside a character set negates it • "/[^abcd]/" matches any character other than a, b, c, or d • inside a character set, - must be escaped to be matched • "/[+\-]?[0-9]+/" matches an optional + or -, followed by at least one digit • What regular expression matches letter grades such as A, B+, or D-? • "/[ABCDF][+\-]?/"

  32. Escape sequences • special escape sequence character sets: • \dmatches any digit (same as [0-9]); • \Dany non-digit ([^0-9]) • \w matches any “word character” (same as [a-zA-Z_0-9]); • \Wany non-word char • \s matches any whitespace character ( , \t, \n, etc.); • \Sany non-whitespace • What regular expression matches a three digit dollar amounts such as $100.00? • "/\$\d{3,}\.\d{2}/"

  33. More on Preg_match • Preg_matchis really useful for extracting phrases out of a text string. • To do this, you specify an array as the third argument. • You also need to use parenthesizes in your regular expression to specify the sections you want to retrieve. • intpreg_match ( $pattern , $ string, $matches) • The optional thirdargument is an array that is filled with the results of search. • $matches[0] will contain the text that matched the full pattern, • $matches[1] will have the text that matched the first captured parenthesized subpattern, • and so on. • For example, the following regex divides a url into two sections. • The first is "http://", • the second section is whatever comes after: preg_match ('/(http://)(.*)/', "http://www.tipsntutorials.com/", $matchesarray) $matchesarray[0] = "http://www.tipsntutorials.com/" $matchesarray[1] = "http://" $matchesarray[2] = "www.tipsntutorials.com/"

  34. preg_replace • preg_replace(regex, replacement, string) • returns a new string with all substrings that match regexreplaced by replacement • If matches are not found, string will be returned unchanged or NULL if an error occurred. • $str = "the quick brown fox"; • $str = preg_replace("/[aeiou]/", "*", $str); • # "th* q**ck br*wn f*x" • To find multiple instances of a given pattern,: • must make multiple calls to preg_match, • and remove matched instances before calling the function again by using a function such as preg_replace.

  35. preg_split • preg_split(regex, string) • returns an array of strings from given string broken apart using the given regex as the delimiter (similar to explodebut more powerful) # replace vowels with stars $str = "the quick brown fox"; $str = preg_replace("/[aeiou]/", "*", $str); # "th* q**ck br*wn f*x" # break apart into words $words = preg_split("/[ ]+/", $str); # ("th*", "q**ck", "br*wn", "f*x") # capitalize words that had 2+ consecutive vowels for ($i = 0; $i < count($words); $i++) { if (preg_match("/\*{2,}/", $words[$i])) { $words[$i] = strtoupper($words[$i]); } } # ("th*", "Q**CK", "br*wn", "f*x")

  36. Example: Form (1 of 2)

  37. Example: Form (2 of 2)

  38. Example: Invalidating the form (1 of 2) Without extract we could use $_POST[‘phone’] $_POST[‘fname’] $_POST[‘email’] Etc. die function: Terminates execution and closes the document properly

  39. Example: Invalidating the form (2 of 2)

  40. expression.php(1 of 2) String to search Searches for the string “Now” in $search Checks if string “Now” appears at the beginning of $search Checks if string “Now” appears at the end of $search

  41. expression.php (2 of 2) Searches for a word ending in “ow” and stores matches in $match array Prints first encountered instance of word ending in “ow” Performs a case-insensitive search for words beginning with the letter “t” Replaces the found instance from the previous call to preg_matchwith an empty string so that the next instance of the pattern can be found and stored in $match potatos

More Related