how to make multiuser? - php

firstly I get this coding from http://www.webestools.com/scripts_tutorials-code-source-15-personal-message-system-in-php-mysql-pm-system-private-message-discussion.html
before this I create user page and admin page using same coding. I edit same coding to see different user and admin page. I run at same browser at same time.. It run properly. But for this coding I make user and admin using same coding, same browser and run same time. I log in for admin first then log in for user. after I log in for user, I refresh admin page. session that I use in admin change to become like user page.
connexion.php
<?php
include('config.php');
?>
<div class="header">
<img src="<?php echo $design; ?>/images/logo.png" alt="Members Area" />
</div>
<?php
//If the user is logged, we log him out
if(isset($_SESSION['username']))
{
//We log him out by deleting the username and userid sessions
unset($_SESSION['username'], $_SESSION['userid']);
?>
<div class="message">You have successfuly been loged out.<br />
Home</div>
<?php
}
else
{
$ousername = '';
//We check if the form has been sent
if(isset($_POST['username'], $_POST['password']))
{
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$ousername = stripslashes($_POST['username']);
$username = mysql_real_escape_string(stripslashes($_POST['username']));
$password = stripslashes($_POST['password']);
}
else
{
$username = mysql_real_escape_string($_POST['username']);
$password = $_POST['password'];
}
//We get the password of the user
$req = mysql_query('select password,id from users where username="'.$username.'"');
$dn = mysql_fetch_array($req);
//We compare the submited password and the real one, and we check if the user exists
if($dn['password']==$password and mysql_num_rows($req)>0)
{
//If the password is good, we dont show the form
$form = false;
//We save the user name in the session username and the user Id in the session userid
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $dn['id'];
?>
<div class="message">You have successfuly been logged. You can access to your member area.<br />
Home</div>
<?php
}
else
{
//Otherwise, we say the password is incorrect.
$form = true;
$message = 'The username or password is incorrect.';
}
}
else
{
$form = true;
}
if($form)
{
//We display a message if necessary
if(isset($message))
{
echo '<div class="message">'.$message.'</div>';
}
//We display the form
?>
<div class="content">
<form action="connexion.php" method="post"> Please type your IDs to log in:<br />
<div class="center">
<label for="username">Username</label><input type="text" name="username" id="username"value="<?
php echo htmlentities($ousername, ENT_QUOTES, 'UTF-8'); ?>" /><br />
<label for="password">Password</label><input type="password" name="password" id="password" />br />
<input type="submit" value="Log in" />
</div>
</form>
</div>
<?php
}
}
?>
index.php
<?php
include('config.php')
?>
<?php
//We display a welcome message, if the user is logged, we display it username
?>
Hello<?php if(isset($_SESSION['username'])){echo ' '.htmlentities($_SESSION['username'],ENT_QUOTES, 'UTF-8');} ?>,<br />
Welcome on our website.<br />
You can see the list of users.<br /><br />
<?php
//If the user is logged, we display links to edit his infos, to see his pms and to log out
if(isset($_SESSION['username']))
{
//We count the number of new messages the user has
$nb_new_pm = mysql_fetch_array(mysql_query('select count(*) as nb_new_pm from pm where ((user1="'.$_SESSION['userid'].'" and user1read="no") or (user2="'.$_SESSION['userid'].'" and user2read="no")) and id2="1"'));
//The number of new messages is in the variable $nb_new_pm
$nb_new_pm = $nb_new_pm['nb_new_pm'];
//We display the links
?>
Edit my personnal informations<br />
My personnal messages(<?php echo $nb_new_pm; ?> unread)<br />
Logout
<?php
}
else
{
//Otherwise, we display a link to log in and to Sign up
?>
Sign up<br />
Log in
<?php
}
?>

You have to Add to your session some new indexes for admin, it will be like the following
if a normal user logs in after checking if he's admin or not you store the normal user session indexes like these that you're using..
$_SESSION['username'] etc..
and if it's an admin logging in you store something like for example
$_SESSION['isAdmin'];
$_SESSION['adminName'];
etc..
and then you check for the Admin session in the admin panel..
and Then depending on the Session variables you decide what to show and what to not show, ask for login if there's no 'isAdmin' set..

Related

PHP: log a user out

I have a form which allows users to enter their data. It then checks these data against a database to see if the user exists. If so, it logs them into a certain page.
I would then like to allow them to log out (such that they no longer have access to that certain page). To this end, I created a "logout.php" document in which I try to clear the login details.
However, having done this, if I try load the login page, it takes me back to the logged in page.
Here is my code (login.php - creating the form and logging the user in):
<?php //Start the Session
session_start();
require('connect.php');
if (isset($_POST['username']) and isset($_POST['password']))
{
//3.1.1 Assigning posted values to variables.
$username = $_POST['username'];
$password = $_POST['password'];
//3.1.2 Checking if the values exist in the database
$checkLogin = $connection->query("SELECT * FROM users
where (username='$username' && password='$password')");
$numRows = $checkLogin->fetchColumn();
//3.1.2 If the posted values are equal to the database values, then session will be created for the user.
if ($numRows >= 1){
$_SESSION['username'] = $username;
}else{
//3.1.3 If the login credentials doesn't match, he will be shown with an error message.
echo '<script>window.alert("Invalid Login Credentials")</script>';
}
}
//3.1.4 if the user is logged in Greets the user with message
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
echo "Hi " . $username . "
";
echo "This is the Members Area";
echo "<a href='logout.php'>Logout</a>";
echo $username;
}else{
//3.2 When the user visits the page first time, simple login form will be displayed.
?>
<!DOCTYPE html>
<head>
<title>CodingCyber - Simple Login Script</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<!-- Form for logging in the users -->
<div class="register-form">
<?php
if(isset($msg) & !empty($msg)){
echo $msg;
}
?>
<h1>Login</h1>
<form action="login.php" method="POST">
<p><label>User Name : </label>
<input id="username" type="text" name="username" placeholder="username" /></p>
<p><label>Password : </label>
<input id="password" type="password" name="password" placeholder="password" /></p>
<a class="btn" href="register.php">Signup</a>
<input class="btn register" type="submit" name="submit" value="Login" />
</form>
</div>
<?php } ?>
</body>
</html>
The "require('connect.php')"; just connects to my MySQL database. This code all seems to run fine, in that it does log users in, once validated. I've just included it for completeness w.r.t. the problem.
As you can see, once logged in it displays text saying "Member's area", with a logout hyperlink.
Here is my logout.php code (which I would like to remove access to the member's area, and take user back to the login page):
<?php
session_start();
$username = '';
$password = '';
$confirmPassword = '';
$email = '';
echo $username;
unset($_POST['username']);
unset($password);
?>
This second bit of code is where, to be honest, I'm really not sure what I'm meant to do to remove the access privileges.
I've looked at a few other questions, but can't seem to find the solution.
Any help would be awesome! Please let me know if there is a similar thread or if you need more information.
Thanks!
Try this:
unset($_SESSION['username']);
It will remove the username variable from the session
You need to destroy the session variables:
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
$url = 'http://example.com';
header( "Location: $url" );
exit();

correct username and password doesn't have any effect PHP

I have some problem in php. Here is my code:
if (isset($_POST['submit'])) { // Form has been submitte
echo "Submitted";
$username = trim($_POST['username']);
$password = trim($_POST['password']);
// Check database to see if username/password exist.
$found_user = User::authenticate($username, $password);
if ($found_user) {
$session->login($found_user);
redirect_to("index.php");
}
} else { // Form has not been submitted.
$username = "";
$password = "";
}
?>
<html>
<head>
<title>Photo Gallery</title>
<link href="../stylesheets/main.css" media="all" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header">
<h1>Photo Gallery</h1>
</div>
<div id="main">
<h2>Staff Login</h2>
<form action="login.php" method="post">
<table style="float: left;">
<tr>
<td>Username:</td>
<td>
<input type="text" name="username" maxlength="30" value="
<?php echo htmlentities($username); ?>" />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type="password" name="password" maxlength="30" value="
<?php echo htmlentities($password); ?>" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="submit" value="Login" />
</td>
</tr>
</table>
</form>
</div>
<div id="footer">Copyright <?php echo date("Y", time()); ?>, Gio baramidze</div>
</body>
</html>
My problem is that when i try to log in with incorrect user everything works fine and message "submitted" comes on the screen. But when i write correct username and password and click "Log in" it doesn't even show me the message ("submitted"). It means that "if (isset($_POST['submit']))" this condition isn't true. Despite the fact that I've clicked Submit. Thanks.
My guess is above code is index.php. When a user is found it redirects to the same page (quickly) and thus no $_POST is set since it is reloaded.
if ($found_user) {
$session->login($found_user);
redirect_to("index.php"); //If user found redirect without $_POST information.
}
You should make use of the $_SESSION array. This is a server side array, you can fill it with a user ID once a user logs in. On every page where you need to check a login you should include a script that checks for the this ID. You can also use this to store a users name or other stuff you need frequent access to:
$_SESSION['USER_ID'] = //Some ID
$_SESSION['USERNAME'] = $username
To make $_SESSION work you need something like this:
<?php
session_start();
//other code...
if ($found_user) {
$session->login($found_user);
//give the user an ID
$_SESSION['USER_ID'] = //some id, usually fetched from a database
//Let's give a name too
$_SESSION['USERNAME'] = $username;
//Now redirect
redirect_to("index.php"); //If user found redirect without $_POST information.
}
//Other code...
?>
Now from index.php we start again with session_start(); and we can use php to retrieve his ID and name. Put this on top and you see that $_SESSION gets carried over to other pages on the server.
<?php
session_start();
echo $_SESSION['USER_ID'];
echo $_SESSION['USERNAME'];
//or something nicer
if (isset($_SESSION['USER_ID']))
{
echo "User ".$_SESSION['USERNAME']." has logged in and has user id [".$_SESSION['USER_ID']."].";
}
else
{
echo "Not logged on."
}
?>
For testing purpose you can store the above code in whatever.php and redirect to whatever.php inside your login.php. It should pass the if statement if a user is found on login.php and thus show the username and ID.
You might change isset($_POST['submit']) by
if(isset($_POST['username']) && isset($_POST['password'])){
//do your stuff here
}

PHP Online users--- Sessions function

When a person logs in , the online column in the table is set to 1 , and when he logs out , it is set to 0 . I achieved the Login script , but problems on ending the session with SQL query .. Please do help !
There is No Error Displayed but Online value remains as 1 even after logging out
**LOGOUT SCRIPT**
<?php
$offline = $_SESSION["username"] ;
?>
<?php
//If the user is logged, we log him out
if(isset($offline))
{
//We log him out by deleting the username and userid sessions
unset($_SESSION['username'], $_SESSION['userid']);
$con=mysqli_connect("localhost","root","","chat");
mysqli_query($con,"UPDATE users SET Online=0
WHERE username='.$offline.'");
mysqli_close($con);
?>
LOGIN SCRIPT
<?php
$ousername = '';
//We check if the form has been sent
if(isset($_POST['username'], $_POST['password']))
{
//We remove slashes depending on the configuration
if(get_magic_quotes_gpc())
{
$ousername = stripslashes($_POST['username']);
$username = mysql_real_escape_string(stripslashes($_POST['username']));
$password = stripslashes($_POST['password']);
}
else
{
$username = mysql_real_escape_string($_POST['username']);
$password = $_POST['password'];
}
//We get the password of the user
$req = mysql_query('select password,id from users where username="'.$username.'"');
$dn = mysql_fetch_array($req);
//We compare the submited password and the real one, and we check if the user exists
if($dn['password']==$password and mysql_num_rows($req)>0)
{
//If the password is good, we dont show the form
$form = false;
//We save the user name in the session username and the user Id in the session userid
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $dn['id'];
$con=mysqli_connect("localhost","root","","chat");
$sql = mysql_query('UPDATE users SET Online=1 where username="'.$username.'"');
?>
<div class="message">You have successfuly been logged. You can access to your member area.<br />
Home</div>
<?php
}
else
{
//Otherwise, we say the password is incorrect.
$form = true;
$message = 'The username or password is incorrect.';
}
}
else
{
$form = true;
}
if($form)
{
//We display a message if necessary
if(isset($message))
{
echo '<div class="message">'.$message.'</div>';
}
//We display the form
?>
<div class="content">
<form action="connexion.php" method="post">
Please type your IDs to log in:<br />
<div class="center">
<label for="username">Username</label><input type="text" name="username" id="username" value="<?php echo htmlentities($ousername, ENT_QUOTES, 'UTF-8'); ?>" /><br />
<label for="password">Password</label><input type="password" name="password" id="password" /><br />
<input type="submit" value="Log in" />
</div>
</form>
</div>
And , when I do the SQL query , How do I do the if Online = 1 , display online.png ? else 'Blank space ' ?
Thanks in advance !
The below code is for logout.php
<?php
//If the user is logged, we log him out
if(isset($_SESSION['username']))
{echo $_SESSION['username'];
//We log him out by deleting the username and userid sessions
$username=$_SESSION['username'];
$sql="UPDATE users SET online=0 WHERE username='$username'";
mysql_query($sql);
unset($_SESSION['username'], $_SESSION['userid']);
?>
And this one for sign_up.php
if(isset($_POST['username'], $_POST['password'], $_POST['passverif'], $_POST['email'], $_POST['username']))
use session_start();
ANd session_destroy(); FOR LOGOUT.

Login & home page issues?

Well i just got my login page to work as it should and of course this has caused something else to go wrong, the issue i am having is that when you go to the home page it should allow you to browse the home page and navigate to other regular pages not logged in to any sort of account (don't have to be registered or logged in to view these pages) but for some reason when i click on my EOI_home.php (which is my home page) as a non-logged in user it automatically takes me to my login.php (my login page) and forces me to log in before i can view the home page, meaning that i am not able too view the home page as a non-registered or non-logged in user which i should be able to do. Here is my code for my home page (EOI_home.php) :
<head>
<title>Expression of Interest</title>
<link rel="stylesheet" href="Assign.css" type="text/css" />
</head>
<body>
<?php
require_once("nocache.php");
session_start();
if (!$_SESSION["who"]){
header("location: logoff.php");}
else {
$staff = $_SESSION["who"];
$access = $_SESSION["school_type"];
?>
<div class="title_background"><h2>Moving into Year 7 in a NSW government school in 2015</h2>
<h2>Information guide and Expression of Interest form for parents and carers</h2></div>
<p><img src="img1.jpg" width="750" height="550"></p>
<div class="right">
<?php
if ($access == S){
echo '<p>Process EOI</p>';
echo '<p>Print Offer Status Letters</p>';
}
if ($access == P){
echo '<p>School Leavers</p>';
echo '<p>Add School Comments</p>';
}
echo '<p>Logoff</p>';
}
?>
<p>Home</p>
<p>Guidelines</p>
<p>Your Secondary School Options</p>
<p>Expression of Interest Form</p>
<p>Privacy Statement and Contact Us</p>
<p>Login</p>
</div>
<h1>Moving to secondary school</h1>
and here is my code for the login page (login.php) :
<body>
<?php
require_once("nocache.php");
$id = $_POST["id"];
$pword = $_POST["pword"];
$msgp = "";
if(!empty($_POST)) {
if(!empty($id) && !empty($pword)) {
require_once("dbconn.php");
$sql = "select username, school_type from school_info where username = '$id' and password = '$pword'";
$rs = mysql_query($sql, $dbConn);
if(mysql_num_rows($rs) > 0) {
session_start();
$_SESSION["who"] = $id;
$_SESSION["school_type"] = mysql_result($rs, 0, "school_type");
header("location: EOI_home.php");
}
} else {
header("location: login.php");
$msgp = '<span class="error>Incorrect username and/or password</span>';
}
}
?>
<form method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="login">
ID: <input type="text" name="id" /><?php echo $msgp; ?></td><br/>
pword: <input type="password" name="pword" /><br/>
<p>Home</p>
<input type="submit" value="log in" />
<input type="reset" />
</form>
Here is the nochache.php code :
<?php
header("Cache-Control: no-cache");
header("Expires: -1");
?>
Here is also the code for logoff.php, just incase :
<?php
session_start();
require_once("nocache.php");
session_destroy();
header("location: login.php");
?>
By the way the accounts have different access levels and with the different access levels different links are available on the home page e.g. access levels S and P.
If anyone could help me with a solution that would be really great, i am new to this stuff.
<?php
require_once("nocache.php");
session_start();
if ($_SESSION["who"]){
$staff = $_SESSION["who"];
$access = $_SESSION["school_type"];
?>
Just comment header("location: logoff.php");
also check code for logoff is working or not

Access Denied on Php Login

I have a buyer form, called "Buyer.php":
<form method="post" action="check_buyer.php" id="LoggingInBuyer">
<div style="width:265px;margin:0; padding:0; float:left;">
<label>Username: <span>Forgot Username?</span></label> <br />
<input id="UserReg" style="width:250px;" type="text" name="userName" tabindex="1" class="required" /></div>
<div style="width:265px;margin:0; padding:0; float:right;">
<label>Password: <span>Forgot Password?</span></label> <br />
<input id="UserReg" style="width:250px;" type="password" name="userPass" tabindex="2" class="required" /></div>
<div class="clearB"> </div>
<input type="submit" style="width:100px; margin:10px 200px;" id="UserRegSubmit" name="submit" value="Login" tabindex="3" />
</form>
A file called check_buyer.php (in the same dir):
<?php
session_start(); #recall session from index.php where user logged include()
function isLoggedIn()
{
if(isset($_SESSION['valid']) && $_SESSION['valid'])
header( 'Location: buyer/' ); # return true if sessions are made and login creds are valid
echo "Invalid Username and/or Password";
return false;
}
require_once('../inc/db/dbc.php');
$connect = mysql_connect($h, $u, $p) or die ("Can't Connect to Database.");
mysql_select_db($db);
$LoginUserName = $_POST['userName'];
$LoginPassword = mysql_real_escape_string($_POST['userPass']);
//connect to the database here
$LoginUserName = mysql_real_escape_string($LoginUserName);
$query = "SELECT uID, uUPass, dynamSalt, uUserType FROM User WHERE uUName = '$LoginUserName';";
function validateUser($ifUserExists['uID'], $ifUserExists['uUserType']) {
$_SESSION['valid'] = 1;
$_SESSION['uID'] = $uID;
$_SESSION['uUserType'] = $uUserType; // 1 for buyer - 2 for merchant
}
$result = mysql_query($query);
if(mysql_num_rows($result) < 1) //no such USER exists
{
echo "Invalid Username and/or Password";
}
$ifUserExists = mysql_fetch_array($result, MYSQL_ASSOC);
$dynamSalt = $ifUserExists['dynamSalt']; #get value of dynamSalt in query above
$SaltyPass = hash('sha512',$dynamSalt.$LoginPassword); #recreate originally created dynamic, unique pass
if($SaltyPass != $ifUserExists['uUPass']) # incorrect PASS
{
echo "Invalid Username and/or Password";
}else {
validateUser();
}
// If User *has not* logged in yet, keep on /login
if(!isLoggedIn())
{
header('Location: index.php');
die();
}
?>
// This is now throwing error of: Parse error: syntax error, unexpected '[', expecting ')' in on line 23 which is function validateUser($ifUserExists['uID'], $ifUserExists['uUserType']) {
and the file "index.php" in the buyer/ directory:
<?php
session_start();
if($_SESSION['uUserType']!=1)
{
die("You may not view this page. Access denied.");
}
function isLoggedIn()
{
return (isset($_SESSION['valid']) && $_SESSION['valid']);
}
//if the user has not logged in
if(!isLoggedIn())
{
header('Location: index.php');
die();
}
?>
<?php
if($_SESSION['valid'] == 1){
#echo "<a href='../logout.php'>Logout</a>";
require_once('buyer_profile.php');
}else{
echo "<a href='../index.php'>Login</a>";
}
?>
The point of this is that when a username and password is entered, the user is logged in and directed to /buyer/index.php, to the buyer portion of that website. It seems everytime I login with the dummy credentials I made to test, it just blurts out : You may not view this page. Access denied. But, then if I go back by pressing back arrow in browser it has me logged in and showing a link to logout.
I did some trouble shooting:
1) Shown here, to test my sql query is fine and indeed it is. http://i.stack.imgur.com/n2b5z.png
2)Tried choing out echo 'the userid: ' . $userid; before it whines about You may not view.. and it doesn't print anything.
How do I go about getting this userID? I double checked the field names in the database and all is fine..
From a quick check, it looks like you're setting $_SESSION['uUserType'] = $userType in validateUser(), but don't seem to be passing in $userType itself to that function. So $_SESSION['uUserType'] won't be 1, but $_SESSION['valid'] will be, because you're setting it to that in validateUser().
I suspect you should be passing valid data in to validateUser in order to set it into the session.
e.g.
validateUser($ifUserExists['uID'], $ifUserExists['uUserType']);
function validateUser($uID, $uUserType) {
$_SESSION['valid'] = 1;
$_SESSION['uID'] = $uID;
$_SESSION['uUserType'] = $uUserType; // 1 for buyer - 2 for merchant
}

Categories