File

advertisement
Leksion 13
1
Nevoja per qendrueshmeri


Marrim ne konsiderate shembujt:
 Numerimi i vizitave ne nje website
 Sa here e ka ngarkuar nje klient faqen tuaj web?
Pra faqja juaj .php duhet qe te kujtoje instancat e
meparshme te saj qe jane kerkuar nga nje klient.
2
Qendrueshmeria


Qendrueshmeria eshte aftesia e te dhenave per te
jetuar me gjate se ekzekutimi i programit qe i ka krijuar
ato.
Nje menyre e qarte per ta arritur kete eshte qe thjesht
te ruhen te dhenat ne nje skedar.
3
Qendrueshmeria dhe HTTP
Rikujtojme qe http eshte nje protokoll pa gjendje. Pra ai nuk
kujton asgje nga trasferimet e meparshme
Dy menyra per te arritur qendrueshmerine:

PHP cookies

PHP sessions
Client
HTTP
server
Session
Cookie
4
Cookies ne HTTP
Ne programimin ne internet, nje cookie eshte nje pakete informacioni
qe dergohet nga serveri tek klienti, dhe me pas kthehet mbrapsht ne
server sa here qe aksesohet nga klienti.
I shton gjendje HTTP-se (kujtojme: HTTP eshte pa gjendje)
Cookies transferohen ndermjet serverit dhe klientit me ane te http-se.
PHP suporton cookies te http-se
Cookies mund te mendohen edhe si “bileta” qe perdoren per te
identifikuar klientet dhe porosite e tyre.
5
Si jane implementuar cookies?

Cookies dergohen nga serveri tek klienti nepermjet
kokave te http-se me komanden “Set-Cookie”
Set-Cookie: NAME=VALUE; expires=DATE; path=PATH;
domain=DOMAIN_NAME; secure


Vlera e NAME eshte nje emer qe identifikon nje cookie
sipas kodimit URL
PATH dhe DOMAIN percaktojne se ku aplikohet cookie
6
setcookie(name,value,expire,path,domain,secure)
Parameter
Pershkrimi
name
(i detyrueshem). Percakton emrin e cookie
value
(i detyrueshem). Percakton vleren e cookie
expire
(opsional). Percakton se kur skadon cookie.
Psh: time()+3600*24*30 vendos qe cookie te skadoje pas 30 ditesh.
Nese ky parameter nuk eshte i vendosur, cookie do te skadoje ne fund te sesionit (kur
te mbyllet browseri).
path
(opsional). Percakton pathin ne server te cookie.
Nese eshte "/", cookie do te jete e vlefshme brenda te gjithe domainit.
Nese eshte "/phptest/", cookie do te jete e vlefshme vetem brenda direktorise test dhe
te gjithe nendirektorive te phptest.
Vlera default eshte direktoria aktuale ne te cilen po krijohet cookie.
domain
secure
(opsional). Percakton emrin e domainit te cookie.
Per ta bere cookien te vlefshme ne te gjithe nendomainet e example.com, atehere ju
duhet ta vendosni ate ".example.com".
Po ta vendosni www.example.com do ta beje cookie-n te vlefshme vetem ne
nendomainin www.
(opsional). Percakton nese cookie duhet te transmetohet vetem mbi nje lidhje te sigurte
HTTPS.
TRUE tregon qe cookie do te krijohet vetem nese ekziston nje lidhje e sigurte. Vlera
default eshte FALSE.
7
Cookies nga HTTP
Client (e.g. Firefox)
it026945
GET /*.html HTTP/1.1
Host: it026954.domain
HTTP/1.1 200 OK
Content-type: text/html
Set-Cookie:
name=value
GET /*.html HTTP/1.1
Host: it026945.domain
Cookie: name=value
Accept: */*
(content of page)
8
Krijimi i cookies ne PHP
Cookies mund te krijohen direkt duke manipuluar koken e
mesazhit HTTP me ane te funksionit header() ne PHP
<?php
header(“Set-Cookie: mycookie=myvalue; path=/;
domain=.coggeshall.org”);
?>
9
Krijimi i cookies me setcookie()
Perdorni funksionin setcookie() te PHP-se:
Setcookie (name,value,expire, path, domain, secure)
PSh:
<?php
setcookie("MyCookie",
$value, time()+3600*24);
setcookie("AnotherCookie", $value, time()+3600);
?>






Name: emri i skedarit
Value: te dhenat qe ruhen ne skedar
Expire: string te dhenash qe percakton jetegjatesine
Path: nenbashkesia e URL-ve ne nje domain ku ajo eshte e vlefshme
Domain: domain per te cilin cookie eshte e vlefshme
10
Secure: vendoset '1' per ta transmetuar ne HTTPS
Leximi i cookies
Per te aksesuar nje cookie te marre nga nje klient, perdorni vektorin
superglobal te PHP-se $_COOKIE
<?php
foreach ($_COOKIE as $key=>$val) {
print $key . " => " . $val . "<br/>";
}
?>
Cdo çeles ne vektor perfaqeson nje cookie – emri çeles eshte emri i
cookiet.
11
Shembull i krijimit dhe perdorimit
te cookie-ve
<?php
setcookie("MyCookie",
$value, time()+7200);
setcookie("AnotherCookie", $value, time()+7);
?>
<?php
foreach ($_COOKIE as $key=>$val) {
print $key . " => " . $val . "<br/>";
}
?>

Cookiet behen te dukshme vetem ne ngarkimin tjeter te
faqes
12
Perdorimi i headers (menyra e gabuar!)
<!DOCTYPE html PUBLIC "=//W3C//DTD XHMTL 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhmtl" xml:lang="en">
<head><title>PHP Script using Cookies</title>
<meta http-equiv="Content-Type" content="text/html; chatset=ISO-8859-1" />
</head>
<body>
<?php
$strValue = "This is my first cookie";
setcookie ("mycookie", $strValue);
echo "Cookie set<br>";
?>
</body>
</html>
Merr nje mesazh gabimi!:
Warning: Cannot modify header information - headers already sent by (output started
at /var/www/html/TESTandre/159339/PHP/cookie_with_headers.php:9) in
/var/www/html/TESTandre/159339/PHP/cookie_with_headers.php on line 11
13
Perdorimi i headers
setcookie() nuk u ekzekutua perpara se
informacioni te dergohej ne browser...
Cookiet duhet te dergohen perpara
elementeve te kokes
14
Perdorimi i headers (menyra e sakte)
<?php
$strValue = "This is my first cookie";
setcookie ("mycookie", $strValue);
echo "Cookie set<br>";
?>
<!DOCTYPE html PUBLIC "=//W3C//DTD XHMTL 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhmtl" xml:lang="en">
<head><title>PHP Script using Cookies</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
</head>
<body>
<?php
echo “<p> A cookie has been set. </p>”;
?>
</body>
</html>
Kjo eshte menyra e sakte
15
Fshirja e nje cookie

Per te fshire nje cookie duhet te caktoni daten e skadimit ne te
shkuaren:
<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>
16
Cookie me shume elemente te dhenash
Perdorni explode() PSh:
<?php
$strAddress = $_SERVER['REMOTE_ADDR'];
$strBrowser = $_SERVER['HTTP_USER_AGENT'];
$strOperatingSystem = getenv('OS');
$strInfo = "$strAddress::$strBrowser::$strOperatingSystem";
setcookie ("somecookie4",$strInfo, time()+7200);
?>
<?php
$strReadCookie = $_COOKIE["somecookie4"];
$arrListOfStrings = explode ("::", $strReadCookie);
echo "<p>$strInfo</p>";
echo "<p>Your IP address is: $arrListOfStrings[0] </p>";
echo "<p>Client Browser is: $arrListOfStrings[1] </p>";
echo "<p>Your OS is: $arrListOfStrings[2] </p>";
?>

17
Ku ruhet cookie?
18
19
Sesionet ne PHP



Ju mund te ruani informacionin e perdoruesit (psh:
username, elementet e zgjedhur, etj.) ne anen e
serverit per ta perdorur me vone ne duke perdorur
sesionin PHP.
Sesionet punojne duke krijuar nga nje id unike (UID)
per çdo visitor dhe duke ruajtur variabla bazuar ne
kete UID.
UID ose ruhet ne nje cookie ose perhapet ne URL.
20
Kur duhet t’i perdorni sesionet?
Nevojiten te dhena te ruajtura ne server
 Informacione sesioni unike per secilin perdorues
 Te dhena kalimtare, qe nevojiten vetem per kohe te
shkurter
 Te dhenat nuk ruajne informacion sekret
 Ngjan me cookies, por ruhet ne server
 Me i sigurte, kur krijohet sesioni nuk ka me te dhena qe
shkojne e vijne ndermjet makinave

Punon edhe nese cookies jane te ç’aktivizuara
Shembull: ne deshirojme te numerojme numrin e vizitave ne
faqen tone web.

21
Sesionet ne PHP
Perpara se te mund te ruani informacionin e perdoruesit ne
sesionin tuaj PHP, fillimisht ju duhet ta filloni sesionin.
Funksioni session_start() duhet te shfaqet PERPARA
tagut <html> .
<?php session_start(); ?>
<html>
<body>
</body>
</html>
22
Sesionet ne PHP

Fillimi i nje sesioni ne PHP:
<?php
session_start();
?>
• Kjo i tregon PHP-se qe kerkohet nje sesion.
• Nje ID sesioni me pas caktohet nga ana e serverit
• session ID ka nje paraqitje te tille:
sess_f1234781237468123768asjkhfa7891234g
23
Variablat e Sesionit

$_SESSION
Psh: $_SESSION[“intVar”] = 10;

Testimi nese nje variabel sesioni eshte krijuar apo jo:

session_start();
if (!isset($_SESSION['intVar'])) {...} //intVar is set or not

24
Regjistrimi i variablave te sesionit

Ne vend te caktimit te variablave superglobale, ju mund te
regjistroni variablat tuaj te sesionit ne me poshte:
<?php
$barney = “A big purple dinosaur.”;
$myvar_name = “barney”;
session_register($myvar_name);
?>
• $barney mund te aksesohet tashme “globalisht” nga nje sesion
ne tjetrin

Kjo punon vetem nese direktiva register_globals eshte e
aktivizuar ne php.ini – ne menyre default ajo eshte e ç’aktivizuar
25
Perdorimi i session_register() eshte i vjeteruar!
Krijoni variablat tuaj te sesionit


Me session_start() krijohet nje variabel sesioni default, i
cili e merr emrin nga emri i faqes
Per te krijuar variablat tuaj te sesionit, shtoni nje çeles
te ri ne variablin superglobal $_SESSION
$_SESSION[‘dug’] = “a talking dog.”;
26
Perdorimi i $_SESSION eshte i preferuar, qe nga PHP 4.1.0.
Shembull Sesioni 1
<?php
session_start();
if (!isset($_SESSION["intVar"]) ){
$_SESSION["intVar"] = 1;
} else {
$_SESSION["intVar"]++;
}
echo "<p>In this session you have accessed this page " .
$_SESSION["intVar"] . "times.</p>";
?>
27
Shembull Sesioni 2
<?php session_start();?>
<?php
$thisPage = $_SERVER['PHP_SELF'];
$pageNameArray = explode('/', $thisPage);
$pageName = $pageNameArray[count($pageNameArray) - 1];
print "The name of this page is: $pageName<br/>";
$nameItems = explode('.', $pageName);
$sessionName = $nameItems[0];
print "The session name is $sessionName<br/>";
if (!isset($_SESSION[$sessionName])) {
$_SESSION[$sessionName] = 0;
print "This is the first time you have visited this page<br/>";
}
else {
$_SESSION[$sessionName]++;
}
print "<h1>You have visited this page " . $_SESSION[$sessionName] .
" times</h1>";
?>
28
Mbarimi i sesionit
unset($_SESSION[‘name’])
–Fshin nje variabel sesioni
session_destroy()
– Shkaterron te gjitha te dhenat e regjistruara ne nje sesion
– nuk i ben unset variablave globale te sesionit dhe cookie-ve qe
lidhen me sesionin
–Normalisht nuk perdoret – lihet te skadoje
29
Shkaterrimi i plote i nje sesioni
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) { // Returns the value of the configuration option
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
Kthen emrin e sesionit
);
aktual
}
// Finally, destroy the session.
session_destroy();
?>
30
http://nz2.php.net/manual/en/function.session-destroy.php
Shembull Sesioni 3
<?php
session_start();
if(!isset($_SESSION['strColourBg'])) $_SESSION['strColourBg'] = "red";
else echo "Currently Bg set to " . $_SESSION['strColourBg'] . "<br>";
if(!isset($_SESSION['strColourFg'])) $_SESSION['strColourFg'] = "yellow";
else echo "Currently Fg set to " . $_SESSION['strColourFg'];
if(isset($_POST["submit"]) ) {
$strColourBg = $_POST["strNewBg"];
$strColourFg = $_POST["strNewFg"];
$_SESSION['strColourBg'] = $strColourBg;
$_SESSION['strColourFg'] = $strColourFg;
echo "<br>New Settings";
}
else {
$strColourBg = $_SESSION['strColourBg'];
$strColourFg = $_SESSION['strColourFg'];
echo "<br>Keep old settings";
}
?>
31
Shembull Sesioni 3 (vazhd.)
<html><head> <style type="text/css">
body {background-color: <?php echo $strColourBg ?>;}
p {color: <?php echo $strColourFg?>;}
h2 {color: <?php echo $strColourFg?>;}
</style></head>
<body>
<h2>h2 colour</h2>
<form action = '<?php echo $_SERVER["PHP_SELF"] ?>' method='post'>
<label for="strNewBg"> Background colour: </label>
<select name='strNewBg' id='strNewBg'>
<option>red</option> <option>grey</option>
</select>
<label for="strNewFg"> Text colour: </label>
<select name='strNewFg' id='strNewFg'>
<option>yellow</option> <option>grey</option>
</select>
<input type='submit' name='submit'/>
</form></body></html>
32
Permbledhje
Sesionet dhe cookiet ne PHP jane mekanizma
per te shtuar gjendje ne transaksionet HTTP.
33
• Pyetje?
34
Download