680 likes | 809 Views
Lecture 10 More on PHP. Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU. Form Handling, Example 1. <html> <-- form.html CSC382 --> <body> <form action="welcome.php" method="POST"> Enter your name: <input type="text" name=" name " /> < br />
E N D
Lecture 10 More on PHP Presented By Dr. ShazzadHosain Asst. Prof. EECS, NSU
Form Handling, Example 1 <html> <-- form.html CSC382 --> <body> <form action="welcome.php" method="POST"> Enter your name: <input type="text" name="name" /> <br/> Enter your age: <input type="text" name="age" /> <br/> <input type="submit" /> <input type="reset" /> </form> </body> </html> • Any form element is automatically available via one of the built-in PHP variables. Welcome Karim You are 20 years old! <html> <!–- welcome.php CSC382 --> <body> Welcome <?php echo $_POST["name"].”.”; ?><br /> You are <?php echo $_POST["age"]; ?> years old! </body> </html> $_POST contains all POST data. $_GET contains all GET data.
Form Handling, Example 2Change password No separate PHP file
Example 3: Required Fields in User-Entered Data <html> <!-- form_checker.php CSE382 --> <head> <title></title> </head> <body> <?php /*declare some functions*/ • A multipurpose script which asks users for some basic contact information and then checks to see that the required fields have been entered. function print_form($f_name, $l_name, $email, $os) { ?> <form action="form_checker.php" method=“POST"> First Name: <input type="text" name="f_name" value="<?php echo $f_name?>“ /> <br/> Last Name <b>*</b>:<input type="text" name="l_name" value="<?php echo $l_name?>“ /> <br/> Email Address <b>*</b>:<input type="text" name="email" value="<?php echo $email?>“ /> <br/> Operating System: <input type="text" name="os" value="<?php echo $os?>“ /> <br/><br/> <input type="submit" name="submit" value="Submit“ /> <input type=“reset“ /> </form> <?php } Print Function
Check and Confirm Functions function check_form($f_name, $l_name, $email, $os){ if (!$l_name||!$email){ echo "<h3>You are missing some required fields!</h3>"; print_form($f_name, $l_name, $email, $os); }else{ confirm_form($f_name, $l_name, $email, $os); } } function confirm_form($f_name, $l_name, $email, $os){ ?> <h2>Thanks! Below is the information you sent to us.</h2> <h3>Contact Info</h3> <?php echo "Name: $f_name $l_name <br/>"; echo "Email: $email <br/>"; echo "OS: $os"; }
<html> *** <body> <?php function print_form($f_name, $l_name, $email, $os) function check_form($f_name, $l_name, $email, $os) function confirm_form($f_name, $l_name, $email, $os) Main Program /*Main Program*/ if (!$_POST["submit"]) { ?> <h3>Please enter your information</h3> <p>Fields with a "<b>*</b>" are required.</p> <?php print_form("","","",""); } else{ check_form($_POST["f_name"],$_POST["l_name"],$_POST["email"],$_POST["os"]); } ?> </body> </html>
Example: formValidating Form Data • First check that form data was submitted, usually with array_key_exists() for the submit button name • Creating functions can be helpful for validation, especially when the validation needs to be done in different forms: <?php function validate_price($value) { if(!isset($errors)) $errors = array(); // init empty array if not defined if( !is_numeric($value) ) $errors['not_number'] = "not numeric"; if( $value < 0 ) $errors['not_non-negative'] = "price cannot be negative"; return $errors(); } ?>
File Processing • There are 3 steps to using data in a file • Open the file. If the file doesn’t already exist create it or catch the error gracefully. • Write/Read data from the file. • Close the file. • To open a file in PHP use the fopen() function. • We supply it with a filename, but we also need to set the file mode – how we intend to use it.
fopen() • Fopen expects 2 or parameters – the location of the file and the file mode. $fp = fopen(“$DOCUMENT_ROOT/../orders/orders.txt”, “w”); • If no path is specified the current directory is used. • N.b. if you are in a windows environment you must use double back slashes. $fp = fopen(“$DOCUMENT_ROOT\\..\\orders\\orders.txt”, “w”);
Summary of File Modes r Read mode r+ Reading and writing w OverWrite mode – if the file already exists delete it and create a new one w+ Overwrite and reading mode– if the file already exists delete it and create a new one a Append mode a+ Appending and writing b binary mode – differentiates between binary and text files
Checking the file exists • Lots of things can go wrong when you try and open a file. • The file might not exist • You might not have permission to view it • It may already be being written to • The following code handles this situation: $fp = fopen(“orders.txt”, “a”); if (!fp){ print “There were problems opening the file”; exit(); }
Writing and Closing • Writing to a file in PHP is easy. You can either use the function: • fwrite() …file write • fputs() …file put sting (an alias to fwrite) $fp = fopen(“orders.txt”, “a”); fwrite($fp, “adding something to the file”); • All that is left is to tidy everything up by closing the file fclose($fp);
Reading from a File • fgets() is the most common function used - It is used to read one line at a time from a file. In this case below it will read until it encounters a newline character, an EOF or has read 99 bytes from the file. $fp = fopen(“orders.txt”, “a”); fwrite($fp, “adding something to the file”); while (!feof($fp)) { $order = fgets($fp, 100); print $order.”<br>; } • You can also usefgetss, fread and fgetc. feof is a really useful function when dealing with files – here we check we are not at the end of the file
Other useful file functions • File_exists(path) – does what is says on the tin. • filesize(path) – tells you how many bytes the file has. • Unlink(path) - deletes the file given to it as a parameter • Flock(path, option) – file locking function with options : • Reading lock • Writing lock • Release existing lock
Environment Variables • Information coming from both the client and server and pertaining to the current execution of a script. PHP has a series of arrays defined. • These arrays are sometimes referred to as the superglobals • You will also find these arrays referred to as environmental variables, since they store information about the environment in which the script is running.
Example Login.phpRequest Methods • There are two basic methods for getting data from an HTML form into PHP • GET and POST • What’s the difference? • GET will encode all data into a query string that is passed with the URL to the action page. This allows data to be bookmarked by the user. • POSTwill pass data via the servers environment variables. Data is not seen directly by the user
Environment Variables • Information from a web server is made available through EGPCS • Environment, GET, POST, Cookies, Server • PHP will create arrays with EGPCS information • $HTTP_COOKIE_VARS, $HTTP_GET_VARS, $HTTP_POST_VARS, etc. • The ‘HTTP’ and ‘_VARS’ can be dropped if desired • These arrays are ‘global’ even inside functions • PHP also will define $_SERVER[‘PHP_SELF’] that refers to the current script file which is useful for self-processing forms
Server Info • A ton of information about the server and current browser is made available in the $_SERVER array • SERVER_NAME • REQUEST_METHOD • QUERY_STRING • REMOTE_ADDR • PHP_SELF • ….
env.php Example <?php // print the key and value for each element // in the $_ENV array foreach ( $_ENV as $key => $value ) print( "<tr><td bgcolor = \"#11bbff\"> <strong>$key</strong></td> <td>$value</td></tr>" ); ?> Print the variables and check what they gives
Server Variables • The $_SERVER is a reserved variable that contains all server information. <html><head></head> <body> <?php echo "Referer: " . $_SERVER["HTTP_REFERER"] . "<br />"; echo "Browser: " . $_SERVER["HTTP_USER_AGENT"] . "<br />"; echo "User's IP address: " . $_SERVER["REMOTE_ADDR"]; ?> </body> </html> view the output page The $_SERVER is a super global variable, i.e. it's available in all scopes of a PHP script.
Spy On Your User • Knowing who uses your site is essential information, whether it be for the purposes tailoring your site to your audience or simple interest. • For example you might want to know their: • location • screen size • colour depth • operating system • browsing patterns • where they’ve linked from
Environment Variables <? //name of the server host and the script being run $x = $SERVER_NAME; //The filename of the currently executing script $x = $PHP_SELF; //variables to do with info sent by a form (GET, POST) $x = $REQUEST_METHOD; //variables that were posted using post, get or cookie. $x = $HTTP_GET_VARS["Varname"]; $x = $HTTP_POST_VARS["Varname"]; $x = $HTTP_COOKIE_VARS["Varname"]; //The users IP address, browser $x = $REMOTE_ADDR; $x = $HTTP_USER_AGENT; ?>
Simple User Info Script <? $IP = $REMOTE_ADDR; $browser = $HTTP_USER_AGENT; print "You are using $browser<BR>”; print "Your IP address is $IP<BR>”; ?>
IP Addresses • Why would you want to know someone’s IP address? • Security • Geographical personalisation • You can identify the same user over and over <? $IP = $REMOTE_ADDR; $IPArray = explode(“.”,$IP); if ($IP_array[0] == 202) print “Welcome. How is Bangladesh?”; ?>
phpinfo() • PHP includes a special command that will display all of these variables to screen and a lot more. • phpinfo() shows you everything about the server you are running, how php is set up, as well as client side information – details of where you are browsing the page from. <? phpinfo(); ?>
Tracking your users • Time() -- gives you the current UNIX timestamp • Date() – formats it so you can understand it • To follow your users progress in a site you can hence keep a log of : • the time a user activated the script • what page they are viewing • their ip address • and where they browsed here from. • This way you can profile your users browsing habits. Combine this information with the file IO we looked at and we can have good user logging.
Bringing it together • The next few slides are going to show you the code to bring this file IO user tracking together. • We will start off with simple code for one page • Then we will functionalise it • We will then separate our functions into a different script, and include them using the require() statement • require() is like include() but will stop the script if it can’t find the specified file
Step 1 – Basic Code <? $ip = $REMOTE_ADDR; $page = "Log Page"; $now = date("F j, Y, g:i a"); $str = "$now - User at ($ip) browsed page ($page)\n"; $fp = fopen("log.txt", "a"); fwrite($fp, $str); fclose($fp); print "</HTML></BODY>"; print "<B>WELCOME TO PAGE - ($page)</B><BR><BR>"; print "your visit here has been logged in a text file <BR>"; print "</BODY></HTML>"; ?>
Step 2 - Making it into a function <? function log_user($page, $ip) { $now = date("F j, Y, g:i a"); $str = "$now - User at ($ip) browsed page ($page)\n"; $fp = fopen("log.txt", "a"); fwrite($fp, $str); fclose($fp); } log_user("Log Page“, $REMOTE_ADDR); ?> <B>WELCOME- your visit here has been logged in a text file </B>
Step 3 – Moving that Function <? function log_user($page) { $ip = $REMOTE_ADDR; $now = date("F j, Y, g:i a"); $str = "$now - User at ($ip) browsed page ($page)"; $fp = fopen("log.txt", "a"); fwrite($fp, $str); fclose($fp); } ?> tracking.fns
Step 4 – Job done <? require(“tracking.fns"); log_user(“Welcome Page"); print "<B>This is the Welcome Page – visit logged</B>"; ?> welcome_page.php search_page.php <? require(“tracking.fns"); log_user(“Search Page"); print "<B>This is the Search Page – visit logged</B>"; ?>
Cookies in PHP • Setting and playing around with cookies can be a fun and useful way to save data on a user's hard drive. • It can successfully store valuable information which may be helpful the next time they come to the site. • Its fairly simple to set up, and even easier to read. To use it, you have to remember some guidelines…
Guidelines • You have to put the cookie code before you print out any other HTML in your script. • The cookie will not be evident on the page until its refreshed, or the user visits the page again (It is sent with the current page data) • Here's the code to set a variable: <? setcookie (“loginName", “Jimbo"); ?> VARIABLE NAME VALUE
Cookie Expiration • Now, the next time someone visits this page, or any other PHP page in the same or sub-directory that cookie variable will be available. • However by default this cookie will expire when the user turns his browser off. • To extend the time to expire, set in seconds as the next field. For example: <? setcookie(“loginName", “jimbo", time()+3600); ?> EXPIRES IN 1 HOUR
Time Conversion table 1 minute - 60s 1 hour - 3600s 1 day - 86400s 1 week - 604800s 1 fortnight - 1209600s 1 month - 2419200s 3 month - 7257600s 1 year - 29030400s
Multiple Cookies • It is not a problem to have multiple cookies - save it, here is a code example: <? setcookie (“loginName", “jimbo"); setcookie (“password", “bosh"); setcookie (“hits", “3"); print $cookie[one].”<BR>”; print $cookie[two].”<BR>”; print $cookie[three].”<BR>”;?>
Deleting Cookies – Reading • There are two ways of deleting cookies. The traditional way <? setcookie ("cookie", "", time()-86400); ?>Or simply by setting the cookie as nothing: <? setcookie ("cookie"); ?>
Don’t use multiple cookies • There is a limit (20 cookies /server) to the number of cookies you can set on someones pc for the same web domain. • As such it is viewed as bad coding to use more than one cookie, and so people tend to store all variables they need in ONE cookie. • This is easy in PHP because of the explode() and implode() commands.
Reading Cookie Information • The cookies for the web domain your page is in will be automatically loaded into PHP. • You can get at them via two arrays: $HTTP_COOKIE_VARS["cookie"]; or $_COOKIE['cookie']; • So to display the cookie data in full on screen all you need is: <? print $_COOKIE['cookie'] ?>
Formatting Cookies • If you use sprintfto set cookies you can use the exact same format in a sscanf to get them out. • And you can take them out as follows $name = “Smith”; $pass = “swordFish”; cookie = sprintf(“name=%s pass=%s", $name, $pass); setcookie ("myCookie", $cookie, time()+86400); • And you can take them out as follows $cookie = $_COOKIE[myCookie]; sscanf($cookie, “name=%s pass=%s", &$name, &$pass);
Exploding Cookies • As I said before you can also use implode and explode. $info[0] = “Smith”; $info[1] = “swordFish”; $cookie = implode($info, “-”); setcookie (“myCookie", $cookie, time()+86400); • And you can take them out as follows $cookie = $_COOKIE[‘myCookie']; $info = explode($cookie, “-”); • Of course you need to remember that element 0 of the info array is the username and element 1 is the password. But this way you can build up huge cookies.
<html> <body> <?php if (isset($_COOKIE["uname"])) echo "Welcome " . $_COOKIE["uname"] . "!<br />"; else echo "You are not logged in!<br />"; ?> </body> </html> $_COOKIE contains all COOKIE data. isset() finds out if a cookie is set view the output page use the cookie name as a variable Cookie Workings <?php setcookie("uname", $_POST["name"], time()+36000); ?> <html> <body> <p> Dear <?php echo $_POST["name"] ?>, a cookie was set on this page! The cookie will be active when the client has sent the cookie back to the server. </p> </body> </html> • setcookie(name,value,expire,path,domain)creates cookies. NOTE: setcookie()must appear BEFORE <html>(or any output)as it’s part of the header information sent with the page. view the output page
Sites that Remember • It is essential in good sites that we maintain state – that we remember certain variables from page to page • We have considered two ways of maintaining state – of keeping variables common between scripts. • Adding variables to the url • Storing variables in cookies • Neither are satisfactory. So what’s the answer? • Sessions!
Problems with Cookies • Not only are cookies painful to code. • It may seem a surprisingly low statistic, but Cookies are about 30% unreliable on the web right now and it's getting worse. • More and more web browsers are starting to come with security and privacy settings and people browsing the net these days are starting to frown upon Cookies because they store information on their local computer that they do not want stored there.