PHP Session (PHPS)

When we browse a website, for example e-mail, we will be asked to enter a username and password. This procedure is only done once at the beginning of the process. Then the system will 'remember' our identity, and display the appropriate information. Without a session, the system will be wrong and display confidential data to the wrong person.

A. No Session 

To understand the usefulness of sessions, we will create an application without sessions. We need one web page and three php scripts: login.htm, loginNoSession.php, welcomeNoSession.php and displayNoSession.php

login.htm

<html>

<head>
<title>Login</title>
</head>

<body>

<h1>Login </h1>
<form method="POST" action="loginNoSession.php">
  <table border="1" width="44%">
    <tr>
      <td width="27%">user : </td>
      <td width="73%"><input type="text" name="login" size="20"></td>
    </tr>
    <tr>
      <td width="27%">password : </td>
      <td width="73%"><input type="text" name="pass" size="20"></td>
    </tr>
    <tr>
      <td width="27%">&nbsp;</td>
      <td width="73%"><input type="submit" value="Submit" name="B1"><input type="reset" value="Reset" name="B2"></td>
    </tr>
  </table>
</form>
<p><a href="register.htm">Daftar</a></p>

</body>

</html>

loginNoSession.php

<?
  // -- cek user dan password -- //

  if($login == "endy" && $pass =="test"){
    header("Location: welcomeNoSession.php?user=endy");   }elseif($login == "oky" && $pass =="coba"){     header("Location: welcomeNoSession.php?user=oky");
  }else{
    echo("User dan password salah");
  }
?>

welcomeNoSession.php

<?
 echo("Welcome $user <br>");
  echo("<a href=\"displayNoSession.php?user=$user\">");   echo("klik di sini untuk mengakses daftar kenalan anda</a>");
?>

displayNoSession.php

<?
$dbUser = "endy";
$dbPass = "test";
$db = "latihan";
$server = "localhost";

// membuat koneksi
$koneksi = mysql_connect($server, $dbUser, $dbPass);

// memeriksa koneksi if(!$koneksi){
  echo("Koneksi ke database gagal");   exit;
}

// membuka database mysql_select_db($db);

// membuat query dan mengakses hasil
$query = "SELECT * FROM UserData WHERE user='$user'";
$hasil = mysql_query($query);

// menampilkan hasil echo("<table border=1>"); echo("<tr>");
echo("<td>NamaTeman</td>"); echo("<td>Keterangan</td>"); echo("</tr>");
while($row = mysql_fetch_array($hasil)){   echo("<tr>");
  echo("<td>".$row["namaTeman"]."</td>");   echo("<td>".$row["keterangan"]."</td>");   echo("</tr>");
}
echo("</table>");
?>

This code requires contact data taken from the UserData table with the following definition:

CREATE TABLE userData (   user VARCHAR(50),   namaTeman VARCHAR(50),   keterangan VARCHAR(50)
);

and sample data as follows:

INSERT INTO userData VALUES (
  'endy',
  'Imanudin',
  'Teman ceting'
);

INSERT INTO userData VALUES (
  'oky',
  'Iswahyudi',
  'Pak Lurah kos adhyaksa'
);

INSERT INTO userData VALUES (
  'oky',
  'Anton Raharja',
  'Rekan kerja di kantor'
);

INSERT INTO userData VALUES (
  'endy',
  'Widya Andhini',
  'Gebetan lama tapi masih mesra'
);

Application path: 

login with user = oky and password = coba

Click the link to display the output, the display will appear as follows:

Now, we will "fake" the link in the address bar to display endy's user data. Open a new browser and enter the following link in the address bar:

http://localhost/latihan/displayNoSession.php?user=endy

Then press enter.

Ooopss… easily confidential data will appear. The way to prevent this from happening is to ask the user to enter the login and password every time he changes pages. But of course this method is annoying for the user. In addition, passing the login and password variables on each page is very insecure and vulnerable to eavesdropping. That's why we use sessions.

B. Session concept 

Session works like a supermarket drop-off point. We come in, leave our belongings, and the clerk will give us an ID.

When we want to take an item, we give a sign to the officer, and the officer will be able to take the item that was deposited without exchanging it with someone else's item.

The problem that occurs is how the "identity tag" will be stored on each page accessed by the user, so that it can be accessed by the system every time the user clicks on a link. 

There are three alternatives that can be used to store session data: 

  • Cookie
  • Hidden Form
  • URL Embedding

C. Implementation: Cookies 

Cookies are information stored on a user's browser. The script runs the setcookie function which will write data to the user's hard disk. Cookies are written to the user's browser using the command: 

setcookie("sessionId", "1234");

After that, the $sessionId variable will be available every time the user's browser accesses the system. The cookie will disappear from the user's browser after passing the specified expiration period or being deleted via the command:

setcookie("sessionId");

This approach has been controversial. Because cookies can eliminate user privacy and potentially contain viruses. Therefore, users can disable cookies through browser settings.

Thus, this approach is less reliable to be applied to our application. To see more clearly the implementation of cookies, we will modify the application above as follows:

login.htm

<form method="POST" action="loginSessionCookie.php">

loginSessionCookie.php

<?
  // -- cek user dan password -- //    if($login == "endy" && $pass =="test"){     setcookie("user", $login);
    header("Location: welcomeSessionCookie.php");   }elseif($login == "oky" && $pass =="coba"){     setcookie("user", $login);
    header("Location: welcomeSessionCookie.php");
  }else{
    echo("User dan password salah");
  }
?>

welcomeSessionCookie.php

<? if(!$user){
  echo("Illegal Access");   exit; }
echo("Welcome $user <br>");
echo("<a href=\"displaySessionCookie.php\">"); echo("klik di sini untuk mengakses daftar kenalan anda</a>");
?>

add the following line at the top of displayNoSession.php and save as displaySessionCookie.php

if(!$user){
echo("Illegal Access");
exit;
}

To test it, open a new browser and enter the following link in the address bar:

http://localhost/latihan/displaySessionCookie.php

Then press enter. You will get:

Now, disable cookies by:

Click Tools – Internet Options

Click the Security tab and click the Custom Level button.

click disable cookies

try again to access the contact page. You will get Illegal Access.

D. Implementation: Hidden Form

The second way to save session data is to save the data in a hidden input in the form. For example, by using the code: 

<input type="hidden" name="user" value="$user">

This method also cannot be done in all conditions, because there are times when we cannot use the form.

E. Implementation: URL Embedding  

The last surefire way is to "stick" the session variable in the link/URL. For example, the link to welcome.php is modified to welcome.php?sessionId=1234.

The only downside to this method is that the URL link becomes un-bookmarkable. In addition, the link becomes unsightly. But technically, this method is the most effective and reliable.

F. Implementation: Session API 

The PHP Session API combines cookie techniques and URL Embedding techniques. If the user activates cookies, PHP will store session data in the cookie. However, if the user deactivates cookies, PHP will store session data in the URL. This mechanism occurs automatically if PHP is compiled with the --enable-trans-sid option.

How to use PHP Session API can be seen in loginSessionApi.php, welcomeSessionApi.php, and displaySessionApi.php. You can modify Internet Explorer settings to see that this method can be run even though cookies are disabled. We also cannot type the URL directly.

http://localhost/latihan/displaySessionApi.php

to open a personal page.

loginSessionApi.php:

<?
  // -- cek user dan password -- //    if($login == "endy" && $pass =="test"){     session_start();      $user = $login;     session_register("user");
    header("Location: welcomeSessionApi.php");   }elseif($login == "oky" && $pass =="coba"){     session_start();      $user = $login;     session_register("user");
    header("Location: welcomeSessionApi.php");
  }else{
    echo("User dan password salah");
  }
?>

welcomeSessionApi.php 

<?
session_start();
if(!session_is_registered("user")){   echo("Illegal Access");   exit; }
echo("Welcome $user <br>");
echo("<a href=\"displaySessionApi.php\">"); echo("klik di sini untuk mengakses daftar kenalan anda</a>");

?>

displaySessionApi.php

<? session_start();
if(!session_is_registered("user")){   echo("Illegal Access");   exit;
}
$dbUser = "endy";
$dbPass = "test";
$db = "latihan";
$server = "localhost";

// membuat koneksi
$koneksi = mysql_connect($server, $dbUser, $dbPass);

// memeriksa koneksi if(!$koneksi){
  echo("Koneksi ke database gagal");   exit;
}

// membuka database mysql_select_db($db);

// membuat query dan mengakses hasil
$query = "SELECT * FROM UserData WHERE user='$user'";
$hasil = mysql_query($query); echo($sessionId); // menampilkan hasil echo("<table border=1>"); echo("<tr>");
echo("<td>NamaTeman</td>"); echo("<td>Keterangan</td>"); echo("</tr>");
while($row = mysql_fetch_array($hasil)){ echo("<tr>");
echo("<td>".$row["namaTeman"]."</td>"); echo("<td>".$row["keterangan"]."</td>"); echo("</tr>");
  }
echo("</table>");

?>

Post a Comment

Previous Next

نموذج الاتصال