AWPChapter 6
AWPChapter 6
PHP COOKIES
AND
SESSION
Introduction
2
What is a Cookie?
A cookie is often used to identify a user.
A cookie is a small text file that is saved on the user’s
computer.
The maximum file size for a cookie is 4KB.
Each time the same computer requests a page with a
browser, it will send the cookie too.
With PHP, you can both create and retrieve cookie
values.
Cont…
3
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); //
86400 = 1 day ?>
<html><body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body></html>
Note: The setcookie() function must appear BEFORE the <html> tag.
Continued
8
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30),
"/"); ?>
<html><body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body></html>
Delete a Cookie
10
<?php
setcookie("test_cookie", "test", time() + 3600, '/'); ?>
<html><body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body></html>
PHP Sessions
13
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html><body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body></html>
Note: The session_start() function must be the very first thing in your
document. Before any HTML tags.
Get PHP Session Variable Values
19
Also notice that all session variable values are stored in the
global $_SESSION variable:
Example
20
<?php
session_start();
?>
<!DOCTYPE html>
<html><body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body></html>
Another way to show all the session variable values for a user
session is to run the following code:
Example
21
<?php
session_start();
?>
<!DOCTYPE html>
<html><body>
<?php
print_r($_SESSION);
?>
</body></html>
How does it work? How does it know it's me?
Most sessions set a user-key on the user's computer that looks something like
this:
765487cf34ert8dede5a562e4f3a7e12.
Then, when a session is opened on another page, it scans the computer for a
user-key.
If there is a match, it accesses that session, if not, it starts a new session.
Modify a PHP Session Variable
22
<!DOCTYPE html>
<html><head><style>table, th, td { border: 1px solid
black; border-collapse: collapse;
}th, td { padding: 5px; } </style></head><body><table>
<tr><td>Filter Name</td><td>Filter ID</td></tr>
<?php
foreach (filter_list() as $id =>$filter) {
echo '<tr><td>' . $filter . '</td><td>' .
filter_id($filter) . '</td></tr>';
} ?></table>
</body>
</html>
Why Use Filters?
27
<!DOCTYPE html>
<html>
<body>
<?php
$str = "<h1>Hello World!</h1>";
$newstr = filter_var($str, FILTER_SANITIZE_STRING);
echo $newstr;
?> </body></html>
Validate an Integer
The following example uses the filter_var() function to check if the
variable $int is an integer.
If $int is an integer, the output of the code above will be: "Integer is
valid".
If $int is not an integer, the output will be: "Integer is not valid":
Example
30
<!DOCTYPE html>
<html><body>
<?php
$int = 100;
if (!filter_var($int, FILTER_VALIDATE_INT) ===
false) {
echo("Integer is valid");
} else {
echo("Integer is not valid"); } ?>
</body></html>
Continued
31
<!DOCTYPE html>
<html><body>
<?php
$email = "[email protected]";
// Remove all illegal characters from email
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate e-mail
if (!filter_var($email, FILTER_VALIDATE_EMAIL) ===
false) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}?></body></html>
Sanitize and Validate a URL
35
<!DOCTYPE html>
<html><body>
<?php
$url = "http://www.w3schools.com";
// Remove all illegal characters from a url
$url = filter_var($url, FILTER_SANITIZE_URL);
// Validate url
if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
echo("$url is a valid URL");
} else {
echo("$url is not a valid URL");} ?>
</body></html>
PHP Error Handling
37
<?php
if(!file_exists("welcome.txt")) {
die("File not found");
} else {
$file=fopen("welcome.txt","r"); } ?>
Now if the file does not exist you get an error like
this:
File not found
The code above is more efficient than the earlier code,
because it uses a simple error handling mechanism to stop
the script after the error.
Continued
41
Syntax
error_function(error_level,error_message,
error_file,error_line,error_context)
Continued
43
Parameter Description
error_level Required. Specifies the error report level for the user-defined
error. Must be a value number. See table below for possible error
report levels
error_message Required. Specifies the error message for the user-defined error
error_file Optional. Specifies the filename in which the error occurred
error_line Optional. Specifies the line number in which the error occurred
error_context Optional. Specifies an array containing every variable, and their
values, in use when the error occurred
Error Report levels
44
8 E_NOTICE Run-time notices. The script found something that might be an error, but could also happen when running a script
normally
256 E_USER_ERROR Fatal user-generated error. This is like an E_ERROR set by the programmer using the PHP function trigger_error()
512 E_USER_WARNING Non-fatal user-generated warning. This is like an E_WARNING set by the programmer using the PHP function
trigger_error()
1024 E_USER_NOTICE User-generated notice. This is like an E_NOTICE set by the programmer using the PHP function trigger_error()
4096 E_RECOVERABLE_E Catchable fatal error. This is like an E_ERROR but can be caught by a user defined handle (see also
RROR set_error_handler())
8191 E_ALL All errors and warnings (E_STRICT became a part of E_ALL in PHP 5.4)
Example
46
set_error_handler("customError");
Since we want our custom function to handle all
errors, the set_error_handler() only needed one
parameter, a second parameter could be added to
specify an error level.
Example
49
Example
In this example an E_USER_WARNING occurs if
the "test" variable is bigger than "1".
If an E_USER_WARNING occurs we will use our
custom error handler and end the script:
Example
53
<?php
//error handler function
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Ending Script";
die();} //set error handler
set_error_handler("customError",E_USER_WARNI
NG);
//trigger error
$test=2; if ($test>1) { trigger_error("Value must be
1 or below",E_USER_WARNING); } ?>
54
<?php
//error handler function
function customError($errno, $errstr) {
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Webmaster has been notified";
error_log("Error: [$errno] $errstr",1,
"[email protected]","From: [email protected]");
}
//set error handler
set_error_handler("customError",E_USER_WARNING);//trigger error
$test=2;
if ($test>1) {
trigger_error("Value must be 1 or below",E_USER_WARNING);
}
?>
Continued
57
<?php
//create function with an exception
function checkNum($number) {
if($number>1) {
throw new Exception("Value must be 1 or below");
}
return true;
}
//trigger exception
checkNum(2);
?>
Try, throw and catch
63
<?php
//create function with an exception
function checkNum($number) {
if($number>1) { throw new Exception("Value must be 1 or below");
}
return true;
}//trigger exception in a "try" block
try {checkNum(2); //If the exception is thrown, this text will not be
shown
echo 'If you see this, the number is 1 or below';
}//catch exception
catch(Exception $e) { echo 'Message: ' .$e->getMessage(); } ?>
The code above will get an error like this:
Message: Value must be 1 or below
Example explained:
65
try { //check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
//throw exception if email is not valid
throw new customException($email);
}
}
catch (customException $e) {
//display custom message
echo $e->errorMessage();
}
?>
Continued
69
try { //check if
if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) { //throw exception if email
is not valid
throw new customException($email);
} //check for "example" in mail address
if(strpos($email, "example") !== FALSE) {
throw new Exception("$email is an example e-mail"); } }
catch (customException $e) {
echo $e->errorMessage();
} catch(Exception $e) {
echo $e->getMessage(); } ?>
Example explained:
73
<?php
class customException extends Exception {
public function errorMessage() { //error message
$errorMsg = $this->getMessage().' is not a valid E-Mail address.';
return $errorMsg; }}
$email = "[email protected]";
try {
try { //check for "example" in mail address
if(strpos($email, "example") !== FALSE) { //throw exception if email is not
valid
throw new Exception($email); }
} catch(Exception $e) {
//re-throw exception
throw new customException($email); } }
catch (customException $e) { //display custom message
echo $e->errorMessage(); }
?>
Example explained:
77
The code above tests if the email-address contains the string "example" in it, if it
does, the exception is re-thrown:
The customException() class is created as an extension of the old exception class.
This way it inherits all methods and properties from the old exception class
The errorMessage() function is created. This function returns an error message if
an e-mail address is invalid
The $email variable is set to a string that is a valid e-mail address, but contains
the string "example"
The "try" block contains another "try" block to make it possible to re-throw the
exception
The exception is triggered since the e-mail contains the string "example"
The "catch" block catches the exception and re-throws a "customException"
The "customException" is caught and displays an error message
If the exception is not caught in its current "try" block, it will search for a catch
block on "higher levels".
Continued
78