[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 530
  • Last Modified:

Simple session example

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
tantan6611
Asked:
tantan6611
  • 8
  • 6
  • 4
10 Solutions
 
Robin HickmottSoftware DeveloperCommented:
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
 
Robin HickmottSoftware DeveloperCommented:
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
 
psimationCommented:
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
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
tantan6611Author Commented:
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
 
Robin HickmottSoftware DeveloperCommented:
---------------------
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
 
tantan6611Author Commented:
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
 
Robin HickmottSoftware DeveloperCommented:
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
 
psimationCommented:
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
 
tantan6611Author Commented:
ok this is fine
but what about if I wanna pass the $username to a fourth page linked with the main.php page?
0
 
psimationCommented:
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
 
psimationCommented:
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
 
tantan6611Author Commented:

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
 
Robin HickmottSoftware DeveloperCommented:
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
 
tantan6611Author Commented:
rhickmott,
What code does the session.php file contain ?
0
 
Robin HickmottSoftware DeveloperCommented:
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
 
Robin HickmottSoftware DeveloperCommented:
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
 
tantan6611Author Commented:
That's pretty good,
But what about setting the session time, e.g. if I wanna set session time for 1 hour?
0
 
Robin HickmottSoftware DeveloperCommented:
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

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

  • 8
  • 6
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now