When you log in by my login form authentication.php will check if the data from the inputs excists in the database. When there is a match the user will be directed to a page for his role so lets say the user is a admin he will be directed to admin.php. When the user is successfully logged in i want to show a message like welcome firstname lastname. In my database i have a field called firstname and a field called lastname. I hope someone can help me with this since i cannot seem to figure it out :(
authentication.php
<?php
session_start();
// Making a connection with the database.
$mysqli=new MySQLi("localhost", "root", "root", "portfolio");
$role="";
// Declaring the username and password input.
$username=filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$password=filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
// If role from members where username and password from inputs exicts in database bind parameters.
// If given parameters not excists in database die
if($query=$mysqli->prepare("SELECT `role` FROM members WHERE username=? AND password=?")) {
$query->bind_param("ss", $username, $password);
$query->execute();
$query->bind_result($role);
$query->fetch();
} else {
echo "Errors in the Query. ".$mysqli->error;
die();
}
// If $role is filled make session for username to check if logged in and session role for redirect page.
// If $role and $username is not filled invalid password, username combination.
if($role!="") {
$_SESSION['ingelogt']=$username;
$_SESSION['user_role']=$role;
$location="$role.php";
header("location: $location");
} else {
echo "Invalid password, username combination";
echo "<br/><a href='login.html'>Click to go back</a>";
}
?>
The page the admin will be directed to called admin.php
<?php
session_start();
// If session is not ingelogt lead back to index.php.
if(!isset($_SESSION['ingelogt'])) {
header("location: index.php");
}
// The role that has access to this page.
$page_role="admin";
$role=$_SESSION['user_role'];
// If a user with a different role visits wrong page.
if($role!=$page_role)
{
echo "You are not supposed to be here.";
die();
}
// Start new DOMDocument and load html file.
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTMLFile("admin.html");
libxml_use_internal_errors(false);
// If user is logged in add logg out icon in the menu.
if($_SESSION['ingelogt']) {
$oUl = $dom->getElementById('navUl');
$oList = $dom->createElement('li');
$oLink = $dom->createElement('a');
$oLink->setAttribute('href','logout.php');
$oI = $dom->createElement('i');
$oI->setAttribute('class','icon-logout');
$oLink->appendChild($oI);
$oList->appendChild($oLink);
$oUl->appendChild($oList);
}
// Save DOMDocument with html document.
echo $dom->saveHTML();
?>
If I'm misunderstanding you in any way, just give me a hint, and I will delete this answer. Although what I assume that you want to do is to print the greeting somewhere on the page, based off the user's first name and surname.
Basically, once you have declared a $_SESSION-element, you can access it at different pages (similar to $_COOKIE, but not identical). So the best solution for this is to initialize $_SESSION variables with the first- and last name you receive from the database, and then print those variables on the desired pages (same method as you've used with the role).
Firstly, you need to fetch the names in the database, which can be done by changing the if-statement in authentication.php to the following:
if($query=$mysqli->prepare("SELECT `role`, `firstname`, `lastname` FROM members WHERE username=? AND password=?")) //assuming that your columns are called `firstname` and `lastname`
To fetch these, you also need to change the row further down to:
$query->bind_result($role, $first, $last);
When using fetch on the next row, your variables will be put into their appropriate bound ones. So after that statement, you can do the following (preferably after the $_SESSION['user_role']=$role;):
$_SESSION["firstname"] = $first;
$_SESSION["lastname"] = $last;
After that point, you can echo the first- and last name wherever you want (it depends on where you want it to be put...). If you want it to appear at the top of admin.php, for instance, you can simply put this before $dom = new DOMDocument();:
echo "Hello " . $_SESSION["firstname"] . " " . $_SESSION["lastname"] . "!";
If you're confused where to put something, then try re-reading the given instructions. Most of my examples are simply things to replace (in which case, you just need to find the corresponding code), and if not that, I've tried to redirect you. Although realize that things like these are important to know without getting the code right in your hand, so I advice you to try to understand.
Related
I'm creating a profile page where the name of the user can be edited. I can't seem to figure out how to update the name of the user that is displayed at the top page (i.e. Hi Kana!) after a successful edit.
The name is generated using a session variable at the top of my page, $_SESSION['username']
<?php
session_start();
if(isset($_POST['submit']) && isset($_SESSION['newusername'])){
unset($_SESSION['username']); //clear existing username session
$_SESSION['username'] = $_SESSION['newusername']; //replace with the new username
echo $_SESSION['username'];
} else {
echo $_SESSION['username'];
}
?>
After hitting the submit button with a different name set on the text input it should change but it does not. These are the lines of codes after the code I mentioned above.
<?php
$textinput = $_POST['textinput'];
if(isset($_POST['submit']))
{
if(strlen($_POST['textinput']) < 2)) {
$errormessage = 'too short';
}
else
{
$_SESSION['newusername'] = $textinput; //setup a new session for the new username to be used above.
}
}
?>
Note that the two quoted set of codes are in the same page.
What happens is that the name still shows the previous name, which is supposedly overwritten. I tried refreshing the page but it still does not change, I need to submit again (2nd time) to show the new name.
You can and should drastically simplify your code. Currently there are a variety of unnecessary operations here. Consider semantically what you want to accomplish:
If the user submits their name, update the session with the new value. Then output the value.
That's it. Let the semantics of what you want to accomplish guide how you accomplish it. Start the session, check for the form post, conditionally update the value, output the current state of the value. For example:
<?php
session_start();
// update the value
if(isset($_POST['submit'])) {
$_SESSION['username'] = $_POST['textinput'];
}
// output the value
echo $_SESSION['username'];
?>
Maybe you'll want to add a sensible default in the absence of a username. That would just be something like:
<?php
session_start();
// set a default value
if (!isset($_SESSION['username'])) {
$_SESSION['username'] = "Default User";
}
// update the value
if(isset($_POST['submit'])) {
$_SESSION['username'] = $_POST['textinput'];
}
// output the value
echo $_SESSION['username'];
?>
I am trying in my PHP to make it to where if the Account database value matches 0 or 1 or 2 or 3 then it makes the login go to a certain page but so far it doesn't log me in and it doesn't take me to the page. Before I had a log in page but it sent it to a universally restricted page, but what I want is depending on what the User signed up for then he gets put this value(which I have already implemented) that if this page were to work than it would send him to one of four restricted sites upon login. What I can't get is the value to get pulled and used to send him upon login to the specific page.I am using Mysqli. Here is the code:
<?php require 'connections/connections.php'; ?>
<?php
if(isset($_POST['Login'])){
$Username = $_POST['Username'];
$Password = $_POST['Password'];
$result = $con->query("select * from user where Username='$Username'
AND Password='$Password'");
$row = $result->fetch_array(MYSQLI_BOTH);
$AccountPerm = $con->query("SELECT * FROM `user` WHERE Account =
?");
session_start();
$AccountPerm = $_SESSION['Account'];
if($AccountPerm == 0){
header("Location: account.php");
}
if($AccountPerm == 1){
header("Location: Account1.php");
}
if($AccountPerm == 2){
header("Location: Account2.php");
}
if($AccountPerm == 3){
header("Location: Account3.php");
}
}
?>
so far it doesn't log me in
Just to be sure, your Account.php, Account1.php, Accout2.php and Account3.php rely on $_SESSION['Account'] right? (The code below assume so)
As for your problem with both login and redirecting you forget a line :
$_SESSION['Account'] = $row['Account'];
Also, I removed
$AccountPerm = $con->query("SELECT * FROM `user` WHERE Account =
?");
You code should look like :
<?php require 'connections/connections.php'; // NOTE: I don't close the php tag here ! See the "session_start()" point in the "Reviews" section below
if(isset($_POST['Login'])){
$Username = $_POST['Username'];
$Password = $_POST['Password'];
// TODO: Sanitize $Username and $Password against SQL injection (More in the "Reviews" section)
$result = $con->query("select * from user where Username='$Username'
AND Password='$Password'");
// TODO: Check if $result return NULL, if so the database couldn't execute your query and you must not continue to execute the code below.
$row = $result->fetch_array(MYSQLI_BOTH);
// TODO: Check if $row is NULL, if so the username/password doesn't match any row and you must not execute code below. (You should "logout" the user when user visit login.php, see the "Login pages" point in the "Reviews" section below)
session_start();
$_SESSION['Account'] = $row['Account']; // What you forgot to do
$AccountPerm = $_SESSION['Account'];
if($AccountPerm == 0){
header("Location: account.php");
}
if($AccountPerm == 1){
header("Location: Account1.php");
}
if($AccountPerm == 2){
header("Location: Account2.php");
}
if($AccountPerm == 3){
header("Location: Account3.php");
}
}
?>
Reviews
session_start()
Should be call at the top of your code. (It will probably end-up in a a shared file like connections.php that you will include in all of your file).
One reason is that session_start() won't work if you send ANY character to the user browser BEFORE calling session_start().
For exemple you close php tag after including connections.php, you may not know but you newline is actually text send to the browser !
To fix this you just have to not close your php tag, such as in
<?php require 'connections/connections.php'; ?>
if(isset($_POST['Login'])){
Login page
Make sure to logout (unset $_SESSION variables that you use to check if user is logged) the user in every case except if he enter the right username/password combinaison.
If the user is trying to login it may be a different user from the last time and we don't want him to be logged as somebody else if his username/password is wrong.
MySQL checks : You should always check what the MySQL function returned to you before using it ! (see the documentation !) Not doing so will throw php error/notification.
SQL injection : You must sanitize $Username/$Password before using them into your query.
Either you append the value with $con->real_escape_string() such as
$result = $con->query("SELECT * FROM user WHERE Account = '" . $con->real_escape_string($Username) . "' AND Password = '" . $con->real_escape_string($Password) ."')
or you use bind parameter, such as explained in this post (THIS IS THE RECOMMENDED WAY)
No multiple account pages
Your login page should redirect only to accout.php and within this page split the logic according with the $_SESSION['Account'] value.
Nothing stop you from including account1.php, account2.php, ... within account.php.
If you do so put your account1.php, account2.php, account3.php in a private folder that the user can't browse in.
(One of the method is to create a folder (such as includes) and put a file name .htaccess with Deny from all in it)
below is the authorisation script (from login). I want to send a user to a specific page depending on (new column called company to be added to database table) a user and their company.
Current script, even if someone can point me in the direction I would appreciate it:
<title>authorise</title>
<?php
session_start();
$un = $_POST['username'];
$pw = $_POST['password'];
if ($pw != ''){
$_SESSION['user'] = $un;
echo "Incorrect username / password";
}
try
{
$dbh = new PDO("mysql:host=localhost;dbname=login_site","root","black$23");
}
catch (PDOException $e){
echo $e->getMessage();
}
$query = "SELECT * FROM users WHERE LOWER(username)=:username";
$stmt=$dbh->prepare($query);
$stmt->bindValue(':username',strtolower ($_POST['username']));
$stmt->execute();
if ($stmt->rowCount() == 1)
{
$row=$stmt->fetch(PDO::FETCH_ASSOC);
require('blowfish.php');
require('bcrypt.class.php');
$bcrypt = new Bcrypt(4);
if($bcrypt->verify($_POST['password'],$row['password']))
{
echo"logged in!!";
header("Location: hollyfort/123.php");
}
}
?>
I think you need a table with the userID and a page id (or perhaps w/ the companyID and a pageID), so you can determine the page to be returned by the user or company. Maybe you even want both tables, e.g. if you want all employees of a company to get a certain site, but the CEO should get to a special site where he can see all his employees' activities.
you then first check, if an entry for that user exists (if it does, you return the page). if not, check if an entry for the company exists. if you cannot find an entry, you probably want to return a default page
all is ok - I setup company variables to check against the database column and it works :)
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 )) {
}
Hello I have a question. I have set up my login system with cookies and it works. But I wonder is there a more clean version of doing this.
<?
include('../config/db_config.php');
$username = $_COOKIE['user'];
$password = $_COOKIE['pass'];
$result = mysql_query("SELECT * FROM users WHERE isadmin = 1");
while($row = mysql_fetch_array($result))
{
if($username == $row['username'] && $password == $row['password'])
{
//User entered correct username and password
echo("ALLOW");
}
else
{
//User entered incorrect username and password
echo("DENY");
}
}
?>
You see I want all my content to be shown ONLY if I am logged in as admin. So what, now only way of doing this would be ECHO'ing out my HTML/PHP/Javascript instead of echoing ALLOW because if I just include("somepage.php") there that page would still be avialable for usage without logging in, and even if I do same check there I still would be ECHO'ing out everything.
Why are you loading every user, then comparing the username and the password? Wouldn't be easier to load a single user matching the username and the password?
Loading a single user will allow to remove the while().
In PHP, don't use mysql_query; do use PDO (if need, google for it to know why it's better).
Check your input (quite optional here, I agree).
Do never store passwords in plain text format.
You can probably do something like (I haven't used PHP/PDO for years, so the code may be inexact):
if (strlen($username)> 128)
{
// Something wrong. The username is too long.
}
$hash = sha1($password);
$sth = $dbh->prepare('if exists(select * from users where isadmin = 1 and username = :username and password = :password) select 1 else select 0');
$sth->bindParam(':username', $username, PDO::PARAM_STR, 128);
$sth->bindParam(':password', $hash, PDO::PARAM_STR, 40);
$sth->execute();
$isFound = $sth->fetchAll();
if ($isFound)
{
// User entered correct username and password.
echo 'ALLOW';
}
You could set a session variable on your login page (or any page that checks the login) that stores whether or not they're logged in and it will persist across pages. Then you can simple wrap your admin html in an if statement like so:
<?php
if ($_SESSION['isAdmin'] == true) {
?>
<p>My admin html</p>
<?php
} else {
?>
<p>My non-admin html</p>
<?php
}
?>
To save the info in a session, just add this to the part where you have echo("ALLOW");:
$_SESSION['isAdmin'] = true;
You'll also want to add session_start(); to the top of the script.
I would suggest that you do something like that only once, when the user first accesses the page, and then set a $_SESSION['is_admin'] or something for the rest of the time, so that you don't have to make an extra db call each page.
You could always put your "somepage.php" above the document root. This is a common way of preventing direct execution.
For example, if your webserver looks like 'project/public_html/index.php' put your admin-only include in 'project/somepage.php' then reference it using something like include("../somepage.php").
Obviously this will need adjustment according to the real paths you use.