Jump to content

Need help understanding $_SESSION


Cued4

Recommended Posts

First you need to register your session ( means login ) then you can enter a page. Example :

 

This is my login.php and you will be redirected to the dashboard.php

 

<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="root"; // Mysql password
$db_name="gb"; // Database name
$tbl_name="users"; // Table name

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form
$username=$_POST['username'];
$password=$_POST['pwd'];

// To protect MySQL injection (more detail about MySQL injection)
$username = stripslashes($username);
$pwd = stripslashes($password);
$username = mysql_real_escape_string($username);
$pwd = mysql_real_escape_string($password);

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

// Mysql_num_row is counting table row
$count = mysql_num_rows($result);
// If result matched $username and $pwd, table row must be 1 row

if($count==1){
session_start();
session_register("username");
session_register("pwd");
header("location:dashboard.php");
}
else {
echo "Wrong Username or Password";
}
?>

 

If you try to go to dashboard.php without login you will be redirected to the login page.

 

<?php

//start the session
session_start();

//check to make sure the session variable is registered

if(isset($_SESSION['username']))
{
    print("You're an admin. Do whatever you want !  ");
}
else
{
    header( "Location:login.html" );
}

?> 

LOL, ^^^. I'll second that.

 

session_register() was depreciated a really long time ago (8 years) when the $_SESSION array was introduced in favor of it, finally throws a deprecated error message in php5.3, and is scheduled to be completely removed in the next major release of php. Don't use any code that is using session_register()

ok, i will try to explain to you how SESSIONS work as fast and short as possible.

 

also... at the top of every page/code where you use SESSION variables you need to put this command on top of the code:

 

session_start();

 

then after that you can define a new session like this:

 

$_SESSION['thenameofthesessionyouwant'] = 'whatyouwantittobe';

 

and then you use the session always like this:

 

echo $_SESSION['thenameofthesessionyouwant'];

// and this will output whatyouwantittobe in this case.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.