usminuru
usminuru

Reputation: 341

How to use session inside webpages?

I am trouble with session; I know it theoretically but I encountered with it how to use session , transferring username to other page and adding logout in order to clear the current logged account information. Since I have no idea of session usage I commented it.

This is the checklogin.php

 <?php
    session_start();
    include("database.php");

    // username and password sent from form
    $name=$_POST['email'];
    $password=$_POST['pwd'];
    //select data from database

    $sql="SELECT * FROM $tbl_name WHERE usermail='$name' && userpasswd='$password'";
    $result=mysql_query($sql);

    // Mysql_num_row is counting table row
    $count=mysql_num_rows($result);

    // If result matched $myusername and $mypassword, table row must be 1 row

    if( $count == 1) {
        // Register $myusername, $mypassword and redirect to file "search.php"
        //session_register("$name");
        //session_register("$password");
        //$_SESSION['name']= $name;
        header("location:jcte/index.php");
    } else {
        $msg = "Wrong Username or Password. Please retry";
        header("location:ErrorPage.html");      
    }
?>

Upvotes: 0

Views: 119

Answers (3)

user3141441
user3141441

Reputation: 31

<?php
    session_start();
    $_SESSION['user']="Varma"; //intializing the session['user'];
    echo $_SESSION['user'];   // displaying the data  
    unset($_SESSION['user']); // destroying the session data.
?>

but you have to initialize session_start(); in all web pages where you have need to access that session variables.

Upvotes: 0

Deepu Sasidharan
Deepu Sasidharan

Reputation: 5309

After the line

$result=mysql_query($sql);

add

if ($data = mysql_fetch_array($result)) {
    $_SESSION['user'] = $data['usermail'];
}

Now session created.Call this session in jcte/index.php page as:

<?php
session_start();
echo "welcome $_SESSION['user']";
?>

Unset the session in logout.php page as:

<?php
session_start();
unset($_SESSION['user']);
?>

Upvotes: 1

Mahmood Rehman
Mahmood Rehman

Reputation: 4331

Always start session page with session_start().If you want to use session first assign session a value like this :

session_start();
$_SESSION['username'] = 'Mahmood';

And when you want to access get it like this :

echo $_SESSION['username'];
OR
$username = $_SESSION['username'];

And unset this session like this :

unset($_SESSION['username']);

Some Details are here.

Upvotes: 0

Related Questions