I have a database set up and I use 'user_id' for example to displays the name, age, address etc. I want to display all information with just the id in php. This then echos in another page. Currently i have to do this:
$row=mysql_fetch_array($result);
$_SESSION['Name'] = $row['Name'];
$_SESSION['Address'] = $row['Address'];
Store just the user ID and a token that you set when the user logged in:
if (isset($_SESSION['user_id']) && $_SESSION['logged_in']) {
$user_id = $_SESSION['user_id'];
$user = // Query your database to get the user with that ID.
} else {
// Not logged in.
}
Alternatively, you could use secure sessions and serialize the user's profile object into a string, but you will need to keep it updated in case the user changes their information.
Related
i want insert data to current logged in user i changed 4 to session id but error please help me how to store id in session and use here
login.php
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
home.php
<?php
//Get current user ID from session
$userId = 4;
//Get user data from database
$result = $db->query("SELECT * FROM user WHERE id = $userId");
$row = $result->fetch_assoc();
?>
Try this.Directly add the value to session array.It will updated with session
session_start();
$_SESSION['user_id'] = 4;
$userId =$_SESSION['user_id']
executing the function call 'session_id()' returns the id of the session for the vistor, the session is actually a file kept in a directory of your server, the session_id will point to this file in all instances that I've personally seen.
to actually access the session you need to use $_SESSION to set and read data :) Happy Coding!
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 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'];
// ....
}
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 )) {
}