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"; ?>
Related
I am trying out simple PHP page. I am trying out the following:
<?php
include("db/db_config.php");
session_start();
$user_check=$_SESSION['login_user'];
$ses_sql = mysqli_query($bd, "SELECT username FROM cmn_users where username='$user_check'");
$row=mysqli_fetch_array($ses_sql);
$login_session=$row['username']; //get session username
echo ("<p style='text-align:left;'><h1>HEADER WILL COME UP <span style='float:right;'><a href='/admin.php'>ADMIN</a> | <a href='/logout.php'>Logout</a></h1></span></p>");
?>
I want to show admin page (link) only for a particular user. Like admin should be hidden near loggout if admin user doesn't login...How do I do it?
I have got session's userID but I don't know how control the text in php/html.
Help on this will be great.
Thanks!
If session userId is this then show admin
The semantics of your statement are your exact code:
if ($_SESSION['username'] == 'admin') {
// output the admin stuff
}
(Or however you check if the user is an admin. Based on username, some identifier, something else, etc. Your question doesn't specify.)
So you'd output whatever is before the admin link, then conditionally output the admin link, then output whatever is after it. Something like this:
echo "<p style='text-align:left;'><h1>HEADER WILL COME UP <span style='float:right;'>";
if ($_SESSION['username'] == 'admin') {
echo "<a href='/admin.php'>ADMIN</a> | ";
}
echo "<a href='/logout.php'>Logout</a></h1></span></p>";
There are many other ways you can structure it as well. Perhaps store the resulting links in variables and conditionally concatenate them as needed, then echo the result of that only once at the end.
But the concept is the same however you do it. If the user is an admin, output the admin link. That way if the user is not an admin, they never see that link.
Note: The admin page itself must also implement security. There is nothing to stop a user from guessing the link and trying to open that page. Do not consider the approach in your question to be security. This is nothing more than user experience.
you need to store html links in your variables, and use them where needed, like this,
<?php
include("db/db_config.php");
session_start();
$user_check=$_SESSION['login_user'];
$ses_sql = mysqli_query($bd, "SELECT username FROM cmn_users where username='$user_check'");
$row=mysqli_fetch_array($ses_sql);
$login_session=$row['username']; //get session username
$adminLink = " <a href='/admin.php'>ADMIN</a> | ";
$logoutLink = " <a href='/logout.php'>Logout</a>";
?>
// suppose your html header link container
<div>
<p style='text-align:left;'><h1>HEADER WILL COME UP <span style='float:right;'><?php echo $adminLink.$logoutLink ?>
</h1></span></p>
</div>
============================================
for blocking acces on admin page
<?php
// start session
session_start();
// check if username is admin
replace it with your admin user name
$adminUsername = "admin";
if($_SESSION['login_user'] !== $adminUsername){
// isn't admin, redirect them to a different page
header("Location: /someotherpage.php");
}
?>
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.
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'];
// ....
}
I have a homework which is creating a web page which user can share photos or texts in their profile. But I am stuck at using login information to do it.
Here is my login.html:
<form method="post" action="login.php">
<br><label for="username">Username:</label></br>
<input type="text" id="username" name="username">
<br><label for="password">Password:</label></br>
<input type="password" id="password" name="password">
<div id="lower">
<br><input type="submit" value="Login"></br>
<p>
Not yet registered?
Click here to register
</p>
</div><!--/ lower-->
</form>
and here is my login.php:
?php
$con=mysqli_connect("localhost","root","","webpage");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_POST['username'];
$password = $_POST['password'];
$sql=mysqli_query($con,"SELECT * FROM user WHERE username='$username' and password='$password'");
if (!mysqli_fetch_assoc($sql)) {
die("You entered wrong username/password.");}
while ($sql){
$sql2="SELECT * FROM user WHERE username='$username' and approval = 1";
$res = mysqli_query($con,$sql2);
if (!$res) {
echo "Your account isn't approved yet. Please wait for approval. Thanks :)";}
else echo 'You have succesfully logged in.';
header('Location: http://localhost/project2/redirect.html');
}
mysqli_close($conn);
?>
From here, I am stuck. I don't know what to do to use the username that the user has entered. What am I suppose to do?
Thanks.
You can set the username in session which can be used till the session is cleared..ie till the user logs out or close the browser
A session is a way to store information (in variables) to be used
across multiple pages.
Unlike a cookie, the information is not stored on the users computer.
By default, session variables last until the user closes the browser.
Thus, Session variables hold information about one single user, and are available to all pages in one application.
A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
To Set Session variables
<?php
// Start the session
session_start();
$username = $_POST['username'];
// Set session variables
$_SESSION["uname"] =$username;
?>
To Get Session variable's value
<?php
session_start();
$username =$_SESSION["uname"];
?>
To Destroy the Session
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
Cookies! Yum!
http://www.w3schools.com/js/js_cookies.asp
Do some research here, try it out, and come back if you still can't get it.
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.