I am constructing a social networking site. Users who register and log in correctly are redirected to home.php with a $_SESSION made accordingly.
But I have manually made an admin user with the username of freddy (the username is required to log in). What I am trying to state is that "if the username is equal to freddy, then take him to admin_home.php".
What I have tried is to create two separate $_SESSION's.
$_SESSION created for normal user:
// if the user credentials are correct, log the user in:
$_SESSION["user_login"] = $user_login;
header( "Location: home.php" ); // refresh page
exit;
}
$_SESSION created for admin:
if ($account_type == "admin"){
// Create seperate session for admin
$_SESSION["user_login"] = $admin_login;
header( "Location: admin_home.php" ); // refresh page
exit;
}
Full query:
<?php
$user_query = mysqli_query ($connect, "SELECT * FROM users WHERE username = '$user_login' AND password = '$decrypted_password' AND closed='no' LIMIT 1");
$check_for_user = mysqli_num_rows ($user_query); // checking to see if there is infact a user which those credentials in the DB
if ($check_for_user==1){
while ($row = mysqli_fetch_array($user_query)){
$user_id = $row['id'];
$account_type = $row['account_type'];
}
// if the user credentials are correct, log the user in:
$_SESSION["user_login"] = $user_login;
header( "Location: home.php" ); // refresh page
exit;
}
if ($account_type == "admin"){
// Create seperate session for admin
$_SESSION["user_login"] = $admin_login;
header( "Location: admin_home.php" ); // refresh page
exit;
}
else {
// if user row does not equal 1 ...
echo "<div class='wrong_login'>
<p> Username or password is incorrect, please try again. </p>
</div>";
exit();
}
}
?>
With the current code, logging in with the username freddy - which should take me to admin_home.php, takes me to home.php which is not what I want.
First a quick suggestion. You should not store plain-text passwords if you want your users to trust you. See this doc about hashing passwords, especially the part about salting your hashes.
I would say best practice would be to create a user class, matching your database table, and create an instance of it when the user logs in, and store that class instance in your session variable. Currently you don't store things like user ID, or account type, which you'll probably want to use later.
The problem with your code as it is written, as #FirstOne points out, is that you are exiting as soon as the user is logged in correctly, instead of checking their account type first.
Related
i am creating login page where user will be redirected to his/her profile page. Profile page contains the articles of that user...
I have problem in login page, actually i want to store user id in
session from login page.. as i am storing user_email in session and it
does successfuly.. but it gives error on user_id session (undefined
index)....
addition
i want to show articles of logged in user through user_id session...
Here is the code of login page..
<?php
if(isset($_POST['login'])){
$user_email=mysqli_real_escape_string($con,$_POST['user_email']);
$user_password=mysqli_real_escape_string($con,$_POST['user_password']);
$encrypt= md5($user_password);
$check_login="select * from users where customer_email='$user_email'
AND customer_pass='$user_password'";
$run_login= mysqli_query($con, $check_login);
$row = mysqli_fetch_array($run_login);
$num = mysqli_num_rows($run_login);
$user_id=['customer_id'];
if($num==1){
$_SESSION['customer_email']="$user_email";
$_SESSION['customer_id']="$user_id";
echo "<script>window.open('index.php','_self')</script>";
}
else{
echo "This Username Doesnt Exists or Empty Login !";
}
}
?>
</div>
Step 1:
Do not forget to put session_start();
Step 2:
Change $user_id=['customer_id']; to $user_id=$row['customer_id'];
You must set $user_id only if there is a return from DB (otherwize you don't know this id)
if($num==1){
$user_id=$row['customer_id'];
// ....
}
Can anyone help me?
Im still newbie in using most of the php stuff here. I kinda having a problem with creating multi users using session.
What I want to do is this. An account exclusive only of admin and an account only for normal users.
Admin privileges will be able to access pages for admins only while normal users who logs in, will be able to access pages meant for users only.
So far Ive created a single user login credentials. Which is for admins only. Im really confused how do I add non-admin in order to access pages only for them.
Can anyone help me with this code?
This is the home page
<?php
//Initialize Session
session_start();
error_reporting(E_ALL ^ E_NOTICE);
//$name = $_SESSION['username'];
if(isset($_SESSION['username']))
{
header('Location: index_admin.php');
}
?>
This is the admin page
<?php
// Inialize session
session_start();
// Check, if username session is NOT set then this page will jump to login page
if (!isset($_SESSION['username']))
{
header('Location: index.php');
}
?>
This is the login form
<form action="login.php" method="post">
<input type="text" name="uname" placeholder="USERNAME . . . " autofocus/>
<br/>
<input type="password" name="pword" placeholder="PASSWORD . . . " />
<br/>
<center><input type="submit" name="submit" value="LOGIN" /><button type="reset" value="Reset" />RESET</button></center>
</form>
This is the login.php
<?php
session_start();
include("config.php");
$login = mysql_query("SELECT * FROM users WHERE (username = '" . mysql_real_escape_string($_POST['uname']) . "') and (password = '" . mysql_real_escape_string($_POST['pword']) . "')");
// Check username and password match
if (mysql_num_rows($login) == 1)
{
// Set username session variable
$_SESSION['username'] = $_POST['uname'];
// Jump to secured page
header('Location: index_admin.php');
}
else
{
// Jump to login page
header('Location: index.php');
}
?>
This is the database
user_tbl
id = 1
username = admin
password = 12345
Thanks in advance for the assitance.
It seems from your question that you'll use the same login page for both administrative users and non-administrative users. That's the case for which I'll offer an answer.
In the process of validating a particular user's name and password, you need to determine what privilege level that user has been granted. You might have a column called "privilege" in your user table.
usr_tbl needs to look something like this:
id username password privilege
1 admin W$^%^$%^%^% admin
2 reggel DJDT&646364 user
3 ollie DTHDHFGEERT user
Upon login, you'l read the usr_table and pull that user's value out of the column and store it as a session variable something like this:
$_SESSION['privilege'] = $privilege; /* from user table */
Then you can do logic like this to decide what your user should see, and what she should be able to do.
if ( 'admin' == $_SESSION['privilege'] ) {
// Jump to secured page
header('Location: index_admin.php');
}
else {
// Jump to login page
header('Location: index.php');
}
In later page views, if your session logic is functioning correctly, the $_SESSION['privilege'] variable should continue to be available.
p.s. mysql_ APIs for security code? Really?
You need to add a new field in your database for user type (admin/normal_user).
In your login script save the user type in session (admin/normal_user).
Now on every top of page check the session value of user type if it is admin let the page open and if it is normal_user redirect page to login.
ideally you need to expand on the data structure serving this code: Set up a table of users and a table of groups; the groups will imply access rights. When you submit the login page, check the database for the username, then:-
1) If no match, return to "access denied" screen
2) if match, xref with groups table to determine privilege level of this user. Then:-
2a) if admin, return to admin screen, setting appropriate session vars to store that decision.
2b) Else, return to normal user screen, ditto setting appropriate session vars.
Your core problem is that upon entering "the" homepage, you are simply checking if the username is set, and then taking the user to the admin screen. This is wrong. Try to split out your logic into smaller simpler steps, and consider the "if-else" logic in human terms. "What do I want to happen?" then "What do I need to know to ascertain how to do that?".
Good luck!
I use the same but I got one error
This page does not work local host has redirected you too often.
Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS
<?php
// Include config file
require_once "config.php";
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
$_SESSION['privilege'] = $privilege; /* from user table */
if ( 'admin' == $_SESSION['privilege'] ) {
// Jump to secured page
header('Location: index_admin.php');
}
else {
// Jump to login page
header('Location: index.php');
}
?>
<?php include "theme/header.tpl"; ?>
<div class="page-header">
<h1>Hi, <b><?php echo htmlspecialchars($_SESSION["username"]); ?></b>. Welcome to our site.</h1>
</div>
<p>
Reset Your Password
Sign Out of Your Account
Users
</p>
<?php include "theme/footer.tpl"; ?>
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM tz_members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if($row['usr'])
{
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$id = $row['id'];
$_SESSION['rememberMe'] = $_POST['rememberMe'];
// Store some data in the session
setcookie('tzRemember',$_POST['rememberMe']);
}
else $err[]='Wrong username and/or password!';
}
if($err)
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
$goHere = 'Location: /index2.php?id=' . $id;
header($goHere);
exit;
}
I have the following code that once logged in, it $_GET the id and prepends to the url like index2.php?id=5 . How do I keep this id=5 in the URL no matter WHAT link they click on??
This id is grabbed from this:
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$id = $row['id'];
What I want to do
Well way i have it setup, you login, it then sends you to the homepage such as index2.php?id=[someint] , if you click another link say 'prof.php', it removes the id=[someint] part, I want to keep it there in the url, so as long as a user is LOGGED in -- using my code above, the url might read: index.php?id=5, then go to another page it might read prof.php?id=5, etc, etc. This integer would obviously be dynamic depending on WHO logged in
Instead of passing around an ID in the URL, consider referring to the id value in the $_SESSION variable. That way the user can't modify the URL and see data they aren't supposed to see (or much worse), and you don't have to worry over appending it to every URL and reading it into a value every time you go to process a script. When the user logs in, you determine their ID - read it from a database, determine it realtime, whatever. Then store it in the $_SESSION and refer to it as needed. You can even use this as part of a check to see if the user is logged in - if they have no $_SESSION['id'] value, something is wrong and you make them log in.
The query string isn't the place for that, for a whole host of reasons. The most obvious one is that I can log in with a valid account, then change the number in the URL and it'll think I'm someone else.
Instead, just continue using the session as it's the proper way.
If you REALLY want to do it, you'd probably want to write a custom function for generating links
function makeLink ($link, $queryString = '')
{
return $link . '?id=' . (int) $_SESSION['id'] . ((strpos($queryString, '?') === 0) ? substr($queryString, 1) : $queryString);
}
called like
Click me
As a basic auth example using the ID...
<?php
// Session start and so on here
if (!isset($_SESSION['id']))
{
// Not logged in
header('Location: /login.php');
exit;
}
http://www.knowledgesutra.com/forums/topic/7887-php-simple-login-tutorial/ is a pretty straightforward full example of it.
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 have been trying to learn session management with PHP... i have been looking at the documentation at www.php.net and looking at these EXAMPLES. BUt they are going over my head....
what my goal is that when a user Logs In... then user can access some reserved pages and and without logging in those pages are not available... obviously this will be done through sessions but all the material on the internet is too difficult to learn...
can anybody provide some code sample to achieve my goal from which i can LEARN or some reference to some tutorial...
p.s. EXCUSE if i have been making no sense in the above because i don;t know this stuff i am a beginner
First check out wheather session module is enabled
<?php
phpinfo();
?>
Using sessions each of your visitors will got a unique id. This id will identify various visitors and with the help of this id are the user data stored on the server.
First of all you need to start the session with the session_start() function. Note that this function should be called before any output is generated! This function initialise the $_SESSION superglobal array where you can store your data.
session_start();
$_SESSION['username'] = 'alex';
Now if you create a new file where you want to display the username you need to start the session again. In this case PHP checks whether session data are sored with the actual id or not. If it can find it then initialise the $_SESSION array with that values else the array will be empty.
session_start();
echo "User : ".$_SESSION['username'];
To check whether a session variable exists or not you can use the isset() function.
session_start();
if (isset($_SESSION['username'])){
echo "User : ".$_SESSION['username'];
} else {
echo "Set the username";
$_SESSION['username'] = 'alex';
}
Every pages should start immediately with session_start()
Display a login form on your public pages with minimum login credentials (username/password, email/password)
On submit check submitted data against your database (Is this username exists? ยป Is this password valid?)
If so, assign a variable to your $_SESSION array e.g. $_SESSION['user_id'] = $result['user_id']
Check for this variable on every reserved page like:
<?php
if(!isset($_SESSION['user_id'])){
//display login form here
}else{
//everything fine, display secret content here
}
?>
Before starting to write anything on any web page, you must start the session, by using the following code at the very first line:-
<?php
ob_start(); // This is required when the "`header()`" function will be used. Also it's use will not affect the performance of your web application.
session_start();
// Rest of the web page logic, along with the HTML and / or PHP
?>
In the login page, where you are writing the login process logic, use the following code:-
<?php
if (isset($_POST['btn_submit'])) {
$sql = mysql_query("SELECT userid, email, password FROM table_users
WHERE username = '".mysql_real_escape_string($_POST['username'])."'
AND is_active = 1");
if (mysql_num_rows($sql) == 1) {
$rowVal = mysql_fetch_assoc($sql);
// Considering that the Password Encryption used in this web application is MD5, for the Password Comparison with the User Input
if (md5($_POST['password']) == $rowVal['password']) {
$_SESSION['username'] = $_POST['username'];
$_SESSION['email'] = $rowVal['email'];
$_SESSION['userid'] = $rowVal['userid'];
}
}
}
?>
Now in all the reserved pages, you need to do two things:-
First, initialize / start the session, as mentioned at the top.
Initialize all the important configuration variables, as required by your web application.
Call an user-defined function "checkUserStatus()", to check the availability of the User's status as logged in or not. If the return is true, then the web page will be shown automatically, as no further checking is required, otherwise the function itself will redirect the (guest) viewer to the login page. Remember to include the definition of this function before calling this function, otherwise you will get a fatal error.
The definition of the user-defined function "checkUserStatus()" will be somewhat like:-
function checkUserStatus() {
if (isset($_SESSION['userid']) && !empty($_SESSION['userid'])) {
return true;
}
else {
header("Location: http://your_website_domain_name/login.php");
exit();
}
}
Hope it helps.
It's not simple. You cannot safely only save in the session "user is logged in". The user can possibly write anything in his/her session.
Simplest solution would be to use some framework like Kohana which has built-in support for such function.
To make it yourself you should use some mechanisme like this:
session_start();
if (isset($_SESSION['auth_key'])) {
// TODO: Check in DB that auth_key is valid
if ($auth_key_in_db_and_valid) {
// Okay: Display page!
} else {
header('Location: /login/'); // Or some page showing session expired
}
} else {
header('Location: /login/'); // You're login page URL
exit;
}
In the login page form:
session_start();
if (isset($_POST['submit'])) {
// TODO: Check username and password posted; consider MD5()
if ($_POST['username'] == $username && $_POST['password'] == $password) {
// Generate unique ID.
$_SESSION['auth_key'] = rand();
// TODO: Save $_SESSION['auth_key'] in the DB.
// Return to some page
header('Location: ....');
} else {
// Display: invalid user/password
}
}
Missing part: You should invalidate any other auth_key not used after a certain time.