Professional Documents
Culture Documents
Topic 9 CIS423 PHP Sessions Cookies
Topic 9 CIS423 PHP Sessions Cookies
Topic 9 CIS423 PHP Sessions Cookies
PHP
Sessions &
Cookies
+
Encrypting Passwords stored in DB
◼ Examples:
◼ header ('Location: http://www. example.com/page.php');
◼ header("Content-Type:application/ pdf\n");
header ("Content-Disposition: ➝ attachment;
filename=\"somefile.pdf\"\n");
◼ The same!
+
Interacting with the File System
and the Server
◼ dirname() Function:
Sessions
+
What is a Session?
if (isset($_SESSION['user_id']))
{ echo "<h1>Logged In!</h1>
<p>You are now logged in, {$_SESSION['first_name']}!</p>
<p><a href=\"logout.php\">Logout </a></p>"; }
◼ To
remove the session variable value:
unset($_SESSION[‘KeyValue’]);
◼ Or session_destroy()
+
Cookies
How cookies are sent back and forth
between the server and the client.
+
What are Cookies?
◼ For example, to retrieve the value of the cookie established with the
line:
◼ setcookie ('username', ’Ahmed');
◼ Check for the presence of a cookie:if (isset($_COOKIE['user_id']))
◼ Then you would refer to $_COOKIE['username'].
◼ Example: Script 12.3 login.php & Example 19.10 (Deitel & Deitel)
◼ To
effectively program using cookies, you need to
be able to accurately test for their presence.
◼ The best way to do so is to have your Web browser ask what
to do when receiving a cookie. In such a case, the browser
will prompt you with the cookie information each time PHP
attempts to send a cookie
+
Cookies (Testing Cookie-Handling
cont’d)
◼ To set this up using Internet Explorer on Windows: IE ➔ Tools ➔
Internet Options ➔ Privacy tab ➔ the Advanced button under
Settings ➔ Click “Override automatic cookie handling” ➔then
choose “Prompt” for First-party Cookies.
+
Cookies (Testing Cookie-Handling
cont’d)
◼ Using Firefox on
Windows: choose
Tools ➔ Options ➔
Privacy. Firefox on
Mac OS X: Firefox ➔
Preferences ➔
Privacy tab, ➔ select
“Use custom settings
for history” and
you’ll see the “Keep
until” selector.
+
Setting Google Chrome Cookies
+
Cookies vs. Sessions: What is the
main difference between them?
Sessions Cookies
◼ They are generally more ◼ They are easier to
secure (because the data program.
is being retained on the
server).
◼ They require less of the
◼ They allow for more data server.
to be stored.
◼ They can be made to last
◼ They can be used far longer.
without cookies
In general, to store and retrieve just a couple of small pieces of
information, or to store information for a longer duration, use
cookies. For most of your Web applications, though, you’ll use
sessions.
+
Questions?
+ To test the session scripts
◼ Create a folder and name it session
◼ Add the Script 3.4 - index.php (add the code session_start() to the
beginning of the script).
◼ add folder includes from ch12, then replace header.html with Script
12.10 - header.html