4 - Pi (Php Lanjut)

12
3/25/2011 1 Manajemen Sesi Login User Cookie Session Session Session digunakan untuk menyimpan suatu informasi antar proses request, baik request dalam bentuk POST atau GET Salah satu contoh yang menggambarkan penggunaan session adalah proses login. User akan memasukkan username melalui form login. Setelah login berhasil, user tersebut dihadapkan pada link menu navigasi yang menuju ke beberapa halaman web. Agar username tersebut akan selalu tampil atau tercatat di halamanhalaman web tersebut, maka username dapat disimpan dalam session.

Transcript of 4 - Pi (Php Lanjut)

Page 1: 4 - Pi (Php Lanjut)

3/25/2011

1

‐Manajemen Sesi‐Login User

‐ Cookie

SessionSessionSession digunakan untuk menyimpan suatu informasiantar proses request, baik request dalam bentuk POST atau GETSalah satu contoh yang menggambarkan penggunaansession adalah proses login. User akan memasukkan username melalui form login. Setelah login berhasil, user tersebut dihadapkan padalink menu navigasi yang menuju ke beberapa halamang y g j pweb. Agar username tersebut akan selalu tampil atautercatat di halaman‐halaman web tersebut, makausername dapat disimpan dalam session.

Page 2: 4 - Pi (Php Lanjut)

3/25/2011

2

ContohContoh sederhanasederhana<html><body> <form action="session.php" method="POST"><form action session.php method POST > User Name :<input type="text" name="username"><br> Password :<input type="password" name="password"><br>

<input type="submit" value="Login"></form> </body></html>

<? //session.phpsession start(); _$username = $_POST["username"];$password = $_POST["password"]; if ($username=="ragil" && $password=="rahasia"){ $_SESSION["user"] = $username;header("Location: berhasil.php");

}else {echo "Maaf anda gagal melakukan login";}?>

Page 3: 4 - Pi (Php Lanjut)

3/25/2011

3

<? //berhasil.phpsession_start(); if (isset($ SESSION["user"])){if (isset($_SESSION[ user ])){echo "Selamat datang <b>".$_SESSION["user"]." </b> andaberhasil login<br>"; echo "<a href='logout.php'>logout</a>";

}else { echo "Maaf anda tidak berhak mengakses halaman ini !"; }?>

//l h<? //logout.phpsession_start(); session_unset();session_destroy(); header("Location: login.php");?>

HasilHasil

Page 4: 4 - Pi (Php Lanjut)

3/25/2011

4

Login User with SessionLogin User with SessionSession dapat digunakan untuk mengatur menu yang dapatdiakses oleh userDigunakan database untuk menyimpan data userSchema :

Schema FlowSchema FlowThe first time that a protected page is requested, the user will not have entered his or her login details yet. The script detects this and prompts the user for a username and p p ppassword with a login form instead of displaying the requested page. When that form is submitted, the page is reloaded, this time with a username and password specified. The script sees that the login details have been specified, and registers them as session variables so that they remain available for the rest of the user's visit. Finally, the script checks the database to make sure the y, pusername/password combination is valid. 

If it is, the page requested is displayed. If not, an "access denied" message is displayed with a link inviting the user to try logging in again.

Page 5: 4 - Pi (Php Lanjut)

3/25/2011

5

Form LoginForm LoginForm : Validasi Form :

ValidasiValidasi Form Form dengandengan javascriptjavascript<script language="javascript"><!—function cek2(){

if (document.form2.username.value==""){alert('Username belum diisi');document.form2.username.focus();return false;

}

if (document.form2.password.value==""){alert('Password wajib diisi');document.form2.password.focus();return false;return false;

}return true;}

--></script>

Page 6: 4 - Pi (Php Lanjut)

3/25/2011

6

CekCek LoginLogin$password=md5($_POST[password]);$sql="select *from user where username='$_POST[username]' AND password='$password'";$result=mysql_query($sql);$ketemu=mysql_num_rows($result);$data=mysql_fetch_array($result);if($ketemu>0) {

session_start();$_SESSION[username]=$data[username];$_SESSION[password]=$data[password];$ SESSION[level] $data[level];$_SESSION[level]=$data[level];

if($data[level]=="User Biasa“) {header('location:index.php?module=home');}elseif($data[level]=="Administrator“) {header('location:index.php?module=home');

}}

echo "<script>alert('Username dan Password Anda tidak cocok');location.href='index.php'</script>";

Page 7: 4 - Pi (Php Lanjut)

3/25/2011

7

Login Login ‐‐‐‐ OKOKPembagian hak akses menuCek level user

if($ SESSION[level]=="User Biasa"){if($_SESSION[level]== User Biasa ){echo“<a href="?module=home">Home</a><br /><br><a href="?module=info">Browsing</a><br /><br><a href="?module=info2">Surving </a><br><br>”;}if($_SESSION[level]=="Administrator“) {echo “<a href="?module=home">Home</a><br /><br><a href="?module=tambah">Tambah</a><br /><br><a href="?module=edit">Edit</a><br /><br><a href="?module=hapus">Hapus </a><br><br>”;}

HasilHasil ManajemenManajemen MenuMenuUser Biasa Administrator

Page 8: 4 - Pi (Php Lanjut)

3/25/2011

8

Manajemen Content<?// Tanpa User dan Passwordif( t ($ SESSION[ ]) ANDif(empty($_SESSION[username]) AND

empty($_SESSION[password])){echo "<h2>SELAMAT DATANG di Sistem Informasi xxx</h2><br>";echo "Halaman ini dapat diakses tanpa user dan password";}

else{// Setting Menu berdasarkan level userif($_SESSION[level]=="User Biasa"){echo "Tampilan informasi yang bisa diakes <b>user biasa</b>";}}if($_SESSION[level]=="Administrator"){echo "Tampilan informasi yang bisa diakes

<b>administrator</b>";}?>

HasilHasil ManajemenManajemen ContentContentUmum

User Biasa

Administrator

Page 9: 4 - Pi (Php Lanjut)

3/25/2011

9

Secure session management with cookieSecure session management with cookieStrong session management is a key part of a secure web application. ppSince HTTP does not directly provide a session abstraction, application and framework developers must bake their own using cookies.

What Cookie??What Cookie??Most web application frameworks use client‐side cookies to index a state table on the server side.Session state is usually represented with a special‐purpose object type, stored on the server, and could contain anything relevant to the application:

user profile,user privileges,cached data from a back‐end store,browsing history and page flow state, orCSRF (Cross‐Site Request Forgery )prevention tokens.

Page 10: 4 - Pi (Php Lanjut)

3/25/2011

10

Create CookieCreate CookieMenggunakan function setcookieDideklarasikan sebelum tag htmlDideklarasikan sebelum tag htmlSyntax :setcookie(name, value, expire, path, domain);

Contoh :<?phpsetcookie(“user”, “Aman Khan”, time()+3600);?>?>

<html>

. . . .

Retrieve CookieRetrieve Cookie• Menggunakan $_COOKIE variablenama variabel cookie = usernama variabel cookie   user<?php// Print a cookieecho $_COOKIE["user"];

// A way to view all cookiesprint_r($_COOKIE);?>

Page 11: 4 - Pi (Php Lanjut)

3/25/2011

11

• Menggunakan fungsi isset<html><html><body>

<?phpif (isset($_COOKIE["user"]))echo "Welcome " . $_COOKIE["user"] . "!<br />";

elseecho "Welcome guest!<br />";

?>

</body></html>

MenghapusMenghapus CookieCookie• Dengan cara membuat expired cookie tersebut<?php// set the expiration date to one hour agosetcookie("user", "", time()-3600);?>

• Expired time = (‐) negatif, • Cookie telah expired 3600 detik atau 1 jam yang lalu

Page 12: 4 - Pi (Php Lanjut)

3/25/2011

12

MembuatMembuat beberapabeberapa cookiescookies<? //set beberapasetcookie("username[one]","ragil",time()+60 );setcookie("username[two]","saputra",time()+60) ;setcookie("username[three]","hadi",time()+60);echo "Cookie telah diset... <a href='lihatcookie.php'>cookie</a>";?>

<? //lihatcookie.phpecho "Cookie yang telah dikirimkan: <br>"; if (isset($_COOKIE["username"])){

while(list($index,$value) = each($_COOKIE["username"])){echo "Nama Ke-".$index." = ".$value."<br>";} }?>

HasilHasil CookiesCookies