Hello

This is a simple php login script with sessions. It connects to mySQL for usernames and passwords.

I’m using a variation of the code from http://www.phpportalen.net/wiki/index.php?page=Enkel+Inloggning+med+Mysql+och+sessioner+-+Komplett+kod (index.php is the relevant part)

Here is my code (my script is called login.php):

<?php
session_start(); // Always at the top

include "conn.php"; // Databaseconnection
include "functions.php"; // Functions

// Login
if (isset($_POST['submit'])){

  $_POST = db_escape($_POST);

  $passwd = safepass($_POST['passwd']);
  $sql = "SELECT id FROM members
		 WHERE user='{$_POST['user']}'
		 AND pass='$passwd'";
  $result = mysql_query($sql);

  // Didn't find username and password
  if (mysql_num_rows($result) == 0){
	header("Location: login.php?badlogin=");
	exit;
  }

  // set session with unique index
  $_SESSION['sess_id'] = mysql_result($result, 0, 'id');
  $_SESSION['sess_user'] = $_POST['user'];
  
  // Log the logins  
  // $REMOTE_ADDR = PHP variable to get ip address
	$visitor_ip = $_SERVER["REMOTE_ADDR"];
	$sql = "INSERT INTO userlog(user, date, ipadress)
			VALUES('{$_POST['user']}', CURRENT_TIMESTAMP, '{$visitor_ip}')";
	mysql_query($sql);
  
  header("Location: valjtv.php");
  exit;
}

// Logout
if (isset($_GET['logout'])){
  session_unset();
  session_destroy();
  header("Location: login.php");
  exit;
}

?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Login</title>
<link rel="stylesheet" type="text/css" media="print" href="css/reset.css">
</head>
<body bgcolor="#C0C0FF">
		
	
<?php

		// If not logged in, let log in, else logut link
		if (!isset($_SESSION['sess_user'])){
	
		echo '

		

<table width="100%" border="0" align="center" cellpadding="0" cellspacing="0">
  <tr>
    <th><img src="img/Ikon.png" alt="" width="264" height="175" /></th>
  </tr>
</table>

<div id="login-box" align="center">
						<H2>Welcome!</H2>
						<p>Log in here.</p>
	
						<form action="login.php" method="post">
						Username:<br>
						<input type="text" name="user"><br>
						Password:<br>
						<input type="password" name="passwd"><br><br>
						<input type="submit" name="submit" value="Log in">
						</form>
</div>
				
		';
	
		// Wrong login message
		if (isset($_GET['badlogin'])){
			echo '<div id="fail-box">';
			echo "Wrong username or password.<br>\n";
			echo "Try Again.\n";
			echo '</div>';
		}
?>
		
		<div id="main">
		
		<?php

		} else {
		header("Location: valjTV.php");
		?>

<?php	}	?>
</body>
</html>

I’d like to make more sessions. I have checked the php manual, but I can’t make it work with session_name(), I’m probably doing it wrong.

What I have now is login1.php and login2.php. Each one connects to a different table in a mySQL database, but they both use the same session. Login2 is pretty much the same script with a few changed constants. So if user1, while being logged into session1, types in a link that’s supposed to be accessible only by user2, he accesses the webpage because it’s the same session.

I figure one has to name the sessions different names in order to make “separate” logins. I need two (eventually more) separate sets of users (mySQL tables) who are allowed access to two separate sets of web pages, ergo I need two seperate sessions.

I’ll appreciate any help

Recommended Answers

All 12 Replies

Can all users logged in to session1 also log in to session2 and can all users logged in to session2 also log in to session1?

My thinking is that instead of seperate logins, you can have security levels.

That failing, you can rename your session variables to SESS1_xxx and SESS2_xxx

I've never tried using the session names and never run across someone who has done so susscessfully... I know a few pretty decent coders who've tried and given up (which is why "ve never tried it).

Can all users logged in to session1 also log in to session2 and can all users logged in to session2 also log in to session1?

My thinking is that instead of seperate logins, you can have security levels.

That failing, you can rename your session variables to SESS1_xxx and SESS2_xxx

I've never tried using the session names and never run across someone who has done so susscessfully... I know a few pretty decent coders who've tried and given up (which is why "ve never tried it).

Yes, I mean it's one and the same session. I think having two sessions is what I need in order to do what i described. I don't know how to make different security levels, especially when they are actually on the same level- one user is not above the other, just has different privileges, and when I mess with the sess variables the thing just stops working.

On the other hand I know that I don't seem to know much... I've tried what I can do, so I'm pretty much looking for a handout code from someone with more experience.

If, when you rename session variables "the thing just stops working", then using session names will cause the same problem because every line of code that uses a session variable now has to use session_name.session_variable so that deadends us on a lot of fronts.

Security level is just another field in the users table and you assign a value to that and only let people perform certain tasks when their security level is => than what that task requires. Depending on how simple or complex your script is, that can be trivial or a major rewrite.

Not knowing more about what you're trying to do, I can't think of another answer for you. If you can't rename the session variables without breaking everything then you're pretty much need to back up and think about your problem how you're attempting to solve it.

If, when you rename session variables "the thing just stops working", then using session names will cause the same problem because every line of code that uses a session variable now has to use session_name.session_variable so that deadends us on a lot of fronts.

Security level is just another field in the users table and you assign a value to that and only let people perform certain tasks when their security level is => than what that task requires. Depending on how simple or complex your script is, that can be trivial or a major rewrite.

Not knowing more about what you're trying to do, I can't think of another answer for you. If you can't rename the session variables without breaking everything then you're pretty much need to back up and think about your problem how you're attempting to solve it.

Well, in theory, I understand completely what you're saying, but I have no idea how to proceed. I have (almost) never used sessions. I need code, not wisdom.

I think that making two sessions solves my problem, because if it's the wrong session, the user will get redirected to the login page for that session. If it's the right session, the user will be allowed access. It doesn't sound impossible to me, I just don't have the know-how. But there must be somebody out here who does.

By writing that the whole thing stops working I meant that if I mess with the sess_id and sess_user i'm redirected to /login.php?badlogin= because those variables are used for retrieving usernames and passwords from the database. Then again, maybe I'm doing it wrong. Besides, I don't want to pass different variables in the same session since the code uses a session to verify whether the user is logged in or not. So if it is the same session, the user will be let in. I don't understand how changing those variables would help me.

Every webpage needs the code below at the top to be "embraced" by the login.

<?php
session_start(); // Always at the top
// Check if logged in = session set
if (!isset($_SESSION['sess_user'])){
  header("Location: login2.php");
  exit;
}
?>

So lets say we have index that goes to login1 or 2, those go to separate sets of subpages, which all have that identifying code at the top, and since it's the same session, user2 can type in a link to subpage1 and get in. It's not rocket science, there must be an easy solution.

Also, I don't want major rewrites, since it's not my code and I don't fully understand how it works. If I did, I'd write my own script that does exactly what I want it to do. If your only recommendation is to try another approach, get all new code, make all new tables in databases and rewrite all subpages, I might just wait a little bit longer to let someone else answer my question before I do that.

Then why not just set a seperate session variable called SESSION_TYPE and in each of the login's you set it to

$_SESSION = 1; // OR
$_SESSION = 2;

Then you can just check if($_SESSION == 1|2) and do what you need to do... of course, my guess is this wont work and you'll discover why...

commented: good idea +1

Then why not just set a seperate session variable called SESSION_TYPE and in each of the login's you set it to

$_SESSION = 1; // OR
$_SESSION = 2;

Then you can just check if($_SESSION == 1|2) and do what you need to do... of course, my guess is this wont work and you'll discover why...

Thank you very much. Even though it's not exactly what I was looking for, it does the job.
Here's how I used it:

<?php
session_start(); // Always at the top
// Check if logged in = session set
if (!isset($_SESSION['sess_user'])){
  header("Location: login2.php");
  exit;
}
if($_SESSION['sess_type'] == 2 ){
echo '
HTMLCODE
';
}else echo 'You don\'t have permission to access this page.';
?>

and, of course, I added the variables in the login scripts.
I didn't know I could do that.
Is there a better way of doing it?
My main concern is that i have php code inside the html code, like this for example:

<table width="100%" border="0" align="center" cellpadding="0" cellspacing="0">
	  <tr>
		<th><img src="img/Ikon.png" alt="" width="264" height="175" /></th>
	  </tr>
	</table>
	<h2><?php echo "Hello " . $_SESSION['sess_user'] . "!<br/>";  ?></h2>
	<p>Subpage</p>

Update:
Lost my train of thought.
So if html is in php and there is php in html, I'll end up with php in php, which doesn't really work.
I could also close the echo, remove internal php tags and continue the html in another "if else", but I'm wondering if there's a better way to use your suggestion. And, yes, I do see that I can put it all on one page, in one script.
Sorry for being such a "newbie poster".

Nothing wrong with the way you did this... people integrate html inside of php scripts all the time, thats what it was designed for.

Update:
Lost my train of thought.
So if html is in php and there is php in html, I'll end up with php in php, which doesn't really work.
I could also close the echo, remove internal php tags and continue the html in another "if else", but I'm wondering if there's a better way to use your suggestion. And, yes, I do see that I can put it all on one page, in one script.
Sorry for being such a "newbie poster".

Ok im not sure where your coming from/what your talking about but...

Putting html in a php document doesn't make it php in php... most php documents that display stuff on a webpage look like this..

<html>
<head>
<!-- head stuff -->
</head>
<body>
<?php echo("something") ?>
<h1> asfunasjfina </h1>
</body>
</html>

Ect... its just a way of using dynamic information. And stuff that your don't want rendered on the page thats in php goes like this...

<?php 

<!-- PHP code -->

?>
<html>
<!-- ECT -->

Ok im not sure where your coming from/what your talking about but...

Putting html in a php document doesn't make it php in php... most php documents that display stuff on a webpage look like this..

<html>
<head>
<!-- head stuff -->
</head>
<body>
<?php echo("something") ?>
<h1> asfunasjfina </h1>
</body>
</html>

Ect... its just a way of using dynamic information. And stuff that your don't want rendered on the page thats in php goes like this...

<?php 

<!-- PHP code -->

?>
<html>
<!-- ECT -->

Comment tags! Of course! I knew I shouldn't have posted at 4 a.m.
I fixed it like this:

<?php
session_start(); // Always at the top
// Check if logged in = session set
if (!isset($_SESSION['sess_user'])){
header("Location: login2.php");
exit;
}
if($_SESSION['sess_type'] == 1 ){
echo '
HTMLCODE PART1
'
 . "Hello " . $_SESSION['sess_user'] . "!<br/>" . 
'
HTMLCODE PART2
';
}else echo 'You don\'t have permission to access this page.';
?>

The problem is pretty much solved, but the thread isn't. I'm gonna hold out a little bit longer for someone who might make the separate sessions work. I'd like to learn how to do that.
Otherwise the credit goes to ppetree.
Thank you

So.. sorry to rez a 10 month old post, especially as my first post... but here goes...

I dont think that using sessions the way you are is the best method... instead, you should declare in your SQL DB what security level, or what options, the user will have, based on their initial sign up/register.

So.. a table would be something like...
usrID, login, securty_level

So, what the user logs in, you can store a session variable $_SESSION['sec_level']=$blah

using something as simple as numeric identifiers for their level of involvement.... if ('sec_level')==1 then basic commands.. if ==2 then more advanced, and so on and so forth...
Or you could even use language constructs - clearance1, clearance2.... this way, you can even offer scalability in the future, and you are not necessarily making 2 whole websites, just choosing which functions are available to which users...

If you want, you can even dedicate a full table to security...
userID, security_level

In this instance, you can assign multiple levels to the same individual, and check against what rank they have.. if they are a 1 and 2, they get both. If they are just a 1... or just a 2...

Then, include a file that will run a function based on what security level they have... it can be something as simple as changing the query allowed, but under two different function names...

Just my 2 cents...

ryan

Hi There, if I'm understanding your issue correctly, I think exploring the concept of URL parameters will be helpful.
While logging in, you can add a URL parameter that uniquely identifies the user (for example user_id from your database) and since the parameter stays in the link, you can always retrieve it to get the correct details for the user accessing the system. This would work, even if a different user logs into your system, since the link shall be different for the two because they have separate URL parameters.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.