Create a current session variable not working - php

I have a table and it has more columns:
id | username | picture
Picture is varchar type and it keeps the path of user picture
username is varchar and is unique
<?php
session_start();
if (isset($_POST["logIn"])) {
$connection = new mysqli(...);
$email = $connection->real_escape_string($_POST["email"]);
$password = sha1($connection->real_escape_string($_POST["password"]));
$data = $connection->query("SELECT * FROM users WHERE email='$email' AND password='$password'");
if ($data->num_rows > 0) {
$_SESSION["email"] = $email;
$_SESSION["loggedIn"] = 1;
$picture = $connection->query("SELECT picture FROM users WHERE email='$email' AND password='$password'");
$_SESSION["picture"]=$picture;
header("Location:../index.php");
exit();
}
So what I want to do is, create a $_SESSION["picture"] variable which will keep the value of the username's picture , i mean the picture of the user that is trying to login now

You have to call a fetch function to get the data from the table.
$data = $connection->query("SELECT picture FROM users WHERE email='$email' AND password='$password'");
if ($data->num_rows > 0) {
$row = $data->fetch_assoc();
$_SESSION["email"] = $email;
$_SESSION["loggedIn"] = 1;
$_SESSION["picture"]=$row['picture'];
header("Location:../index.php");
exit();
}

Related

Getting id from database and put it in session id

For my website I need to be able to get an ID from a database after someone logged in. I already figured out how to put the variables from the login page into a session but I cant figure out how to write a code that gets an ID from a database and turns it into a session variable.
session_start();
include( "connection.php" );
if(isset($_GET['action']) && ($_GET['action'] == "login")){
$name = mysqli_real_escape_string($conn, $_POST["name"]);
$pass = mysqli_real_escape_string($conn, md5( $_POST['pass'] . "90qdjka*#"));
$QUERY = "SELECT * FROM users WHERE username = '$name' AND password = '$pass' AND enabled = 1";
$EXEC = mysqli_query($conn, $QUERY );
if(mysqli_num_rows($EXEC)==0){
die( 'Login niet geldig! Opnieuw inloggen' );
}else{
$_SESSION['name'] = $name;
$_SESSION['pass'] = $pass;
$QUERY = "UPDATE users SET lastlogin=NOW() WHERE username = '$name' AND password = '$pass'";
mysqli_query($conn, $QUERY);
}
}
?>
else{
if (mysqli_num_rows($EXEC) > 0) {
while($row = mysqli_fetch_assoc($EXEC)) {
$_SESSION['id'] = $row["id"];
}
}
$_SESSION['name'] = $name;
$_SESSION['pass'] = $pass;
if your query returns only one result then while loop will run only one time but if your query returns more than one record then the last record's id will be stored in your session variable
In $row["id"], id is the column name of the table, if you are selecting all columns from your table and if your users table has columns like name, username, password then you can access it using $row["name"], $row["username"], $row["password"]

php - sql, get user id after login form by using $_session

i am try to assign the user id in a $_session after login from login page.
I have read many posts here but i can unterstand how its work.
Here is my db structure
Here is my code from login.php
<?php
session_start(); //Έναρξη session
require_once('connect.php'); //καλώ το αρχείο
//Τι γίνετε όταν submitted η φόρμα
if(isset($_POST) & !empty($_POST)){
//Αναθέση τιμών μεταβλητών από τα inputs
$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = md5($_POST['password']);
//Έλεγχος αν υπάρχουν τα στοιχεία σύνδεσης στην βάση
$sql = "SELECT * FROM `usermanagement` WHERE username ='$username' AND password='$password'";
$result = mysqli_query($connection, $sql);
$count = mysqli_num_rows($result);
if($count == 1){
$_SESSION['username'] = $username;
$_SESSION['UserId'] = $userid; // <-trying to determine this variable
}else{
$fmsg = "Λάθος Όνομα Χρήστη ή Κωδικό χρήστη. ";
}
}
?>
i saw that $_SESSION['username'] = $username; but i don' t know how to do something similar for $_SESSION['userid'] = $userId;
Any help? Even a link.
You need to fetch the results from the sql query and use that to get the userid
if( $count == 1 ){
/* there is a recordset so fetch into as array */
$row=mysqli_fetch_assoc( $result );
/* extract the required variables from recordset array */
$userid=$row['userid'];
$_SESSION['username'] = $username;
$_SESSION['UserId'] = $userid; // <-this variable should now exist
}else{
$fmsg = "Λάθος Όνομα Χρήστη ή Κωδικό χρήστη. ";
}

PHP session with permissions

I am having problem with the code.
It suppose to allow admin to view only admin page
and user to view user page only.
my admin still able to view user page.
below is my landing page
<?php
error_reporting(0);
include("config.php");
$host = "localhost"; //DB host
$username = "root"; //DB Username
$password = ""; //DB Password
$db_name = "hklcanet_pha"; //DB Name
$tbl_name = "users"; //Table name, where users are stored
$dbconfig = mysqli_connect($host,$username,$password,$db_name);
$username = $_POST['username']; //Get username from login form
$password = $_POST['password']; //Get password from login form
$username = stripslashes($username); //Makes string safe
$password = stripslashes($password); //Makes string safe
$username = mysqli_real_escape_string($dbconfig, $username); //Makes string safer
$password = mysqli_real_escape_string($dbconfig, $password); //Makes string safer
$sql = "SELECT * FROM $tbl_name WHERE username='$username' and password='$password'"; //SQL Query
$result = mysqli_query($dbconfig, $sql); //Executes Query
$rows = mysqli_num_rows($result); //Count rows selected (1 if a username/password combo can be found)
if($rows == 1){
session_start(); //Starts a PHP session
$_SESSION['username'] = $username; //Allows $username to be used later
header("location: interphase1.php");
$query = "SELECT * FROM $tbl_name WHERE username='$username' and password='$password'";
$result = mysqli_query($dbconfig, $query);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$permissions = $row['permissions']; //Gets the permissions of the user
$id = $row['id']; //Gets the ID of the user
}
$_SESSION['permissions'] = $permissions; //Allows $permissions to be used later
$_SESSION['id'] = $id; //Allows $id to be used later
$_SESSION['authenticated'] = 1; //Allows $id to be used later
echo("Login Succesful");//Prints success message
}
else
{
//echo("Invalid Username/Password");
}
?>
user page
<?php
session_start();
$permissions = $_SESSION['permissions'];
if($_SESSION['authenticated'] != 1)
{
echo("You must be logged in");
header("location:landing.php");
}
else
{
if($permissions < 0)
{
header("location:quicksummary.php");
echo("Your permissions are not high enough");
}
}
?>
admin page
<?php
session_start();
$permissions = $_SESSION['permissions'];
if($_SESSION['authenticated'] != 1)
{
header("location:landing.php");
echo("You must be logged in");
}
else
{
if($permissions < 1 )
{
header("location:quicksummary.php");
echo("Your permissions are not high enough");
}
}
?>
thanks and appreciate if somebody can help me on this, still new with the PHP code.

Trying to make a login for my admin panel if matches password from database

I have already put user name and password in database, now what I am trying to do is when admin puts that user name and password that I have stored in database, they can access next page otherwise error.
if(isset($_REQUEST['submit'])) {
$user=$_REQUEST['user'];
$password=$_REQUEST['password'];
$q = mysql_fetch_assoc( mysql_query("SELECT * FROM adminlogin"));
$r = mysql_query($q);
if ( $user == "admin" && $password == "adminadmin" ) {
echo "welcome";
Header("Location: index.php");
}
}
Try with this:
if(isset($_REQUEST['submit'])) {
$user=$_REQUEST['user'];
$password=$_REQUEST['password'];
//Execute query, adjust the name of the columns to the one you've used in your table
$q = mysql_query("SELECT * FROM adminlogin WHERE user = '$user' and password = '$password'");
//Get the results from the query
$r = mysql_fetch_array($q);
//If any rows, the login is okay
if (mysql_num_rows($q) > 0) {
//User okay, redirect him to the success page
header("location: index.php");
}

PHP Session not holding values

After a good few hours of looking at posts and different forums I finally give up.
I have been learning PHP for the last 24 hours by trying to create a registration and a login page.
Registration seems to be working (I am sure that there are some bugs etc, but as of right now everything seems to be in sql).
As far as my login page, this is where I am having some problems.
NEW EDIT
Here is my registration.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
//Set error msg to blank
$errorMsg = "";
// Check to see if the form has been submitted
if (isset($_POST['username']))
{
include_once 'db_connect.php';
$username = preg_replace('/[^A-Za-z0-9]/', '', $_POST['username']);
$password = preg_replace('/[^A-Za-z0-9]/', '', $_POST['password']);
$accounttype = preg_replace('/[^A-Za-z]/','', $_POST['accounttype']);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
//validate email with filter_var
if ((!$username) || (!$password) || (!$accounttype) || (!$email))
{
$errorMsg = "Everything needs to be filled out";
}
else {
// if fields are not empty
// check if user name is in use
$db_username_check = mysql_query("SELECT id FROM members WHERE username='$username' LIMIT 1");
$username_check = mysql_num_rows($db_username_check);
// check if email is in use
$db_email_check = mysql_query("SELECT id FROM members WHERE email='$email' LIMIT 1");
$email_check = mysql_num_rows($db_email_check);
//if username is in use ... ERROR
if ($username_check > 0) {
$errorMsg = "ERROR: username is already in use";
// if username is ok check if email is in use
} else if ($email_check > 0) {
$errorMsg = "ERROR: email is already in use";
} else {
session_start();
$hashedPass = md5($password);
// Add user info into the database table, claim your fields then values
$sql = mysql_query("INSERT INTO members (username, password, email, accounttype )
VALUES('$username', '$hashedPass', '$email', '$accounttype')") or die (mysql_error());
// Retrieves the ID generated for an AUTO_INCREMENT column by the previous query
$id = mysql_insert_id();
$_SESSION['id'] = $id;
mkdir("members/$id", 0755);
header("location: member_profile.php?id=$id");
$errorMsg = "Registration Successful";
exit();}
}
// if the form has not been submitted
} else { $errorMsg = 'To register please fill out the form'; }
?>
here's my Login.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
// if the form has been submitted
$errorMsg = "";
if ($_POST['username']){
include_once('db_connect.php');
$username = stripslashes($_POST['username']);
$username = strip_tags($username);
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$hashedPass = md5($password);
$sql = "SELECT username,password FROM members WHERE username ='$username' AND password = '$hashedPass'";
$login_check = mysql_query($sql);
$count = mysql_num_rows($login_check);
$row = mysql_fetch_array($login_check);
//var_dump($id, $username, $password);
if($count==1)
{
session_start();
//$id = $row["id"];
// $_SESSION['id'] = $userid;
// $username = $row['username'];
// $_SESSION['username'] = $username;
// header("location: member_profile.php?id=$userid");
echo "User name OK";
return true;
} else {
echo "Wrong username or password";
return false;
}
}
?>
Whenever someone registers $id = mysql_insert_id();will pull the ID from the last query and start a $_SESSION['id']. However during a login right after if($count==1) I am completely lost. For some reason the name and the password is checked and does go through but the ID fails.
I did try adding "SELECT id FROM members WHERE id='$id'" but my $id is always undefined.
My member_profile.php is something like this:
<?php
session_start();
$toplinks = "";
if(isset($_SESSION['id'])) {
//If the user IS logged in show this menu
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '
Profile •
Account •
Logout
';
} else {
// If the user IS NOT logged in show this menu
$toplinks = '
JOIN •
LOGIN
';
}
?>
Thank you to everyone for any tips as far as security, structure and coding style. This is day #3 of php for me.
Please excuse any errors.
Your if is going inside comments check this --
<?php // if the form has been submitted $errorMsg = ""; if
edit it --
<?php
// if the form has been submitted
$errorMsg = "";
if(($_POST['username']) && ($_POST['password'])){
You are using mysql and using mysqli in your code too--
$row = mysqli_fetch_array($sql);
use --
$row = mysql_fetch_array($sql);
Look at your sessions as well as Phil mentioned in comments.
session_start()
Replace the code
$row = mysqli_fetch_array($sql); to $row = mysql_fetch_array($login_check);
if($count==1)
{
$id = $row['id'];
session_start();
$_SESSION['id'] = $id;
//$row = mysqli_fetch_array($sql);
$username = $row['username'];
$_SESSION['username'] = $username;
header("location: member_profile.php?id=$id");
exit();
} else {
echo "Wrong username or password";
return false;
}
Also Change your query if you have any id field in table:
$sql = "SELECT id,username,password FROM members WHERE username ='$username' AND password = '$hashedPass'";
First I went over the code. Since this is my day #4 of php, I started changing everything from mysql to mysqli which made a little more sense to me. The code is probably still messy but it does work so far. Thank you
$sql = ("SELECT * FROM members WHERE username = '$username' && password = '$hashedPass'");
$login_check = mysqli_query($link, $sql);
$count = $login_check->num_rows;
$row = mysqli_fetch_array($login_check);
printf("Result set has %d rows.\n", $count);
if($count==1)
{
session_start();
$id = $row["id"];
$_SESSION['id'] = $id;
$username = $row['username'];
$_SESSION['username'] = $username;
header("location: member_profile.php?id=$id");
echo "User name OK";
return true;

Categories