410 likes | 556 Views
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:
E N D
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: <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
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
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
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
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
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.
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
The htmlspecialchars function $text = "<p>hi 2 u & me</p>"; $text = htmlspecialchars($text); # "<p>hi 2 u & me</p>" • 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
"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.
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
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"
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>
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 ) )
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"; }
(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
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"; }
(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
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)
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
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?
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", ...
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
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
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",
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
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
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)
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]+/"
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][+\-]?/"
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}/"
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/"
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.
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")
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
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
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