Solved

Simple session example

Posted on 2007-03-22
18
500 Views
Last Modified: 2013-12-13
I am really new to php and Mysql
 I want to know how to use sessions in order to send username var from page to page in a simple way
I have three files through which I want to make simple example of a session
My target is to echo the username by the main.php file through session username var registration.
what code should I add to these three files in order to do this?

---------------------
userloginform.php
---------------------

<html>
<head>
<title>Users Login Pgae</title>
</head>
<body>

<form action="userlogin.php" method="post">
Username: <input type="username" name="username" />
password: <input type="password" name="password" />
<input type="submit" />
<p>&nbsp;</p>
</form>

</body>
</html>
-----------------
userlogin.php
-----------------
<?php
error_reporting(E_ALL);
?>

<html>
<head>
<title>Login</title>
</head>
<body>

<?php

$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
 
  mysql_select_db("my_db", $con);

$username = mysql_real_escape_string($_POST["username"]);
$password = mysql_real_escape_string($_POST["password"]);


$result = mysql_query("SELECT * FROM users
WHERE (   username = '$username' ) and (  password = '$password' )  ");

if ($row = mysql_fetch_array($result))
   
{

echo "welcome " . $username . " !";
echo "<br>";
echo "<a href='main.php'>Click here to go to the main page</a>";

} else {

echo "Incorrect username or password";
echo "<br>";
@include("userloginform.php");

}


?>

</body>
</html>
--------------------
main.php
--------------------


<?php

echo "your username is: " . $username . " ."

?>


0
Comment
Question by:tantan6611
  • 8
  • 6
  • 4
18 Comments
 
LVL 13

Assisted Solution

by:rhickmott
rhickmott earned 320 total points
ID: 18769912
At the top of your PHP page before anything else put in

<?php
    session_start();
?>

This will start the session on each of your pages.

When the username is correct do.

$_SESSION['username'] = $username;

This then saves it in the session so its accessable from anywhere you have the sesison active so on your last page you can do.

<?php
       session_start();
       $username = $_SESSION['username'];
       echo "your username is: " . $username . " .";
?>

you can also use a

is (!isset($_SESSION['username'])) {
      echo("Your not legged in!");
     exit();
}

else {
    echo("Welcome $username");
}

style of design too :)

Other handy hints are

unset($_SESSION['username']);

to remove the value and

session_destroy();

To kill the complete session.
0
 
LVL 13

Expert Comment

by:rhickmott
ID: 18769921
More information on

http://www.tizag.com/phpT/phpsessions.php :)

Sessions are easy once you get started the main pitfalls are

1) Starting the session AFTER something has been output so be very careful there are no whitespaces ( Spaces or blank lines) above your <?php tag. Also if you make includes of other PHP files make sure they also have no whitespace before the <?php

Any whitespace, echos or output will be interpreted as HTML or text and PHP will have to send headers of some description to the browser in order to output that qhitespace so any session_starts it then encounters will make it throw a hissy fit.
0
 
LVL 17

Accepted Solution

by:
psimation earned 180 total points
ID: 18769946
Here is a VERY simple example I usually work from; it doesn't use a DB query, but it should be very easy to do that yourself.

Basically I start off like this:

The index.php file does the checking ( and basically EVERY other page has the same "header"):

<?php
session_start();
if ($_SESSION['isgood'] <> "accept") {
header("Location: sorry.php");
exit;
}
# rest of page code follow below
?>

Then, I have this page called "sorry.php" which does the actual checking ( so you should just modify this page to do the sql query for the posted vars.

<?php
session_start();
if (($_POST[username] == "XXX") && ($_POST[password] == "YYY")) {
$_SESSION['isgood'] = "accept";
header("Location: index.php");
} else {
echo '
<form action="sorry.php" method="POST">
<table>
  <tbody>
    <tr>
      <td>Please Log in:</td>
      <td>  </td>
    </tr>
    <tr>
      <td>Username</td>
      <td><input type="text" name="username">  </td>
    </tr>
    <tr>
      <td>Password</td>
      <td><input type="password" name="password">  </td>
    </tr>
    <tr>
      <td>  </td>
      <td><input type="submit" name="submit">  </td>
    </tr>
  </tbody>
</table>
</form>
';
}

?>
So, just exchange the if {} statement in my "sorry.php" code with your sql to check the post vars against your table, and add the "header" code to any page you want to be "password protected".
0
 

Author Comment

by:tantan6611
ID: 18770045
Thank you rhickmott and psimation for the fast reply...
However, I am partially aware about the the session concepts you mentioned
but what confuses me is how to apply these commands in my file codes
Can you help me and clarify this through placing the right code inside the codes of the previously included three files of my first post.

Your help is much appreciated.
0
 
LVL 13

Assisted Solution

by:rhickmott
rhickmott earned 320 total points
ID: 18770089
---------------------
userloginform.php
---------------------
<html>
<head>
<title>Users Login Pgae</title>
</head>
<body>

<form action="userlogin.php" method="post">
Username: <input type="username" name="username" />
password: <input type="password" name="password" />
<input type="submit" />
<p>&nbsp;</p>
</form>

</body>
</html>

-----------------
userlogin.php
-----------------
<?php
      error_reporting(E_ALL);
      session_start();
?>

<html>
<head>
<title>Login</title>
</head>
<body>

<?php

      $con = mysql_connect("localhost","root","");
      if (!$con) {
              die('Could not connect: ' . mysql_error());
        }
 
        mysql_select_db("my_db", $con);

      $username = mysql_real_escape_string($_POST["username"]);
      $password = mysql_real_escape_string($_POST["password"]);

      $result = mysql_query      ("      SELECT * FROM users
                              WHERE (   username = '$username' ) and (  password = '$password' )  
                        ");

      if ($row = mysql_fetch_array($result))
   
      {
               // Correct Password
               $_SESSION['username'] = $username;
               $_SESSION['password'] = $password;
            header("Location: main.php");
            exit();

      }
      
      else {
                 // Incorrect Password
                 unset ($_SESSION['username']);
                 unset ($_SESSION['password']);
                 echo "Incorrect username or password";
            echo "<br>";
            @include("userloginform.php");
      }

?>

</body>
</html>




--------------------
main.php
--------------------
<?php

      session_start();

      if (isset($_SESSION['username']) && isset($_SESSION['password']) {
           // User has logged in!
          $username = $_SESSION['username'];
          $password = $_SESSION['password'];
          echo "your username is: " . $username . " ."
      }
      else {
          // User is not legged in!
          echo "Not logged in!";
          echo "<br>";
          @include("userloginform.php");
      }

?>
0
 

Author Comment

by:tantan6611
ID: 18771123
Hi rhickmott
The userlogin.php is giving me :

Warning: Cannot modify header information - headers already sent by (output started at userlogin.php:12) in userlogin.php on line 34

when I enter a correct username and password.
0
 
LVL 13

Assisted Solution

by:rhickmott
rhickmott earned 320 total points
ID: 18771161
Sorry my bad :)

<?php
      error_reporting(E_ALL);
      session_start();

      $con = mysql_connect("localhost","root","");
      if (!$con) {
              die('Could not connect: ' . mysql_error());
        }
 
        mysql_select_db("my_db", $con);

      $username = mysql_real_escape_string($_POST["username"]);
      $password = mysql_real_escape_string($_POST["password"]);

      $result = mysql_query      ("      SELECT * FROM users
                              WHERE (   username = '$username' ) and (  password = '$password' )  
                        ");

      if ($row = mysql_fetch_array($result))
   
      {
               // Correct Password
               $_SESSION['username'] = $username;
               $_SESSION['password'] = $password;
            header("Location: main.php");
            exit();

      }
     
      else {
                   // Incorrect Password
                unset ($_SESSION['username']);
                unset ($_SESSION['password']);
               
            echo      ("      <html>
                        <head>
                        <title>Login</title>
                        </head>
                        <body>

                        Incorrect username or password <br />
                  ");
            
               
                  @include("userloginform.php");
                  
                  echo      ("      </body>
                        </html>
                  ");
      }

?>
0
 
LVL 17

Assisted Solution

by:psimation
psimation earned 180 total points
ID: 18771171
That's because you cannot use the header() function if there are already any otheroutput on your page. If you want to use the heade() function to redirect , you have to make sure that it is right at the top of your code, or that NOTHING that precedes it causes ANY output. Looking very briefly at your code, the bit of html

------
<html>
<head>
<title>Login</title>
</head>
<body>
-----
is the first suspect, You may need to put that in an "echo" statement as well as nest it in an "if" statement to prevent it being "echoed" if you need the page to redirect...
0
 

Author Comment

by:tantan6611
ID: 18771291
ok this is fine
but what about if I wanna pass the $username to a fourth page linked with the main.php page?
0
Get up to 2TB FREE CLOUD per backup license!

An exclusive Black Friday offer just for Expert Exchange audience! Buy any of our top-rated backup solutions & get up to 2TB free cloud per system! Perform local & cloud backup in the same step, and restore instantly—anytime, anywhere. Grab this deal now before it disappears!

 
LVL 17

Assisted Solution

by:psimation
psimation earned 180 total points
ID: 18771309
if ($row = mysql_fetch_array($result))
   
      {
               // Correct Password
               $_SESSION['username'] = $username;
               $_SESSION['password'] = $password;
            header("Location: main.php");
            exit();

      }
takes care of that; the variables have been registered into session now; on any other page you want to access these variables, just make sure you have session_start() at the top of the page.
0
 
LVL 17

Assisted Solution

by:psimation
psimation earned 180 total points
ID: 18771320
ie. on your 4th page, just put session_start(); at the top, and then call the variables by their proper session names:
$_SESSION['username'] :


0
 

Author Comment

by:tantan6611
ID: 18771865

Gee it's working ...  :^)
Now; if I wanna to end the session it would be through , a log out page containing session_destroy(); isn't it?
And how to make a session expires after certain time interval?


 
0
 
LVL 13

Assisted Solution

by:rhickmott
rhickmott earned 320 total points
ID: 18771907
Yup :)

The session should time out on its own after 30 minutes this is a PHP setting but other than that you can store a timer like $_SESSION['timer'] = time() in the session and check it when you load the page.

What i normally do is have the session initalisation and check in one file called session.php

If you include it in your pages with include_once("session.php") then the authentication system will work across all your scripts without having to copy code and any page you arrive at wont have to check if the yuser is logged in or display a "not logged in message"
0
 

Author Comment

by:tantan6611
ID: 18773937
rhickmott,
What code does the session.php file contain ?
0
 
LVL 13

Assisted Solution

by:rhickmott
rhickmott earned 320 total points
ID: 18774018
Well effectivly

==================

<?php
      
      session_start();

      if (isset($_SESSION['username']) && isset($_SESSION['password']) {
           // User has logged in!
          $username = $_SESSION['username'];
          $password = $_SESSION['password'];
          echo "your username is: " . $username . " ."
      }
      else {
         
          // User is not legged in!
           echo      ("      <html>
                    <head>
                    <title>Login</title>
                    </head>
                    <body>

                    Incorrect username or password <br />
                ");
                    
                      
          @include("userloginform.php");
                          
          echo      ("      </body>
                              </html>
                        ");
                       
             exit();
      }
     
     
?>




then you can do main2 for example as

main2.php

<?php
        include ("session.php");
        echo("Hello " . $_SESSION['username']);
?>

If the user is logged in they will see "Hello Username" if not they will be presented with a login.
0
 
LVL 13

Assisted Solution

by:rhickmott
rhickmott earned 320 total points
ID: 18774034
sorry that should be

session.php
==================
<?php
     
      session_start();

      if (!isset($_SESSION['username'])) {
          // User is not logged in!
           echo      ("      <html>
                    <head>
                    <title>Login</title>
                    </head>
                    <body>

                    Incorrect username or password <br />
                ");
                   
          @include("userloginform.php");
                         
          echo      ("      </body>
                              </html>
                        ");
             exit();
      }
     
?>

main2.php
=========

<?php
        include ("session.php");
        echo("Hello " . $_SESSION['username']);
?>

If the user is logged in they will see "Hello Username" if not they will be presented with a login.
0
 

Author Comment

by:tantan6611
ID: 18774509
That's pretty good,
But what about setting the session time, e.g. if I wanna set session time for 1 hour?
0
 
LVL 13

Expert Comment

by:rhickmott
ID: 18775679
Put in something like at the end

        if (isset($_SESSION['time']) && time() - $_SESSION['time'] > 1800) {
                  // Session Has Expired
                  $_SESSION = array();
             
            // Expire Session
                 echo      ("    <html>
                                <head>
                                <title>Login</title>
                                </head>
                                <body>

                                Session Expired <br />
                         ");
                   
                     @include("userloginform.php");
                         
                echo      ("      </body>
                                    </html>
                              ");
                       
                   exit();
        }
          else {
              $_SESSION['time'] = time();    
        }      
0

Featured Post

Complete Microsoft Windows PC® & Mac Backup

Backup and recovery solutions to protect all your PCs & Mac– on-premises or in remote locations. Acronis backs up entire PC or Mac with patented reliable disk imaging technology and you will be able to restore workstations to a new, dissimilar hardware in minutes.

Join & Write a Comment

Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now