lecture 10 more on php presented by dr. shazzad hosain asst. prof. eecs, nsu

68
Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

Upload: roberta-moore

Post on 16-Jan-2016

222 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

Lecture 10 More on PHP

Presented ByDr. Shazzad Hosain

Asst. Prof. EECS, NSU

Page 2: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

2

Form Handling, Example 1• Any form element is automatically available via one of the built-in PHP variables.<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>

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

Welcome KarimYou are 20 years old!

Page 3: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

Form Handling, Example 2Change password

No separate PHP file

Page 4: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

Form Handling, Example 2Change password

Page 5: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

5

Example 3: Required Fields in User-Entered Data• A multipurpose script which asks users for some

basic contact information and then checks to see that the required fields have been entered.

<html><!-- form_checker.php CSE382 --><head><title></title></head><body><?php/*declare some functions*/

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

Page 6: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

6

Check and Confirm Functionsfunction 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><?phpecho "Name: $f_name $l_name <br/>";echo "Email: $email <br/>";echo "OS: $os";}

Page 7: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

<html> ***<body><?phpfunction 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>

Page 8: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

8

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:

<?phpfunction 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();}?>

Page 9: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

9

PHP File Processing

Page 10: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

10

File Processing

• There are 3 steps to using data in a file

1) Open the file. If the file doesn’t already exist create it or catch the error gracefully.

2) Write/Read data from the file.3) 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.

Page 11: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

11

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”);

Page 12: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

12

Summary of File Modesr 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

Page 13: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

13

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();

}

Page 14: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

14

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 filefclose($fp);

Page 15: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

15

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 use fgetss, 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

Page 16: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

16

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

Page 17: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

17

PHP Environment Variables

Page 18: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

18

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.

Page 19: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

19

Example Login.php Request 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.

– POST will pass data via the servers environment variables. Data is not seen directly by the user

Page 20: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

20

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

Page 21: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

21

Some Superglobal Environment Arrays

Variable Name Description

$_SERVER Information about the server session and the HTTP connection with the client.

$_ENV Information about the server environment and system defined values.

$_GETData posted to the server by the get method.

$_POSTData posted to the server by the post method.

$_SESSION[] used for session management

$_COOKIE Data contained in cookies on the client’s computer.

$GLOBALS Array containing all global variables.

Page 22: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

22

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– ….

Page 23: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

23

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

Page 24: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

24

Server Variables• The $_SERVER is a reserved variable that contains all server information.

<html><head></head><body>

<?phpecho "Referer: " . $_SERVER["HTTP_REFERER"] . "<br />";echo "Browser: " . $_SERVER["HTTP_USER_AGENT"] . "<br />";echo "User's IP address: " . $_SERVER["REMOTE_ADDR"];?>

</body></html>

The $_SERVER is a super global variable, i.e. it's available in all scopes of a PHP script.

view the output page

Page 25: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

25

1. 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

Page 26: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

26

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;

?>

Page 27: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

27

Simple User Info Script

<? $IP = $REMOTE_ADDR;$browser = $HTTP_USER_AGENT;

print "You are using $browser<BR>”;print "Your IP address is $IP<BR>”;?>

Page 28: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

28

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?”;

?>

Page 29: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

29

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();?>

Page 30: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

30

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.

Page 31: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

31

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

Page 32: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

32

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>";?>

Page 33: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

33

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>

Page 34: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

34

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

Page 35: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

35

Step 4 – Job done

<? require(“tracking.fns"); log_user(“Welcome Page");

print "<B>This is the Welcome Page – visit logged</B>";?>

<? require(“tracking.fns"); log_user(“Search Page");

print "<B>This is the Search Page – visit logged</B>";?>

welcome_page.php

search_page.php

Page 36: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

36

PHP Cookies

Page 37: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

37

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…

Page 38: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

38

Guidelines1. You have to put the cookie code before you print out any other HTML in

your script.

2. 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

Page 39: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

39

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

Page 40: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

40

Time Conversion table

1 minute - 60s1 hour - 3600s1 day - 86400s1 week - 604800s1 fortnight - 1209600s1 month - 2419200s3 month - 7257600s1 year - 29030400s

Page 41: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

41

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>”;

?>

Page 42: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

42

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");  

?>

Page 43: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

43

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.

Page 44: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

44

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']?>

Page 45: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

45

Formatting Cookies• If you use sprintf to 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);

Page 46: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

46

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.

Page 47: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

47

Cookie Workings• setcookie(name,value,expire,path,domain) creates cookies.

<?php

setcookie("uname", $_POST["name"], time()+36000);?><html><body><p>Dear <?php echo $_POST["name"] ?>, a cookie was set on thispage! The cookie will be active when the client has sent thecookie back to the server.</p></body></html>

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

<html><body><?phpif (isset($_COOKIE["uname"]))echo "Welcome " . $_COOKIE["uname"] . "!<br />";elseecho "You are not logged in!<br />";?></body></html> use the cookie name as a

variable

isset()finds out if a cookie is set

$_COOKIEcontains all COOKIE data.

view the output page

Page 48: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

48

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!

Page 49: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

49

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.

Page 50: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

50

PHP Session

Page 51: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

51

The Session Solution PHP has a great set of functions that can achieve the same

results of Cookies and more without storing information on the user's computer.

PHP Sessions store the information on the web server in a location that you chose in special files.

These files are connected to the user's web browser via the server and a special ID called a "Session ID".

This is nearly 99% flawless in operation and it is virtually invisible to the user.

Page 52: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

52

Session Start• The correct way to start a session is using the session_start()

command.

• We must include this statement at the start of every script of our site that we want to be able to use session variables in.

<? session_start(); print “We have started our session:";

?>

• This is essential and an easy thing to forget.

Page 53: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

53

Actual Scenario

Page 54: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

54

A common error• Just like Cookies you MUST call the session_start() function before anything is

output to your web browser. This is absolutely important because you will get some ugly errors by PHP that will say something like this:

<? echo “This is incorrect and will cause an error:"; session_start();

?>

Generates the error:

Warning: Cannot send session cookie - headers already sent by (output started at session_header_error/session_error.php:2) in session_header_error/session_error.php on line 3

Page 55: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

55

Assigning Variables<?

// start the session session_start(); print “Registering a session";

// Get the user's input from the form for example $data = $_POST[‘data'];

// Create a new Session variable session_register('name');

// 2 ways of putting data into the variable $_SESSION['name'] = $data; $name = $data

?>Welcome to my website <? print $name ?><BR>This is an example of receiving a data variable from an HTML form and putting it in the session.

Page 56: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

56

Superglobals• Keep in mind that PHP has a switch in its setup which creates

variable names for data sent to a script.

• Often this register_globals setting may be turned OFF for security. This happens to be the same setting as the default PHP installation after PHP version 4.1 series.

• $_POST[data] and $_Session[‘name’] are superglobals

• You have to use them if register_globals is OFF.

Page 57: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

57

Sessions on Multiple Pages

• The first thing you MUST do on each page you want to access a session variable is to start the session.

• That may not sound right to you because "We already started the session on the last page."

• That's true, but we need to keep the "connection" going between our session because they do not have persistent connections like MySQL does.

Page 58: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

58

A Multiple Page Session<?

// start the session session_start(); print “In this script we use session variables”;print “that we created in the previous script<br>”;

// display the session variableprint “Hi there $name everything is working!<br>”;

// or if register_globals is not activeprint “We can use the superglobal $_SESSION['name']”;

?>

Page 59: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

59

Unregistering Session Variables• PHP is really well designed.

• With PHP Sessions, we have the ability to simply remove a single session variable without dumping our entire session and rebuilding it. The function is called session_unregister()

• Here's how we unregister a single session variables and leave the rest intact.

  session_unregister('name');

Page 60: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

60

Destroying a Whole Session Why might it be necessary to destroy a session when the session

will get destroyed when the user closes their browser?

Well, Imagine that you had a session you were using to determine if the user was logged into your site based upon a username and password - anytime you have a login feature, to make the users feel better, you should have a logout feature as well.

That's where session_destroy() may be useful – it will delete the session files and clears any trace of that session.

Page 61: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

61

Viewing All Session Variables• You can view every single session variable you have stored

and what its value is by using the following code:

<?   session_start(); print "Sessions: <BR>"; print_r($_SESSION);

?>

• This script is pretty straight forward and gives all the info about what's in your session's scope.

Page 62: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

62

Viewing Your Session ID• Every Session has a unique Session ID. A session ID looks like

someone has had a typing fit and collapsed on the keyboard. • There's a function in PHP called session_id() that allows you to

display the current session ID or utilize it however you need. <?

session_start(); echo "Your session ID is <B>".session_id() ."</B>";

?>

• This will simply display something like:

Your session ID is Bd315d2ed59dfa1c2d0fb0b0339c758d

Page 63: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

63

IE6 Session Problem

When you click your back button to make changes in the form, you have to click the REFRESH button on that page to get the information that you posted back into the form.

This only works about 50% of the time. The other 50% the users information is lost

This can be horrific for users… but there is a simple solution. Enter this right below the session_start() of each script:

header("Cache-control: private");

Page 64: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

64

PHP Web Mail

Page 65: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

65

Web Mail Systems• Its easy to send emails in php too.

• Mail() function uses SMTP (Simple Mail Transfer Protocol) to send emails automatically from inside your scripts.

• To receive and process mail PHP can use the IMAP protocols (we won’t go into this).

• PHP comes with the IMAP library and this can be used for POP and NNTP (news) connections.

Page 66: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

66

Sending a mail…<? $email = “[email protected]";

$title = “More SPAM!”; $message = “This is my first\n PHP mail message”;

$from = "From: [email protected]\n";

mail($email, $title, $message, $from);

?>

Often the mail goes to spam folder. Extra measures needs to be taken.

Page 67: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

67

Ripping Web Pages• In PHP it is easy to analyse other peoples pages, whether it be for data

mining or web Searching

• The file() command can load whole page of HTML into a variable. It is as simple as:

<?$page = file("http://www.nsu.edu")or die("problem analysing web site");

?>

• From then its up to you to analyse this raw HTML data, using regular expressions, string searching and such like to mine the data that you need.

Page 68: Lecture 10 More on PHP Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU