Mansour Fahad
Mansour Fahad

Reputation: 48

handling with multiple sessions in php

I have a basic knowledge about websites programming. I want to create a website that has two applications on the same domain. The first would be for the users and the second one would be for the Administrator which is me. That will benefits me to do thing and manage the website without sign in to the database. The question is how to handle with these two session. I tried to use session_name before session_start but it doesn‘t work. I need help to make every session on its own independent side, so they dont mix up with each other. And another question. Is this the right way to set a session when you have multiple?

$_SESSION[$variable] = $variable.

EDIT: Still not working. This is my code:

<?php
@$admin = $_POST['admin'];
@$password = $_POST['password'];

if(empty($admin) OR empty($password)) {
echo 'You need to fill all the spaces.';
}

if (!empty($admin) AND !empty($password)) {
    mysql_connect('localhost','root','');
    mysql_select_db('job');
    $tip0 = mysql_query("SELECT admin, password FROM admin WHERE admin = '".mysql_real_escape_string($admin)."' AND password = '".md5($password)."'");
    if(mysql_num_rows($tip0)==TRUE) {
    $_SESSION['admin']['login'] = $admin;
    header('location:administrator.php');
    echo 'Session has been created';
    }
    elseif(mysql_num_rows($tip0)==FALSE) {
    echo 'There is no admin.';
    }

}

?>


<html>
<body>

<form action="admin_login.php" method="POST"></input><br />
Admin: <input type="text" name="admin"></input><br />
Password: <input type="password" name="password"></input><br />
<input type="submit"></input>

</form>
</body>
</html>

And this is the redirect page:

    <?php
session_start();

if (isset($_SESSION['admin']['login'])) {
echo 'Here we go.';
}
elseif(!isset($SESSION['admin']['login'])) {
echo 'Not found';
}

?>

Upvotes: 0

Views: 10749

Answers (3)

Arjan
Arjan

Reputation: 66

Sessions can only be used after session_start(); You can make an array in a array for this to work. You could try something like this:

$_SESSION['user']['name'] = 'Something';
$_SESSION['user']['email'] = 'Something';

And for admin:

$_SESSION['admin']['something'] = 'Something';

EDIT: Remember you use session_start(); on EVERY page you use sessions. Looks like you forgot that on the first page.

Upvotes: 3

Waqar Alamgir
Waqar Alamgir

Reputation: 9968

I would prefer this:

Website:

define('SES_PREFIX' , 'website-');
$_SESSION[ SES_PREFIX . 'user'] = 'waqar';

Admin:

define('SES_PREFIX' , 'admin-');
$_SESSION[ SES_PREFIX . 'user'] = 'admin';

This will allow you to deploy multiple copies of the same application on same domain.

Upvotes: 1

Serge Kuharev
Serge Kuharev

Reputation: 1052

Why don't you use $_SESSION['admin'][] for storing admin related variables?

For example, $_SESSION['admin']['login'] = 'Mansour Fahad';

Upvotes: 1

Related Questions