We're a community of 1.1M IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,080,620 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Login, Redirect Multiple Users in PHP

I am working on login form where multiple users can sign in using their username and password. Depending on who it is, it will take them to certain file or link depending on how we set it for that user (john.doe goes to test1.php and jane.doe goes to test2.php).

When I try to login with username and password, it won't take me to the page. It keep saying the page has a redirect loop and it timed out. Also, how do I secure a page where once I logout, I can't go back to it by using the back button or type in the url directly? Please help. Thank you in advance. Here is what I have so far:

SQL has 4 fields

Field      Type         Collation           Null   Extra
id         int10                            No     auto_increment
username   varchar20    latin1_swedish_ci   No
password   varchar20    latin1_swedish_ci   No
redirect   varchar250   latin1_swedish_ci   No

I have 4 php files I work with. workspace.php, workspace_login.php, workspace_logout.php, workspace_files.php.

workspace.php - login screen

<form name="form" method="post" action="workspace_login.php">
<table>
<tr><td>Login</td></tr>
<tr><td>Username: <input name="username" type="text" style="width:215px" autocomplete="off"></td></tr>
<tr><td>Password: <input name="password" type="password" style="width:215px" autocomplete="off"></td></tr>
<tr><td><input type="submit" name="submit" value="Login"></td></tr>
</table>
</form>

workspace_login.php - login script

workspace_login.php - login script
<?php 
$host="localhost"; // Host name 
$username="*****"; // Mysql username 
$password="******"; // Mysql password 
$db_name="*****"; // Database name 
$tbl_name="workspace"; // 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['password']; 

// To protect MySQL injection (more detail about MySQL injection) 
$username = stripslashes($username); 
$password = stripslashes($password); 
$username = mysql_real_escape_string($username); 
$password = mysql_real_escape_string($password); 
$sql = "SELECT * FROM $tbl_name WHERE username='$username' and password='$password'"; 
$result = mysql_query($sql); 

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

// If result matched $username and $password, table row must be 1 row 
if($count == 1){ 
    // Register $username, $password and redirect to file "workspace_success.php" 
    $_SESSION['username'] = $username; 
    $_SESSION['password'] = $password; 
    // get the result set from the query
    $result = mysql_fetch_array($result); 
    // get the redirect column's value
    $redirect = trim($result['redirect']); 
    if ($redirect == '') {
        echo "No redirect value was set!";
    } else {
        header('Location: ' . $redirect);
        exit;
    }
} else { 
     echo "Wrong Password!";
} 
?>

workspace_logout.php - logout script

<?php
session_start();
$username=$_SESSION['username'];

if (session_destroy()){
unset($username);
}

if($username=="")
{
header("Location: workspace.php");
exit();
}
?>

workspace_files.php

<?php
session_start();
if (!isset($_SESSION['username'])) {
header('Location: workspace_files.php');
}
?>
<html>
<head>
<title>Secured Page</title>
</head>
<body>
<p>Welcome <b><?php echo $_SESSION['username']; ?></b>
Information here.</p>
<p><a href="logout.php">Logout</a></p>
</body>
</html>
6
Contributors
75
Replies
2 Months
Discussion Span
7 Months Ago
Last Updated
76
Views
diablo4151
Light Poster
36 posts since Aug 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

first thing, you need to add the following code to all the page so that the website will detect whether is login or not..if login,then allow to go to the page,if not,go back to workspace.php

<?php
session_start();
if (!isset($_SESSION['username'])) {
header('Location: workspace.php');
}
?>

Second thing,try to change the code in workspace_login.php (line 40) to this:

header("Location: $redirect");
devianleong
Light Poster
44 posts since Dec 2011
Reputation Points: 10
Solved Threads: 1
Skill Endorsements: 0

Devianleong,

I changed and added everything like you said. Now that I try to log in, it just bring me right back to workspace.php. No errors or taking me to the redirect page.

In mySql under redirect, I just put in the file location which is workspace_files.php. Almost feel like if it is not registering the session.

Thanks,

diablo4151
Light Poster
36 posts since Aug 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

Hi diablo4151,

before you can use any session variables (line 30 workspace_login.php) you must use session_start();

You are correct that the username is not being set as a session variable (for the above reason) so when this is checked for, and not found, you are redirected to workspace.php

Zagga
Posting Whiz
388 posts since Dec 2009
Reputation Points: 45
Solved Threads: 81
Skill Endorsements: 4

Zagga,

Still not working. I did added session_start(); yesterday as I realized it after my post but still redirecting to workspace.php.

Do I even this these line in the file since I am keeping track of who is signing in?

// Register $username, $password and redirect to file "workspace_success.php" 
$_SESSION['username'] = $username; 
$_SESSION['password'] = $password;

Here is what I hvae for workspace_login.php again.

<?
//Start session
session_start();

$host="localhost"; // Host name 
$username="*****"; // Mysql username 
$password="*****"; // Mysql password 
$db_name="*****"; // Database name 
$tbl_name="workspace"; // 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['password']; 

// To protect MySQL injection (more detail about MySQL injection) 
$username = stripslashes($username); 
$password = stripslashes($password); 
$username = mysql_real_escape_string($username); 
$password = mysql_real_escape_string($password); 
$sql = "SELECT * FROM $tbl_name WHERE username='$username' and password='$password'"; 
$result = mysql_query($sql); 

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

// If result matched $username and $password, table row must be 1 row 
if($count == 1){ 

// Register $username, $password and redirect" 
$_SESSION['username'] = $username; 
$_SESSION['password'] = $password;

// get the result set from the query
$result = mysql_fetch_array($result); 

// get the redirect column's value
$redirect = trim($result['redirect']); 
    if ($redirect == '') {
        echo "No redirect value was set!";
    } else {
        header("Location: $redirect");
        exit;
    }
} else { 
     echo "Wrong Password!";
} 
?>

Thanks,

diablo4151
Light Poster
36 posts since Aug 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

Hi again.

First off, it's not a good idea to pass the users password in a SESSION variable, once they have logged in you don't need it anyway by the looks of things.
You DO need to set the username as a SESSION variable though so you can ensure the correct, logged in user is visiting the page, not just someone than found the URL (this is devianleong's first bit of code).

Have you checked which redirect is taking you to workspace.php?
Add this line to the very top of workspace_files.php

exit("Made it to workspace_files");

when you login, if you see the message we know the problem lies in workspace_files.php somewhere and can investigate further.

Zagga
Posting Whiz
388 posts since Dec 2009
Reputation Points: 45
Solved Threads: 81
Skill Endorsements: 4

Zagga, thank you for the quick response. I am not all that good with php. Most of these files are found elsewhere and I am just trying to incorporate it and learn from it. I did add the line exit("Made it to workspace_files"); and it is still redirecting back to workspace.php. However, if I put anything else at the very top such as //, it will actually redirect me to workspace_files.php and say Made it to workspace_files. Please see example below.

//
<?php
session_start();
if (!isset($_SESSION['username'])) {
header('Location: workspace.php');
exit("Made it to workspace_files");
}
?>

Below is the 3 files as to what it is right now. Thank you again for your continuing help.

workspace.php (form):

<?
//Start session
session_start();
?>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</HEAD>
<BODY>
<form name="form" method="post" action="workspace_login.php">
<table>
<tr><td>Login</td></tr>
<tr><td>Username: <input name="username" type="text" style="width:215px" autocomplete="off"></td></tr>
<tr><td>Password: <input name="password" type="password" style="width:215px" autocomplete="off"></td></tr>
<tr><td><input type="submit" name="submit" value="Login"></td></tr>
</table>
</form>

workspace_login.php

<?
//Start session
session_start();

$host="localhost"; // Host name 
$username="*****"; // Mysql username 
$password="*****"; // Mysql password 
$db_name="*****"; // Database name 
$tbl_name="workspace"; // 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['password']; 

// To protect MySQL injection (more detail about MySQL injection) 
$username = stripslashes($username); 
$password = stripslashes($password); 
$username = mysql_real_escape_string($username); 
$password = mysql_real_escape_string($password); 
$sql = "SELECT * FROM $tbl_name WHERE username='$username' and password='$password'"; 
$result = mysql_query($sql); 

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

// If result matched $username and $password, table row must be 1 row 
if($count == 1){ 

// Register $username, $password and redirect" 
$_SESSION['username'] = $username; 
$_SESSION['password'] = $password;

// get the result set from the query
$result = mysql_fetch_array($result); 

// get the redirect column's value
$redirect = trim($result['redirect']); 
    if ($redirect == '') {
        echo "No redirect value was set!";
    } else {
        header("Location: $redirect");
        exit;
    }
} else { 
     echo "Wrong Password!";
} 
?>

workspace_files.php

<?php
session_start();
if (!isset($_SESSION['username'])) {
header('Location: workspace.php');
exit("Made it to workspace_files");
}
?>
<html>
<head>
<title>Secured Page</title>
</head>
<body>
<p>Welcome <b><?php echo $_SESSION['username']; ?></b>
Information here.</p>
<p><a href="logout.php">Logout</a></p>
</body>
</html>
diablo4151
Light Poster
36 posts since Aug 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

Hi again.

It does seem that $_SESSION['username'] is not being set correctly.

Try moving the exit statement to the very top of workspace_files.php so it looks like this:

  <?php
  exit("Made it to workspace_files");
  session_start();
  if (!isset($_SESSION['username'])) {
    header('Location: workspace.php');
  }
  ?>
  <html>
  <head>
  <title>Secured Page</title>
  </head>
  <body>
  <p>Welcome <b><?php echo $_SESSION['username']; ?></b>
  Information here.</p>
  <p><a href="logout.php">Logout</a></p>
  </body>
  </html>

This should show you the message and exit the script as soon as you are redirected to workspace_files.php, before it checks for a valid $_SESSION['username'] variable.

Zagga
Posting Whiz
388 posts since Dec 2009
Reputation Points: 45
Solved Threads: 81
Skill Endorsements: 4

Zagga, yes the message Made it to workspace_files now show at the top and nothing more. I'm sorry but are mine missing something here? How do we go about getting the content of workspace_files.php to show up?

diablo4151
Light Poster
36 posts since Aug 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

Hi again.

Your script seems to run through fine until workspace_files.php where it checks to see if $_SESSION['username'] is set. Your script finds that it isn't set so redirects you to workspace.php.

Looking over your code again I noticed you open PHP correctly in workspace_files.php with <?php but in workspace.php and workspace_login.php you open PHP with the short tag version <?

If your PHP installation is not set to accept short tags then it will fail to open PHP and therefor will fail to register your SESSION.

Change <? to <?php and see what happens. (Don't forget to remove the exit statement you added).

Zagga
Posting Whiz
388 posts since Dec 2009
Reputation Points: 45
Solved Threads: 81
Skill Endorsements: 4

I removed the exit statment and change the short tag version to the <?php and all it does is take me back to workspace.php.

diablo4151
Light Poster
36 posts since Aug 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

Try this first, at the top of workspace_files.php:

session_start();
$nm = $_SESSION['username'];
exit("The username in this session is $nm.");

If you get "empty" or "Null" or "The username in this session is ." Then you have a whole different problem to handle.

Then we can try below if necessary.
I kinda wrote this backwards, as I thought of the above after I wrote the below.

Correct me if Im wrong, but shouldn't it just be:

if(!$_SESSION['username']) {
}

instead of using isset()... seems a bit redundant, and may be what is causing the error...

Alternatively, though unlikely, global variables may be turned on in your particular configuration, and if you are using mysql on each of your pages (importing, whatever), you may be overwriting the $username variable from your mysql loging.

Consider changing either $username to $usrnm and change all calls to it --
mysql_connect($host, $usr, $pw);

Alternatively, you can change all your session variables from $_SESSION['username'] to $_SESSION['usr'];

Whichever will save you more typing.. shrug

Ryan

ryantroop
Junior Poster
190 posts since Jun 2012
Reputation Points: 57
Solved Threads: 24
Skill Endorsements: 0

Ryan, I tried the first code and it does come back with "The username in this session is."

I tried the 2nd code you suggested and it came back with

0
Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Thanks for your response.

diablo4151
Light Poster
36 posts since Aug 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

Your sessions are not staying persistent... interesting.

Make a new page, and put <?php phpinfo() ?>

and see what version you are running (you can use cntl+f and search version), and see if you have global_vars (search global) turned on or off.

Im guessing youre running PHP4 and you need to use HTTP_SESSION_VARS[] instead of $_SESSION[] but we wont know until you tell us the version.

ryantroop
Junior Poster
190 posts since Jun 2012
Reputation Points: 57
Solved Threads: 24
Skill Endorsements: 0

I am running PHP Version 5.2.17

diablo4151
Light Poster
36 posts since Aug 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

on line 34 of login, try chaging it to:

$_SESSION['username'] = $_POST['username'];

ryantroop
Junior Poster
190 posts since Jun 2012
Reputation Points: 57
Solved Threads: 24
Skill Endorsements: 0

Same thing. It just redirect back to workspace.php.

diablo4151
Light Poster
36 posts since Aug 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

you will need to eventually add exit(); after a header() call, so put that in because it belongs there.

on line 33 of login page, put die("$username");

ryantroop
Junior Poster
190 posts since Jun 2012
Reputation Points: 57
Solved Threads: 24
Skill Endorsements: 0

So this is what I have so far for workspace_login.php and what it does is take me to workspace_files.php and the username is ontop.

<?php
//Start session
session_start();

$host="localhost"; // Host name 
$username="*****"; // Mysql username 
$password="*****"; // Mysql password 
$db_name="*****"; // Database name 
$tbl_name="workspace"; // 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['password']; 

// To protect MySQL injection (more detail about MySQL injection) 
$username = stripslashes($username); 
$password = stripslashes($password); 
$username = mysql_real_escape_string($username); 
$password = mysql_real_escape_string($password); 
$sql = "SELECT * FROM $tbl_name WHERE username='$username' and password='$password'"; 
$result = mysql_query($sql); 

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

// If result matched $username and $password, table row must be 1 row 
if($count == 1){ 

// Register $username, $password and redirect" 
die("$username");
$_SESSION['username'] = $username; 
$_SESSION['password'] = $password;

// get the result set from the query
$result = mysql_fetch_array($result); 

// get the redirect column's value
$redirect = trim($result['redirect']); 
    if ($redirect == '') {
        echo "No redirect value was set!";
    } else {
        header("Location: $redirect");
        exit;
    }
} else { 
     header("Location: workspace.php");
} 
?>
diablo4151
Light Poster
36 posts since Aug 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

k.. you can get rid of the die()... I have no idea why it isnt going through....

Just to be clear, it is the right username? You have $username declared twice, which is why I pointed it out earlier... it's the only thing I can think of that is causing the problem.. but your query goes through... which means the POST is not overwriting it... so I really don't know :(

I still suggest changing the first $username to $user and changing the mysql_connect() to use $user as well... if not that, I dont know.

ryantroop
Junior Poster
190 posts since Jun 2012
Reputation Points: 57
Solved Threads: 24
Skill Endorsements: 0

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page generated in 0.1270 seconds using 2.77MB