I want to make a certain page viewable only to a certain group of a database. My SQL table is set up as:
Table: DD_users
Columns: id | group | username | paraphrase | guild | level | salt
This is the code I am trying to use:
// First we execute our common code to connection to the database and start the session
require("common.php");
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
header("Location: /DD/index.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to /DD/index.php");
}
if($_SESSION['user']['group'] == '0')
{
// Destroy the session to make them log in again.
unset($_SESSION['user']);
// If they are not, we redirect them to the login page.
header("Location: /DD/index.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to /DD/index.php");
}
// Everything below this point in the file is secured by the login system
When I try this, will let any user group (0, 1, and 2) access the page when I only want groups 1 and 2 to access the page.
You don't have any code to check if they are in groups 1 or 2. Just wrap the code around an if.
if($_SESSION['group'] == '1' || $_SESSION['group'] == '2')
Also make sure $_SESSION['group'] is set using isset. If it is not set then the last if will fail.
Got it working another way:
require('common.php');
$charname = $_SESSION['user']['username'];
$query = "SELECT adminaccess, guild, username, class, level, active, canRegister, canNews, canActive
FROM DD_users
WHERE username = ?";
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$stmt->execute(array($charname));
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
//print_r($rows);
$group = $rows['0']['adminaccess'];
$guild = $rows['0']['guild'];
$username = $rows['0']['username'];
$class = $rows['0']['class'];
$level = $rows['0']['level'];
$accessAdmin = $rows['0']['adminaccess'];
$canRegister = $rows['0']['canRegister'];
$canNews = $rows['0']['canNews'];
$canActive = $rows['0']['canActive'];
Related
First I log in with one user and then I open a second tab and log in with other user.
Now the problem is that when I go to the tab where I logged in first and refresh it, the username from the second tab overlaps the first one.
I have seen that the two different users have different cookies, but is the second one overlapping the first one, because I try to log in with more than one user on a single machine..My theory is that I am only getting the last session and it sets it everyhwere.So I am wondering how can I make them independent.
This is my PHP code for the session of each user:
`
<?php
session_start();
if(isset($_SESSION["user_id"]))
{
$mysqli = require __DIR__ . "/databaseCon.php";
$sql = "SELECT * FROM users
WHERE user_id = {$_SESSION["user_id"]}";
$result = $mysqli->query($sql);
$user = $result->fetch_assoc();
$getSessions = $mysqli->query("SELECT sessionName FROM sessions");
}
This is my login script. Once logged in, they will be sent to different pages determined by the roles(student or a teacher):
<?php
$is_invalid = false;
#if we opened the page its set to GET, when we submit POST
if ($_SERVER["REQUEST_METHOD"] === "POST")
{
$mysqli = require __DIR__ . "/databaseCon.php";
$sql = sprintf("SELECT * FROM users
WHERE email = '%s'",
$mysqli->real_escape_string($_POST["mail"]));
$result = $mysqli->query($sql);
$user = $result->fetch_assoc();
if ($user)
{
if(password_verify($_POST["passw"], $user["password_hash"]))
{
session_start();
session_regenerate_id();
$_SESSION["user_id"] = $user["user_id"];
$_SESSION["firstName"] = $user["firstName"];
$_SESSION["privilege"] = $user["privilege"];
header("Location: /Controllers/sessionInit.php");
exit;
}
}
$is_invalid = true;
}
?>
`
When your php program feeds its session cookie to the browser, the browser then uses it, immediately, for all its tabs. So starting a session for Bob disconnects your browser from the session for Alice.
It's common during debugging to want to have two user sessions going at once. When I do that, I do one of three things
Use different browsers for different sessions (Chrome, Firefox, Edge etc).
Use a browser's anonymous mode for the second session.
Set up multiple user profiles in the browser, and use the different profiles for different sessions. This can be clunky, however.
This code below is having a problem..
<?php
session_start();
include_once("databaseConnect.php"); // This creates $database by mysqli_connect().
if(isset($_SESSION['id'])){ // checking if user has logged in
$id = $_SESSION['id'];
$sql = "SELECT * FROM tableName WHERE id = '$id'";
$query = mysqli_query($database, $sql);
$row = mysqli_fetch_row($query);
$activated = $row[1]; // This is where I store permission for the user
if(!($activated == 2 || $activated == 3)){ // if the user has not enough permission:
header("Location: http://myWebsiteIndex.php");
}
// code for users
}else{
header("Location: http://myWebsiteIndex.php");
}
?>
I have a user who has 3 for $activated, so they should be able to access.
When a user logges in to my website, it sets $_SESSION['id'] to store the id of the user.
This session variable is used to check if the user is logged in.
However, when I run the code several time, sometimes it works and sometimes it doesn't. Sometimes, it will run the '// code for users' part, and sometimes it will just redirect to my 'http://myWebsiteIndex.php'.
How would I fix this??
First, try changing the headers to different redirects. What part of the conditional is failing? If the $_SESSION['id'] is not properly set it will redirect to the same url as it will redirect to when the user does not have proper permissions. Changing one of them will show you what part is executed when you encounter the behaviour.
Second, the comment from Barth is helpful. The if(!($activated == 2 || $activated == 2)) evaluation seems incorrect. You are evalutaing for (not) 2 or 2.
Third, take note of your session data and compare when the redirect happens to when it does not.
I have been trying to make a page protection for the Administrator page, and I can not get it to work. I am sure this would not have been a problem if I was not new to PHP coding, hehe.
So what I am trying to do is, when a normal user with the type '0' is trying to access the administrator page, index_admin.php, the user will get redirected to the normal user page, index.php. And if the user have the type '1', then the user/admin will stay on the page.
So here is the code I have been trying to get working. (This file is required in index_admin.php and it is called index_admin_check.php):
<?php
session_start();
?>
<?php
$vert = "localhost";
$brukarnamn = "root";
$passord = "";
$db_namn = "nettsidebunad";
$tbl_namn = "kunde_register";
// Connecting to the MySQL database.
mysql_connect("$vert", "$brukarnamn", "$passord") or die ("Kan dessverre ikkje koble til databasen.");
mysql_select_db("$db_namn") or die ("Kan ikkje finna den ynkjande databasen.");
?>
<?php
// *** Page protection *** \\
// Admin check. If `type` = 1, let the user (admin) stay on the site. If `type` = 0 kick the user (normal) off the site.
$sql = "SELECT `type` FROM $tbl_namn";
$res = mysql_query($sql);
$tell = mysql_num_rows($res);
if ($tell == 0) {
header ("location: index.php");
exit();
}
?>
Some of this text is in norwegian.
$vert = $host (in english)
$brukarnamn = $usernamn (in english)
$passord = $password (in english)
$db_namn = $db_name (in english)
$tbl_namn = $tbl_name (in english)
$sql = "SELECT `type` FROM $tbl_namn";
This SQL query will return a row for every user in your database. Using your method of simply checking whether the query returned a result or not, you need to select just the row for the current user, and then only if the user has type=1.
You need to make sure that:
The user has previously logged into the system using a username and password or some such
You have saved their details to the session.
If your user table has an ID column, and you saved the ID of the logged in user to the session as 'userid', you might use the query:
$sql = "SELECT `type` FROM $tbl_namn WHERE id = {$_SESSION['userid']} AND type = 1";
But of course that would be moot, because you would just have save the user's type in the session when you first logged them in, wouldn't you?
Well for what I can see, you don't actually check for user.
I will make some remarks to your code to make situation clear:
$sql = "SELECT `type` FROM $tbl_namn"; //Return all values of column "type" from table - instead you should search for specifyc user
$res = mysql_query($sql);
$tell = mysql_num_rows($res); //Count returned rows
So instead of finding out the user type, you get the count of registered users.
What you should do to search for user name and get user type for that name. So lets think of this table concept:
ID | name | type |
Now we can start our user check up. We will ask mysql for type of user "admin".
$name = $_POST["username"]; //username submited in POST HTML form
$name = mysql_real_escape_string($name); //Replace dangerous characters from name. This is important to avoid your database being hacked
$data = mysql_query("SELECT type FROM $tbl_namn WHERE name='$name'") or die(mysql_error()); //On failure, you will is if there is some error
$data=mysql_fetch_row($data); //Get actual data
if($data["type"]==0) {
header("HTTP/1.1 403 Acces Forbidden");
header("Location: forbidden.html"); //send user to page telling me he is not allowed to enter. As well you can use include here.
exit;
put this to login page:
<?php session_start();
if ($_POST['type'] = "1") {
Header('location: http://example.com/admin.php/');
$_SESSION['admin']; = "yes";
exit;
} else {
Header('location: http://example.com/user.php/');
$_SESSION['admin']; = "no";
exit;
}
//modify as needed
?>
and this one into admin.php filename can be any but extension needs to be .php:
<?php session_start():
if ($_SESSION['admin']; = "no") {
Header('location: http://example.com/user.php/');
exit;
}
//modify as needed
?>
and remember to put this in the very beggining of the file otherwise sessions won't work
I want to display the attributes of the game character, which is under the users TABLE. So, I want it to display the specific attributes of the user who has logged in, since it should be in his row. Do I need to register my users with session, because I didn't.
This is the code I used to get the sessions for the user in when login in
<?
if(isset($_POST['Login'])) {
if (ereg('[^A-Za-z0-9]', $_POST['name'])) {// before we fetch anything from the database we want to see if the user name is in the correct format.
echo "Invalid Username.";
}else{
$query = "SELECT password,id,login_ip FROM users WHERE name='".mysql_real_escape_string($_POST['Username'])."'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result); // Search the database and get the password, id, and login ip that belongs to the name in the username field.
if(empty($row['id'])){
// check if the id exist and it isn't blank.
echo "Account doesn't exist.";
}else{
if(md5($_POST['password']) != $row['password']){
// if the account does exist this is matching the password with the password typed in the password field. notice to read the md5 hash we need to use the md5 function.
echo "Your password is incorrect.";
}else{
if(empty($row['login_ip'])){ // checks to see if the login ip has an ip already
$row['login_ip'] = $_SERVER['REMOTE_ADDR'];
}else{
$ip_information = explode("-", $row['login_ip']); // if the ip is different from the ip that is on the database it will store it
if (in_array($_SERVER['REMOTE_ADDR'], $ip_information)) {
$row['login_ip'] = $row['login_ip'];
}else{
$row['login_ip'] = $row['login_ip']."-".$_SERVER['REMOTE_ADDR'];
}
}
$_SESSION['user_id'] = $row['id'];// this line of code is very important. This saves the user id in the php session so we can use it in the game to display information to the user.
$result = mysql_query("UPDATE users SET userip='".mysql_real_escape_string($_SERVER['REMOTE_ADDR'])."',login_ip='".mysql_real_escape_string($row['login_ip'])."' WHERE id='".mysql_real_escape_string($_SESSION['user_id'])."'")
or die(mysql_error());
// to test that the session saves well we are using the sessions id update the database with the ip information we have received.
header("Location: play.php"); // this header redirects me to the Sample.php i made earlier
}
}
}
}
?>
you need to find which user you are logged in as. How do you log in to your system? You have several options which you can try out:
use sessions (save the userID in the session, and add that to the query using something like where id = {$id}
Get your userid from your log-in code. So the same code that checks if a user is logged in, can return a userid.
Your current code shows how you log In, and this works? Then you should be able to use your session in the code you had up before.
Just as an example, you need to check this, and understand the other code. It feels A bit like you don't really understand the code you've posted, so it's hard to show everything, but it should be something like this.
<?php
session_start();
$id = $_SESSION['user_id'];
//you need to do some checking of this ID! sanitize here!
$result = mysql_query("SELECT * FROM users" where id = {$id}) or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
}
I'm using a login system, and I'm trying to keep the user logged in for 10 days unless they specifically log out. I thought by using session_set_cookie_params('864000'); that it would make the user stay logged in for 10 days. But it's not doing that, at least in Chrome. The user only seems to be logged in for the standard 20-30 minutes before being automatically logged out. When I check the cookies in Chrome, there are two PHP Session cookies listed for my URL with expiration dates 10 days into the future. But this seems to be unrelated to the login variables. Most of the relevant code should be below.
Any idea why the user is not logged in for 10 days?
Thanks in advance,
John
In the index file, I have the following:
require_once "header.php";
//content
include "login.php";
In the header.php file, the following is included:
session_set_cookie_params('864000');
session_start();
In the login.php file, the following is included:
if (checkLogin($_POST['username'], $_POST['password']))
{
show_userbox();
}
Here is the function "checkLogin":
function checkLogin($u, $p)
{
global $seed; // global because $seed is declared in the header.php file
if (!valid_username($u) || !valid_password($p) || !user_exists($u))
{
return false; // the name was not valid, or the password, or the username did not exist
}
//Now let us look for the user in the database.
$query = sprintf("
SELECT loginid
FROM login
WHERE
username = '%s' AND password = '%s'
AND disabled = 0 AND activated = 1
LIMIT 1;", mysql_real_escape_string($u), mysql_real_escape_string(sha1($p . $seed)));
$result = mysql_query($query);
// If the database returns a 0 as result we know the login information is incorrect.
// If the database returns a 1 as result we know the login was correct and we proceed.
// If the database returns a result > 1 there are multple users
// with the same username and password, so the login will fail.
if (mysql_num_rows($result) != 1)
{
return false;
} else
{
// Login was successfull
$row = mysql_fetch_array($result);
// Save the user ID for use later
$_SESSION['loginid'] = $row['loginid'];
// Save the username for use later
$_SESSION['username'] = $u;
// Now we show the userbox
return true;
}
return false;
}
Looks more likely that your server is discarding the sessions -- you'd need to store pertinent information in a local friendly database and load from there, based on the cookies as appropriate