Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a college project where users are able to register and login to a website. I have it set up so when registering a user enters their username, email, password, confirm password, address, and phonenumber. Once registered they are assigned a random string value, lets call it $randomString.
So my database is login_db and it contains the table user. The table headings are username, email, password, address, phonenumber, randomstring.
Its running fine a user can register, their details are added to the database and a user can login. When they log in they are redirected to admin.php. This page is blank at the moment.
Remember the $randomString people are assigned? I need to go into the database retrieve $randomString and display on admin.php.
This is what I've tried so far, I've only been able to display all users random strings but i need only the logged in users randomString. So im presuming the steps i need to go through are
1. Check IF user is logged in. maybe ----> if(isset($_SESSION['email']) ????
2. Check WHAT user is logged in. ????
3. Retrieve logged in users randomString. ????
4. Display the random string. maybe ----> echo $result ???
I have absolutely zero idea how to do it so all help is appreciated.
$connection = mysqli_connect('localhost', 'root', '', 'login_db');
if($connection) {
echo "we are connected";
} else {
die("Database connection failed");
}
?>
<div class="jumbotron">
<h1 class="text-center"><?php
$query = "SELECT randomString FROM users";
$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_row($result)) {
print_r($row);
}
?></h1>
</div>
Let me explain with your question :
Check IF user is logged in
You need to set some value in session when user logs in your system,so that you can check that session value in each new request like you have said in your may be . i.e. if(isset($_SESSION['email'])
Check WHAT user is logged in. ????
If you want to find out which user had logged in then also you have to set all the user info
(id,username/first or last name etc) in you session same as you had saved
user email in session.
Retrieve logged in users randomString
To retrieve logged in users randomString, you can query the database with the users info that you had kept in session when user logged in first time. i .e .
Select randromString from users_table where id='$_SESSION['id']'; //i had suppose you had kept id of logged in user in session here .
Display the random string
To display the random string, yes now you simply echo the value of $randomString that you have retrieve from database using the query above.
First create the connection
<?php
$hostname_localhost = "localhost";
$database_localhost = "databasename";
$username_localhost = "root";
$password_localhost = "";
$localhost = mysql_pconnect($hostname_localhost, $username_localhost, $password_localhost) or trigger_error(mysql_error(),E_USER_ERROR);
?>
Secondly select what you want from the database for the logged in user
<?php
$colname_record = "-1";
if (isset($_SESSION['email'])) {
$colname_record = $_SESSION['email'];
}
mysql_select_db($database_localhost, $localhost);
$query_record = "SELECT userID, randomString, email FROM users WHERE email='$colname_record'";
$record = mysql_query($query_record, $localhost) or die(mysql_error());
$row_record = mysql_fetch_assoc($record);
$totalRows_record = mysql_num_rows($record);
?>
Thirdly get the variable of the logged in user and echo it
<?php
$randomstring = $row_record['randomString'];
?>
And display it
<?php
echo $randomstring;
?>
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Good day everyone,
Firstly let me explain a little bit about my page flow, btw Im using PHP:-
User will Login to the page using their ID (NRIC No) with pw
Then, In the Main page I would like to display their full name (Eg: Welcome, fullname) whereby the name will automatically fetched from the same table with the nric no in the database.
I was successfully do that when I used the same attribute (fullname) with the ID. However, my sv wants the login ID using NRIC No. SO, When I edit the code, there is nothing appear in the main page :(
Here are my codes in the main page;
<!-- logged in user information -->
<?php if (isset($_SESSION['namapengguna'])) : ?>
<p style="margin-left:360px;margin-right:60px">Welcome<strong><?php echo $_SESSION['namapengguna']; ?></strong></p>
<?php endif ?>
***The information(NRIC No, full name) in the database was successfully inserted.
Example of my Table in database:-
namapengguna | idpengguna | password |
Maisarah | 1234567891 | dfsdfdsf |
This is code for login:-
// LOGIN USER
if (isset($_POST['login_user'])) {
$idpengguna = mysqli_real_escape_string($db, $_POST['idpengguna']);
$password = mysqli_real_escape_string($db, $_POST['password']);
if (empty($idpengguna)) {
array_push($errors, "Masukkan ID Pengguna");
}
if (empty($password)) {
array_push($errors, "Masukkan Kata Laluan");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE idpengguna='$idpengguna' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['idpengguna'] = $idpengguna;
$_SESSION['success'] = "";
header('location: lamanutama.php');
}else {
array_push($errors, "ID Pengguna/Kata Laluan salah");
}
}
}
<?php
session_start();
// to store session values
$_SESSION['namapengguna']= $idpengguna; // Initializing Session with value of PHP Variable
?>
Main page Code:
echo $_SESSION["namapengguna"];
please visit this link best example for it. here
As long as you have session you can easily write like this
first add session_start(); and change namepenguna to idpenguna because it has to be the same session you set the time you were receiving result form mysql result
echo 'welcome' .$_SESSION['idpengguna'];
I hope this will work
In your database , password column is not encode by md5(dfsdfdsf), but $password = md5($password);.You should check it
try like this, i hope it will help you:
<?php if (isset($_SESSION['namapengguna'])){
echo 'welcome' .$_SESSION['idpengguna'];
}
?>
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"];
i am making my own php game. So far i have made almost everything. Now to finish it, i need to get id from user who is logged in. I'm not so familiar with the functions and sessions. Please help.
This is what i made so far:
In my index page people login. then they are redirected to this.
So $_POST['username'] is where user type his user name in index.
<?php
$username = $_POST['username'];
include("Files/config.php");
$connect = #mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD);
if($connect) {
if(mysql_select_db(DB_NAME)) {
$sql = mysql_query("SELECT * FROM users WHERE `username`='$username'") or die(mysql_error());
$gatherinfo = mysql_fetch_array($sql);
global $getid;
$getid = $gatherinfo['id'];
echo $getid;
function getuid() {
$_SESSION['getuid'] = $getid;
echo $getid;
}
}
}
else{ echo "Can not connect";}
?>
I searched other scripts for this, i found on one it says just $session->uid and it shows his id from mysql.
In mysql database i have table users with info about them
Id, username, password (password is hashed), email,...
Please help me if you can :D
At the beginning of index file (where your user logging in) start named session (be careful to avoid echo or print any values before session_start:
<?php //index.php
session_name('SAMPLESESSION');
session_start();
then when you will get the logged User ID, write this value to the session variable, like this:
.....
$_SESSION['uid'] = $getid;
.....
in the script you was redirected by your index file start session with the same name and get your user ID:
<?php //redirectedfromindex.php
session_name('SAMPLESESSION');
session_start();
echo $_SESSION['uid'];
....
If I right understand you, these that you need.
I have created a basic PHP login system for a website. So far, the only real feature members can participate in is a made from scratch forum.
For some reason, the session variables are not lining up with the proper user. For example:
User John logs in. Everything is fine. He posts to a forum and his username is attributed to his post.
User Jane logs in. Things get weird. When Jane posts to a forum, John's username is attributed to the post. Likewise, when John posts after Jane has logged in, Jane's username is attributed to the post.
I have no idea why or how this could happen.
-----------Requested Code-----------------------------
Here is the login code, I am assuming the problem must be somewhere here:
<?PHP
session_start();
$citizen_email = $_POST['form_email'];
$citizen_password = $_POST['form_password'];
//
// Connect To Database
$connection = mysqli_connect("localhost", "notreal", "notreal", "notreal");
// Create & Submit Query
$query = "SELECT * FROM citizens WHERE citizen_email='$citizen_email' AND citizen_password='$citizen_password'";
$query_result = mysqli_query($connection, $query);
$query_num_rows = mysqli_num_rows($query_result);
if ($query_num_rows > 0) {
while ($query_array = mysqli_fetch_array($query_result, MYSQLI_ASSOC)) {
$citizen_name = $query_array['citizen_name'];
$citizen_id = $query_array['citizen_id'];
}
$_SESSION["citizen_id"] = $citizen_id;
$_SESSION["citizen_name"] = $citizen_name;
$sqlOnlineCitizen = "INSERT INTO online_citizens VALUES ('$citizen_id', now(), now())";
$onlineCitizenGo = mysqli_query($connection, $sqlOnlineCitizen);
$content = "<p>Welcome to Sachap $citizen_name. Click here to continue.</p>";
} else {
$content = "<p>The email/password combination you provided did not match any citizenship records. You can try again or recover your password.</p>";
}
?>
Are these real users or test accounts? Is it possible they have the same email and password but different names?
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 )) {
}