I found this tutorial to create a members only area on my webpage using phpMyAdmin. The only problem I have is I need to have different pages show for different user levels. Currently all my users are user level 0, I would like to create an admin user as user level 1. I believe the php file I need to change is the one below, it is my checkuser.php file. Any help or direction would be much appreciated! Thanks in advance.
<?
/* Check User Script */
session_start(); // Start Session
include 'db.php';
// Conver to simple variables
$username = $_POST['username'];
$password = $_POST['password'];
if((!$username) || (!$password)){
echo "";
include 'loginError.php';
exit();
}
// check if the user info validates the db
$sql = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password' AND activated='1'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){
while($row = mysql_fetch_array($sql)){
foreach( $row AS $key => $val ){
$$key = stripslashes( $val );
}
// Register some session variables!
session_register('first_name');
$_SESSION['first_name'] = $first_name;
session_register('last_name');
$_SESSION['last_name'] = $last_name;
session_register('email_address');
$_SESSION['email_address'] = $email_address;
session_register('special_user');
$_SESSION['user_level'] = $user_level;
mysql_query("UPDATE users SET last_login=now() WHERE userid='$userid'");
header("Location: /restricted/index.php");
}
} else {
echo "";
include 'loginError.php';
}
?>
Simple if
session_start();
if($_SESSION['user_level']==0){
header('location: no-access.php');
}
This will redirect user with level zero to no-access page. Put this top of page you want to restrict.
Related
I have a login page which directs to a process_login page which in turn directs the user to the appropriate page(i.e. i have a SQL table with 3 users - admin, student, instructor)
The code below achieves that but i am having difficulty when i try to add session variables. I have commented out the code i was trying when adding the session variables.
What would be the best way to add session variables to this?
process_login
<?php
//session_start();
include('connect.php');
$name =$_POST['userlogin'];
$pass = $_POST['userpw'];
//$_SESSION['currentuser'] = $name;
$loginsql = "SELECT * FROM VLE_users WHERE name = '$name' AND passw = '$pass' ";
$result = $conn -> query ($loginsql);
if(!$result) {
echo $conn ->error;
}
//$num = $result -> num_rows;
//if($num>0){
while ($row = $result->fetch_assoc()){
//$userid =$row ['id'];
//$S_SESSION['userid'] = $userid;
if($row['type'] == 3){
header('Location:index2.php');
}elseif($row['type'] == 2){
header('Location: studentpage.php');
}elseif($row['type']==1){
header('Location:admin_dash.php');
}else{
header('Location:index.php');
}
}
?>
$_SESSION["currentuser"] = $name;
Should work just fine
$S_SESSION['userid'] = $userid;
Should be :
$_SESSION['userid'] = $userid;
did you make a typo there or? And exactly what is the trouble you are experiencing? what doesn't work ?
Good day.SO i am having an issue in that, when i create a session via a login and a user is authenticated, once i leave that page to say a different page, i am not whether the session is destroyed or not created in the first place, i require this page to hold the session so i can be able to query the users email from it, and use it to query the database to determine the username.
This is my submit.php, called once the user clicks login on the page.
<?php
session_start();
require_once('connect.php');
if(isset($_POST) & !empty($_POST)){
$email = mysqli_real_escape_string($connection, $_POST['email']);
$password =$_POST['password'];
$sql = "SELECT * FROM `USERS` WHERE EMAIL='$email' AND ENCRYPTEDPWD='$password'";
$result = mysqli_query($connection, $sql);
$count = mysqli_num_rows($result);
if($count == 1){
$_SESSION['email'] = $email;
header("Location: Landing page.php");
exit();
}
else{
header("Location: customerportal.php?login=invalid");
exit();
}
}
?>
it redirects to the next page, the landing page.
This page should check email from the session, and then display a username.
<?php
session_start();
$_SESSION['email'] = $email;
$sql = "SELECT * FROM users WHERE EMAIL='$email';";
$result = mysqli_query($connection,$sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0){
while($row = mysqli_fetch_assoc($result)){
echo $row['username'];
}
}
else{
echo "No User.";
}
?>
Please help.
You have an issue with the landing page in below line:-
$_SESSION['email'] = $email;// here you are assigning to SESSION
It needs to be:-
$email = $_SESSION['email'];//assign value from SESSION to variable
So code needs to be like this:-
$email = $_SESSION['email'];
$sql = "SELECT * FROM users WHERE EMAIL='$email'";
Note:- Your code is wide-open for SQL INJECTION. Try to use prepared statements to prevent it.
mysqli::prepare
In your landing page, invert the line after session_start(): You are assigning an empty variable to overwrite your already saved session variable
$email = $_SESSION['email'];
If your query causes you problems after that, try concatenating $email
$sql = "SELECT * FROM users WHERE EMAIL='".$email."';";
I am using the following codes in my login.php and index.php files.
I get the This webpage has a redirect loop error in the browser.
I know the issue is caused by the logic in the login.php file by the following code:
$existCount = mysqli_num_rows($query); // count the row nums
if ($existCount == 1) { // evaluate the count
$row = mysqli_fetch_array($query, MYSQLI_ASSOC);
$_SESSION["id"] = $row["id"];
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
header("location: http://$storeShop.mysite.com/index.php");
exit();
} else {
echo 'That information is incorrect, try again Click Here';
exit();
}
specifically this line: header("location: http://$storeShop.mysite.com/index.php");
I just do not know how I can fix this issue!
LOGIN.PHP
<?php
session_start();
ob_start();
if (isset($_SESSION["manager"])) {
/*
IF THE USER IS LOGGED IN THE CODE BELOW SENDS THEM TO THEIR OWN SUBDOMAIN NAME
WHICH IS STORED IN $_SESSION["storeShop"].
CHANGE "REST_OF_URL" TO THE VALID DOMAIN IN THE HEADER FUNCTION.
BUT DON'T REMOVE THE . (DOT)
*/
header("Location: http://$_SESSION[storeShop].mysite.com/index.php");
exit();
// END OF EDIT.
}
?>
<?php
if (isset($_POST["email"]) && isset($_POST["password"])) {
$manager = $_POST["email"]; // filter everything but numbers and letters
$password = (!empty($_POST['password'])) ? sha1($_POST['password']) : ''; // filter everything but numbers and letters
$storenameTable = $_REQUEST['storeShop'];
// Connect to the MySQL database
include "config/connect.php";
$sql = "SELECT members.id, members.email, members.password, members.randKey, members.storeShop, storename.email, storename.password, storename.randKey, storename.storeShop
FROM members
INNER JOIN storename ON members.randKey = storename.randKey
WHERE members.email = '$manager'
AND members.password = '$password'
";
$result = mysqli_query($db_conx,"SELECT storeShop FROM members WHERE email='$manager' AND password='$password'");
while($row = mysqli_fetch_array($result))
{
$email = $row["email"];
$password = $row["password"];
$storeShop = $row["storeShop"];
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
$_SESSION['storeShop'] = $storeShop;
}
// query the person
// ------- MAKE SURE PERSON EXISTS IN DATABASE ---------
$query = mysqli_query($db_conx, $sql);
if (!$query) {
die(mysqli_error($db_conx));
}
$existCount = mysqli_num_rows($query); // count the row nums
if ($existCount == 1) { // evaluate the count
$row = mysqli_fetch_array($query, MYSQLI_ASSOC);
$_SESSION["id"] = $row["id"];
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
header("location: http://$storeShop.mysite.com/index.php");
exit();
} else {
echo 'That information is incorrect, try again Click Here';
exit();
}
}
?>
INDEX.PHP
<?php
session_start();
ob_start();
if (!isset($_SESSION["manager"])) {
header("location: login");
exit();
}
/*
THE CODE BELOW COMPARES THE SUBDOMAIN TO THE USER'S STORESHOP SESSION
IF THEY DON'T MATCH IT REDIRECTS THEM TO THEIR SUBDOMAIN.
CHANGE "REST_OF_URL" TO THE VALID DOMAIN IN THE HEADER FUNCTION.
BUT DON'T REMOVE THE . (DOT)
*/
else {
$url = $_SERVER["HTTP_HOST"];
$user_subdomain = explode(".", $url);
if($_SESSION["storeShop"] != $user_subdomain[0]) {
header("Location: http://$_SESSION[storeShop].mysite.com/index.php");
}
}
ob_end_flush();
// Be sure to check that this manager SESSION value is in fact in the database
$managerID = preg_replace('#[^0-9]#i', '', $_SESSION["id"]); // filter everything but numbers and letters
$manager = $_POST["email"]; // filter everything but numbers and letters
$password = (!empty($_POST['password'])) ? sha1($_POST['password']) : ''; // filter everything but numbers and letters
$storenameTable = $_REQUEST['storeShop'];
// Run mySQL query to be sure that this person is an admin and that their password session var equals the database information
// Connect to the MySQL database
include "config/connect.php";
$sql = "SELECT members.id, members.email, members.password, members.randKey, members.storeShop, storename.email, storename.password, storename.randKey, storename.storeShop
FROM members
INNER JOIN storename ON members.randKey = storename.randKey
WHERE members.email = '$manager'
AND members.password = '$password'
"; // query the person
// ------- MAKE SURE PERSON EXISTS IN DATABASE ---------
$query = mysqli_query($db_conx, $sql);
if (!$query) {
die(mysqli_error($db_conx));
}
$result = mysqli_query($db_conx,"SELECT storeShop FROM members WHERE email='$manager' AND password='$password'");
while($row = mysqli_fetch_array($result))
{
$email = $row["email"];
$password = $row["password"];
$storeShop = $row["storeShop"];
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
$_SESSION['storeShop'] = $storeShop;
}
?>
could someone please point me in the right direction?
Thanks in advance.
You have started another session in index.php using session_start()
Remove the session_start() from index.php page and confirm if it is working fine
You're redirecting users to a different subdomain, and probably losing all your session data in the process.
Before you call session_start(), make sure your cookies are valid for the whole domain, i.e.,:
session_set_cookie_params(0, '/', '.mysite.com');
session_start();
More information here
Edit: Some other things you should look into:
(1) After the user has been redirected to "login" (header("location: login");), which of your scripts will process the next request? (Did you mean login.php?)
(2) What does login.php do when it receives a GET request (without an active session)?
I'm trying to display the users first name after they login. They login using their email and password. Though, I would like to collect their first name and display it. Their name is in the same table that the email/password are in. Traditionally, I would use a session ID like this below.
<?php
session_start();
$_SESSION['first'] = $first;
?>
But this typically is for submitted data in a form and is used after the form has been authenticated. My question is, how would I gather data from the mySQl table rather than collecting it from the form and be able to have it has a session ID?... if that makes sense
In your script where they login...just fetch the row and store into session...
Im using PDO, because thats much safer than the deprecated mysql_* functions you use in your login example.....
//start the session
session_start();
//Get their credentials, as follows...
$name = $_POST['username'];
$pass = md5($_POST['password']);
$stmt = $db->prepare("SELECT * FROM admin WHERE username=? AND password=?");
$stmt->execute(array($name, $pass));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row > 0 ) {
//Store users info in a session
$_SESSION["username"] = $row["username"];
$_SESSION["firstname"] = $row["firstname"];
$_SESSION["auth"] = "set";
//Redirect to the user area, where you can echo their name
header ("Location: /app");
//Once in the user area, you can just echo their name like so...
//echo "Hello ".$_SESSION['username'].", Welcome to my site";
} else {
//Redirect back to login if their info is incorrect
header('location: /login');
//whatever your login page name might be...
}
But heres the code, if you don't wanna bother changing your site to utilizing PDO...
include("db.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$username=mysql_real_escape_string($_POST['username']);
$password=md5(mysql_real_escape_string($_POST['password']));
$sql="SELECT id, username, firstname FROM admin WHERE username='$username' and passcode='$password'";
$result=mysql_query($sql);
$row = mysql_fetch_row($result);
if(count($row)>0)
{
$_SESSION['auth'] = 'set';
$_SESSION['username'] = $row['username'];
$_SESSION['firstname'] = $row['firstname'];
header ("Location: /app");
}
else
{
$error="Your Hngout credentials are incorrect";
}
}
Select the first name (and any other fields you desire) when checking the user name and password match.
if (!isset($_SESSION)) session_start();
$sql=sprintf("SELECT email, firstname FROM users WHERE email=%s AND password=%s",
$_POST["email"], $_POST["password"]);
//You'd better use parameterized query
$result = mysqli->query($sql);
$row = $result->fetch_assoc();
if(mysqli->num_rows > 0)
{
$_SESSION["email"] = $row["email"];
$_SESSION["firstname"] = $row["firstname"];
}
else
{
//operation for no matches
}
I have this php member page which will show a very basic information from the mysql database.
The issue that i noticed is that if you are logged out and visit the members page i.e. http://www.mywebsite.co.uk/member.php?id=17 and refresh the page from the browser, it will log you into the users account. and it doesn't really matter where and who it is. it will just logs the visitors into that account with id 17 or any other id on PAGE Refresh!!
this is my code for member.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<?php
session_start(); // Must start session first thing
// See if they are a logged in member by checking Session data
$toplinks = "";
if (isset($_SESSION['id'])) {
// Put stored session variables into local php variable
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '' . $username . ' •
Account •
Log Out';
} else {
$toplinks = 'Register • Login';
}
?>
<?php
// Use the URL 'id' variable to set who we want to query info about
$id = preg_replace("[^0-9]", "", $_GET['id']); // filter everything but numbers for security
if ($id == "") {
echo "Missing Data to Run";
exit();
}
//Connect to the database through our include
include_once "config/connect.php";
// Query member data from the database and ready it for display
$sql = "SELECT * FROM members WHERE id='$id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$count = mysqli_num_rows($query);
if ($count > 1) {
echo "There is no user with that id here.";
exit();
}
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$username = $row["username"];
$_SESSION['username'] = $username;
$userid = $row["id"];
$_SESSION['id'] = $userid;
// Convert the sign up date to be more readable by humans
$signupdate = strftime("%b %d, %Y", strtotime($row['signupdate']));
}
?>
anyone can spot the reason why this is happening?
Thanks
Because obviously you're making them logged in. Checkout this line;
$_SESSION['id'] = $userid;
What's your main purpose with this line ?
// Use the URL 'id' variable to set who we want to query info about
$_SESSION['id'] = $userid;
That's the issue right there. Don't pull in data from the url if you want your application to be secure.
After you've checked that their username and password are correct set a variable equal to their user ID and use that value to log them in.