I am trying to figure out how to display user information after they've logged in. I am not sure whether I should create a single php file which would display user information depending on the session or should I create different files for different users. I am also having trouble grabbing the header.
here's my code for login.php
<?php
session_start();
require 'dbh.php';
$username = $_POST['uname'];
$password = $_POST['pwd'];
$sql = "SELECT * FROM registeredusers WHERE UserName = '$username'";
$result = mysqli_query($connection,$sql);
$row = mysqli_fetch_assoc($result);
$hashed_Password = $row['Password'];
$Dehash = password_verify($password,$hashed_Password);
if($Dehash == 0){
echo "username or password is incorrect";
exit();
} else{
$sql = "SELECT * FROM registeredusers WHERE UserName='$username' AND Password='$hashed_Password'";
$result = mysqli_query($connection,$sql);
if (!$row=mysqli_fetch_assoc($result)){
echo "Your User Name or Password is incorrect";
}
else {
$userid = $row['id'];
$_SESSION['UserName'] = $row['UserName'];
header("Location: userhomepage.php?user_id=".$userid);
}
}
?>
The following code redirects to userhomepage.php and the user ID is in the url can someone also tell me how do I grab the user ID from the url? I only started coding in PHP a week ago I am fairly new so if guys have any pointers for me that would be great.
I am not sure whether I should create a single php file which would display user information depending on the session or should I create different files for different users.
You should create a single page that displays user information based on session... you don't want to have to hand-make a new page every time a user signs up!
how do I grab the user ID from the url
echo $_GET["user_id"];
Related
so i'm having trouble and i really have no idea why i'm having this issue because all looks well. But basically i'm trying create multiple user levels for a web page i'm making. For some reason only the regular user role is working at the moment. Basically I want admins to be led to a different user interface. If anyone knows any good content on how to make certain pages only available when a session is started that would be very helpful because that would be my next step after I solve this, also how to create a difference in regular user sessions and admin sessions if that makes sence... But back to my real problem, please tell me why admins arent being led to my admin.php page.. I'm posting the code below.
<?php
session_start();
include 'db.php';
mysqli_select_db($conn, 'users');
$user = $_POST ['user'];
$pass = $_POST ['pass'];
$reg = '0';
$admin = '1';
$hashedpassword = password_hash ($pass, PASSWORD_DEFAULT);
//this query is for admin users **dont forget to change active to 1 within
db
$qa = "select * from users where username ='$user' and active = '0' and admin = '$admin'";
//this query is for regular users
$q = "select * from users where username ='$user' and active = '0' and admin
= '$reg'";
//these will run the querys above (a = admin)
$resulta = mysqli_query($conn, $qa);
$result = mysqli_query($conn, $q);
//will count rows and verify admin users
$numa = mysqli_num_rows($resulta);
$rowa = mysqli_fetch_array($resulta, MYSQLI_ASSOC);
//will count rows and verify regular users
$num = mysqli_num_rows($result);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if(password_verify($pass,$row['password']))
{
if ($num == 1) {
$_SESSION['username'] = $user;
header('location:index.php');
}
else if (password_verify($pass,$rowa['password']))
{
if ($numa == 1) {
$_SESSION['username'] = $user;
header('location:admin.php');
}
}
}
echo mysqli_error($conn);
?>
your code seems a little confusing to me, so I've sampled it down, instead of running two different queries, why not just one.
Look at this code below, this will help you transfer to admin page when admin logs in, and redirects you to regular page in case of all others.
All I am doing is checking the row value, instead of checking the count again.
<?php
session_start();
include 'db.php';
mysqli_select_db($conn, 'users');
$user=mysqli_real_escape_string($conn,$_POST['username']);
$pass=mysqli_real_escape_string($conn,$_POST['password']);
$hashedpassword = password_hash ($pass, PASSWORD_DEFAULT);
$sql="select * from users where username ='$user' and active = '0'";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_array($result, MYSQLI_ASSOC);
if(password_verify($mypassword, $row["pass"])) {
$_SESSION['username']=$user;
if($row["admin"] == "1")
header("location: admin.php");
else if($row["admin"]=="0")
header("location: index.php");
}
else
echo mysqli_error($conn);
?>
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 )) {
}
HI
Could I fetch ALL the info from the user when he/she login and store it in sessions instead of having this piece of code on top of all pages to get username, email etc of the logged in user?
$userq = mysql_query("SELECT * FROM users WHERE id = {$_SESSION['id']}");
$auth_user = mysql_fetch_assoc($userq);
Login.PHP
$sql = mysql_query("SELECT id FROM users
WHERE username = '$username' AND password = '$password'");
if (mysql_num_rows($sql) < 1) {
echo "Wrong username/password";
} else {
$_SESSION['id'] = mysql_result($result, 0, 'id');
header("Location: index.php");
}
Yes you (probably) could.
A couple of things to consider, though :
you might want to keep in session only what you need (to not have a giant session file with lots of useless data)
if the user updates his profile, you'll have to store the new data both in database, and in session -- which means a bit more works on the "edit profile" page.
if some other user (like an admin) edits a user's profile, you won't be able to change the session data of that user, and the updates will be loaded from database into the session only the next time the user logs in.
if this is something that happens frequently, you might want to refresh the data from databse every couple of minutes (but it's rarely the case on a "normal" website)
yeah, instead of getting just the id in the query, you get everything:
$sql = mysql_query("SELECT * FROM users
WHERE username = '$username' AND password = '$password'");
if (mysql_num_rows($sql) < 1) {
echo "Wrong username/password";
} else {
$_SESSION['userdata'] = mysql_result($result, 0);
header("Location: index.php");
}
So recently I learned how to properly add a username and password to a database.
My database is usersys, and the table storing user information is called userdb. The table has two columns - username (primary), password.
The registration form works great, enters the users input into the database correctly and also checks to see whether the user's username is already in the database or not.
With that said, I am asking if anyone could help me create a login script. So far, this is what I have:
$username = $_POST['username'];
$password = $_POST['password'];
$displayname = $_POST['username'];
$displayname = strtolower($displayname);
$displayname = ucfirst($displayname);
echo "Your username: " . $displayname . "<br />";
mysql_connect("localhost", "root", "******") or die(mysql_error());
echo "Connected to MySQL<br />";
mysql_select_db("usersys") or die(mysql_error());
echo "Connected to Database <br />";
$lcusername = strtolower($username);
$esclcusername = mysql_real_escape_string($lcusername);
$escpassword = mysql_real_escape_string($password);
$result = mysql_query("SELECT * FROM userdb WHERE username='$esclcusername' AND password='$escpassword'") or die(mysql_error());
$row = mysql_fetch_array( $result );
$validateUser = $row['username'];
$validatePass = $row['password'];
The POST data is from the previous log in page. I want this script to check the table (userdb) and find the row for the username that the user entered from the previous form and verify that the password entered matches the username's password set in that row, in userdb table.
I also want some type of way to check whether or not if the username entered exists, to tell the user that the username entered does not exists if it can not be found in the table.
This is not a direct answer to this question but a GOOD value-add.
You should use MYSQL SHA1 function to encrypt the password before storing into the database.
$user = $_POST['userid'];
$pwd = $_POST['password'];
$insert_sql = "INSERT into USER(userid, password) VALUES($user, SHA1($pwd))";
$select_sql = "SELECT * FROM USER WHERE userid=$user AND password=SHA1($pwd))";
You can use sessions. Sessions are global variables that when set, stay with the user while he is browsing through the site.
Since you are learning PHP, try out this tutorial on the official website.
But what you would do in theory is when the username and password match, you set a session variable
$_SESSION["auth"] = true;
$_SESSION["user_id"] = $row["user_id"];
And then do a check to see if the user is authenticated.
One way to do it (DISCLAIMER: not necessarily best-practice):
$result = mysql_query("SELECT id FROM userdb WHERE username='$esclcusername' AND password='$escpassword'") or die(mysql_error());
$row = mysql_fetch_array( $result );
$id = (int)$row['id'];
if($id > 0) {
//log in the user
session_start();
$_SESSION['userId'] = $id;
$_SESSION['username'] = $displayname;
}
... and on pages that require authentication:
session_start();
if(!isset($_SESSION['userId'])) {
die('You need to be logged in!!!');
} else {
echo 'Welcome ' . $_SESSION['username'];
}
Read more about PHP sessions.
I like to use both $_SESSION and MYSQL Checks with any login POST. This should help get a few things started.
$username = mysql_real_escape_string($_POST[username]);
$password = strip_tags($_POST[password]);
$password = sha1($password);
if(isset($username) && isset($password) && !empty($username) && !empty($password))
{
$sql = mysql_query("SELECT * FROM users_column WHERE username = '$username' AND password = '$password'");
//Check the number of users against database
//with the given criteria. We're looking for 1 so
//adding > 0 (greater than zero does the trick).
$num_rows = mysql_num_rows($sql);
if($num_rows > 0){
//Lets grab and create a variable from the DB to register
//the user's session with.
$gid = mysql_query("SELECT * FROM users_column WHERE username = '$username' AND password = '$password'");
$row = mysql_fetch_assoc($gid);
$uid = $row[userid];
// This is where we register the session.
$_SESSION[valid_user] = $uid;
//Send the user to the member page. The userid is what the
//session include runs against.
header('Location: memberpage.php?userid='.$userid);
}
//If it doesn't check out -- throw an error.
else
{
echo 'Invalid Login Information';
}
}
NOTE: You would need to start the page file with session_start() and create a separate Session Check include stating with session_start() and then your progressions e.g. if($_SESSION[valid_user] != $userid) do something.
You could use a select statement to retreive from MySQL the password for the specified username. If you have an empty result set, then you do not have the username in the table.
If you need the user to be authenticated in more than one php page, then one choice whould be using sessions (http://www.php.net/manual/en/function.session-start.php).
Also, I think you should think about security, i.e. preventing SQL injection:
$variable = mysql_real_escape_string($_POST['variable'])
and avoiding to "die" (treating errors and returning user-friendly messages from the script).
I would also think about not storing passwords in your database. One way hashes with MD5 or SHA1 are a way of adding a layer of security at the db level.
See http://php.net/md5 or http://php.net/sha1 for further information.
I agree with the idea if using SESSION variables while authenticating the user.
The easy way to authenticate the user is as follows
//connect the mysql_db
$mysql_connect()
$mysql_select_db()
//reading from mysql table
$res="SELECT * FROM table WHERE name=$username AND password=$password";
$val=mysql_query($res);
//authentication
$count=mysql_num_rows($val);
if($count==1)
//authenticate the user
else
through an error