PHP/PDO: How to add more session data in PHP - php

from the question above, currently I already create a login page. in the login page, I include 'email' as a session and I can borrow the 'email in all page'. Let say if I want to include other data to the session, for example, 'fullname', how to do?
Below is my login code
<?php
include("config/configPDO.php");
session_start();
$msg = "";
if(isset($_POST['submitBtnLogin'])) {
$user_id = trim($_POST['email']);
$email=explode('#',$user_id);
if (is_array($email)){
$user_id=$email[0];
}
$pwd = trim($_POST['pwd']);
if($user_id != "" && $pwd != "") {
$ldap_dn = "TOPGLOVE\\".$user_id;
$ldap_password = $pwd;
$ldap_con = ldap_connect("ldap://172.xx.xx.xx:xxx");
ldap_set_option($ldap_con, LDAP_OPT_PROTOCOL_VERSION, 3);
if(#ldap_bind($ldap_con,$ldap_dn,$ldap_password)){;
try {
$records = $conn->prepare("SELECT email, roles_id, pwd FROM users WHERE user_id = :user_id ");
$records->execute(
array(
'user_id' => $user_id,
)
);
$results = $records->fetch(PDO::FETCH_ASSOC);
$message = '';
if($results && count($results) > 0 ){
$_SESSION['login_user'] = $results["email"];
if($results["roles_id"] == "1"){
header("location: pages/dashboard/dashboard_admin.php");
}else if ($results["roles_id"] == "3"){
header("location: pages/dashboard/dashboard_super_admin.php");
}
} else {
echo "
<script>alert('You're not authorized to use this system')</script>
<script>window.location = 'index.php'</script>
";
}
} catch (PDOException $e) {
echo "Error : ".$e->getMessage();
}
} else{
echo "
<script>alert('Invalid Email or Password')</script>
<script>window.location = 'index.php'</script>
";
}
} else {
$msg = "Both fields are required!";
}
}
?>

As #Nick said, make sure the SESSION is started and the User has been logged in.
Then you can use $_SESSION Array, to add new elements.
$_SESSION['name'] = $your_var;

Related

PHP/Session: Bring all data in table User after login

currently, I create a system that requires login. I Uses the LDAP method. I have created the session for this system. When I clicked the login button, it will go to the next page and display the "User_ID". Now, How I also want to display the user's full name on the next page after clicking the login button? The full name and the "User_ID" is on the same table 'staff'
Below is my current code.
<?php
include("config/configPDO.php");
session_start();
$msg = "";
if(isset($_POST['submitBtnLogin'])) {
$User_ID = trim($_POST['User_ID']);
$Pwd = trim($_POST['Pwd']);
if($User_ID != "" && $Pwd != "") {
$ldap_dn = "TOPNET\\".$User_ID;
$ldap_password = $Pwd;
$ldap_con = ldap_connect("ldap://172.xx.xx.xx:xxx");
ldap_set_option($ldap_con, LDAP_OPT_PROTOCOL_VERSION, 3);
if(#ldap_bind($ldap_con,$ldap_dn,$ldap_password)){;
try {
$records = $conn->prepare("SELECT Email, Role_ID FROM Staff WHERE User_ID = :User_ID ");
$records->execute(
array(
'User_ID' => $User_ID,
)
);
$results = $records->fetch(PDO::FETCH_ASSOC);
$message = '';
if($results && count($results) > 0 ){
$_SESSION['login_user'] = $User_ID;
if($results["Role_ID"] == "2"){
header("location: pages/dashboard/dashboard_admin.php");
}else if ($results["Role_ID"] == "1"){
header("location: pages/dashboard/dashboard_super_admin.php");
}else if ($results["Role_ID"] == "3"){
header("location: pages/dashboard/dashboard_normal_user.php");
}
} else {
echo "
<script>alert('You're not authorized to use this system')</script>
<script>window.location = 'index.php'</script>
";
}
} catch (PDOException $e) {
echo "Error : ".$e->getMessage();
}
} else{
echo "
<script>alert('Invalid Email or Password')</script>
<script>window.location = 'index.php'</script>
";
}
} else {
$msg = "Both fields are required!";
}
}
?>
Why don't you save $results into $_SESSION['login_user'] and process it in the next page?

Cannot make register to work with reCAPTCHA2

I cannot make the register to work with recaptcha but it work normally without it
<?php
require_once("database.php");
$conn= pdo_con();
ini_set('SMTP','smtp.intnet.mu');
ini_set('smtp_port',25);
ini_set('sendmail_from','admin#example.co.uk');
if(!empty($_POST) || isset($_POST['regis_submit'])){
// Should the code be place here cause I already try it. //
$errors = array();
if (empty($_POST['firstname']) || empty($_POST['regis_username']) || empty($_POST['lastname']) || empty($_POST['inputEmail'])
|| empty($_POST['phone_num']) || empty($_POST["gender"]) || empty($_POST['regis_pass']) || empty($_POST["postal_address"])
|| empty($_POST["DateField"]) ){
$errors[] = 'Value(s) in the form missing, please fill them all out!';
exit();
} else if(!preg_match ('%^[A-Za-zÀàÂâÇçÉéÈèÊêËëÔôÙùÎîÏïÛûÜü\.\' \-]{2,15}$%', $_POST['firstname'])){
$errors['firstname'] = '<p><font color="red">Please enter your first name!</font></p>';
exit();
} else if ( etc...
}
else if (count($errors) > 0) {
foreach($errors as $error) {
echo $error;
}
} else {
$firstname = escape_data($_POST['firstname']);
$username = escape_data($_POST['regis_username']);
$lastname = escape_data($_POST['lastname']);
$email = escape_data($_POST['inputEmail']);
$telephone = escape_data($_POST['phone_num']);
$password = escape_data($_POST['regis_pass']);
$address = escape_data($_POST['postal_address']);
$gender = escape_data($_POST['gender']);
$date = escape_data($_POST['DateField']);
//check if user already exist
$exist = "";
$query = $heidisql->prepare("SELECT user_id as 'exist' FROM users WHERE user_username='$username' OR email_address='$email' ");
$query->execute();
while($userRow = $query->fetch(PDO::FETCH_ASSOC)) {
$exist = $userRow['exist'];
}
if(strlen($exist) > 0){
echo 'Account already exist!';
exit();
} else {
$sql = "";
$stmt = $heidisql->prepare($sql);
$token = bin2hex(random_bytes(20));
$hash = password_hash($password, PASSWORD_BCRYPT);
$stmt->execute(array ( ... ));
my email here
if (mail($to, $subject, $message, $headers)) { // Sending email // email_to, subject, body,email_from
echo 'Thank you for your registration. Check your email, and click on the link to activate your account ';
exit();
} else {
echo'Server failed to sent message, please try again later.';
exit();
}
}
} // END of else statement
exit();
}
debug($errors);
}
WHere exactly should I put the captcha code below into my code... I already try to put it on top but I get an error. Undefined $responseKey or something like that.
$secretKey = "xxxx";
$responseKey = $_POST['g-recaptcha-response'];
$userIP = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify";
$response = file_get_contents($url."?secret=".$secretKey."&response=".$responseKey."&remoteIP=".$userIP);
$data_response = json_decode($response);
if(isset($data_response->success) AND $data_response==true){
} else {
}
The and div are properly place into my form. I just cant pinpoint where the code should be placed exactly.

Multiple User Type Login Through Single Login Page Issue

I am working on php and mysql code on making access to different pages based on the role of the user, through one Login Page.
Its working good for 'admin' page ..
but not able to login with 'normal type'
Little Help is really appreciated, Thank You
Here is my Code
<?php
session_start();
include 'dbcon.php';
if($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM wp_users WHERE user_login = '$username' AND user_pass = '$password'";
$result = mysqli_query($con,$query) ;
$row = mysqli_fetch_assoc($result);
$count=mysqli_num_rows($result) ;
if ($count == 1) {
if($row['user_type'] == 'admin')
{
header('Location: user_registration.php');
$_SESSION['ID'] = $row['ID'];
$_SESSION['user_login'] = $row['user_login'];
$_SESSION['password'] = $row['user_pass'];
}
elseif($row['user_type'] = 'normal')
{
header('Location: index.php');
}
else
{
echo "WRONG USERNAME OR PASSWORD";
}
}
}
?>
Move your session code after if condition and then redirect. Also is there any specific reason to store password in session. == missing
Use proper filters for inputs.
if ($count == 1) {
if(!empty($row['user_type'])) {
$_SESSION['ID'] = $row['ID'];
$_SESSION['user_login'] = $row['user_login'];
//$_SESSION['password'] = $row['user_pass'];
}
if($row['user_type'] == 'admin')
{
header('Location: user_registration.php');
}
elseif($row['user_type'] == 'normal')
{
header('Location: index.php');
}
else
{
echo "WRONG USERNAME OR PASSWORD";
}
}
The logic test for the normal user was using a single = sign which sets a value rather than tests for equality - it needs to be ==
Also, I think the WRONG USERNAME OR PASSWORD wa at the wrong level - it needs to be the else to the record count
<?php
session_start();
include 'dbcon.php';
if($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM wp_users WHERE user_login = '$username' AND user_pass = '$password'";
$result = mysqli_query($con,$query);
$row = mysqli_fetch_assoc($result);
$count=mysqli_num_rows($result);
if ($count == 1) {
if($row['user_type'] == 'admin') {
header('Location: user_registration.php');
$_SESSION['ID'] = $row['ID'];
$_SESSION['user_login'] = $row['user_login'];
$_SESSION['password'] = $row['user_pass'];
/* require `==` here */
} elseif( $row['user_type'] == 'normal' ) {
header('Location: index.php');
} else {
die('unknown/unhandled user level');
}
/* changed location of this by one level */
} else {
echo "WRONG USERNAME OR PASSWORD";
}
}
?>
This is function for login.
It presumes password come from user with sha512 encryption (see js libs like https://github.com/emn178/js-sha512) - it's good for non-encrypted connections.
It uses salt, and have some protection from brute force, CSRF, XSS and SQL-injection.
static public function db_login($email, $p)
{
if ($stmt = Site::$db->prepare(
"SELECT id, password, salt, name
FROM user
JOIN contact ON contact_id = id
WHERE email = ?
LIMIT 1")
) {
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($user_id, $db_password, $salt, $name);
$stmt->fetch();
// hash the password with the unique salt
$p = hash('sha512', $p . $salt);
if ($stmt->num_rows == 1) {
// If the user exists we check if the account is locked
// from too many login attempts
if (self::checkBrute($user_id) == true) {
// Account is locked
$res['code'] = 0;
$res['reason'] = 'trylimit';
$res['message'] = 'You try too many times. Come back on 30 minutes';
return $res;
} else {
// Check if the password in the database matches
// the password the user submitted.
if ($db_password == $p) {
// Password is correct!
// Get the user-agent string of the user.
// CSRF
$user_browser = filter_input(INPUT_SERVER, 'HTTP_USER_AGENT', FILTER_SANITIZE_SPECIAL_CHARS);
// XSS protection as we might print this value
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
Login::sec_session_start();
$_SESSION['user_id'] = $user_id;
$_SESSION['email'] = htmlspecialchars($email);
$_SESSION['name'] = htmlspecialchars($name);
$_SESSION['token'] = md5(uniqid(rand(), TRUE));
$_SESSION['login_string'] = hash('sha512', $p . $user_browser);
session_write_close();
// Login successful
$res['isLogined'] = 1;
$res['code'] = 1;
$res['name'] = $name;
$res['id'] = $user_id;
return $res;
} else {
// Password is not correct
// We record this attempt in the database
$now = time();
Site::$db->query("INSERT INTO login_attempts(user_id, time) VALUES ('$user_id', '$now')");
$res['code'] = 0;
$res['reason'] = 'pass';
$res['message'] = 'Wrong password';
return $res;
}
}
} else {
// No user exists.
$res['code'] = 0;
$res['reason'] = 'user';
$res['message'] = 'We have no such email';
return $res;
}
}
$res['code'] = 0;
$res['reason'] = 'SQL-error';
return $res;
}

Checking users status before login

I have been coding for hours trying to checking user status(active, inactive, suspended, banned etc.) before he/she can log in to his/her account but nothing seemed to work.
Below is the code for that.
<?php
if (!defined('included')){
die('You cannot access this file directly!');
}
//log user in ---------------------------------------------------
function login($user, $pass){
//strip all tags from varible
$user = strip_tags(mysql_real_escape_string($user));
$pass = strip_tags(mysql_real_escape_string($pass));
$status = 'active';
$salt = sha1('_wchs2242%..father%/**...mygreenparrot_password&username\--\__/heelo"######.');
$password = md5($pass.$salt);
//$pass = md5($pass);
// check if the user id and password combination exist in database
$sql = "SELECT * FROM panel_users WHERE username = '$user' AND password = '$password' ";
$result = mysql_query($sql) or die('Query failed. ' . mysql_error());
if (mysql_num_rows($result) == 1) {
// the username and password match,
// set the session
$_SESSION['authorized'] = true;
$_SESSION['user'] = $user;
// direct to admin
header('Location: '.DIRADMIN);
exit();
} else {
$cs = mysql_fetch_array($result);
$sta = $cs['status'];
if($sta == 'suspended'){
$_SESSION['sus'] = 'Your account is being suspended';
}
elseif($sta == "inactive"){
$_SESSION['ina'] = 'You\'re not yet authorized.';
}else{
// define an error message
$_SESSION['error'] = 'Sorry, wrong username or password';
}
}
}
// Authentication
function logged_in() {
if($_SESSION['authorized'] == true) {
return true;
} else {
return false;
}
}
function login_required() {
if(logged_in()) {
return true;
} else {
header('Location: '.DIRADMIN.'login');
exit();
}
}
function logout(){
unset($_SESSION['authorized']);
header('Location: '.SITEDIR.'login');
exit();
}
// Render error messages
function messages() {
$message = '';
if($_SESSION['success'] != '') {
$message = '<div class="alert-success">'.$_SESSION['success'].'</div>';
$_SESSION['success'] = '';
}
if($_SESSION['error'] != '') {
$message = '<div class="alert-warning">'.$_SESSION['error'].'</div>';
$_SESSION['error'] = '';
}
if($_SESSION['sus'] != '') {
$message = '<div class="alert-warning">'.$_SESSION['sus'].'</div>';
$_SESSION['sus'] = '';
}
if($_SESSION['ina'] != '') {
$message = '<div class="alert-warning">'.$_SESSION['ina'].'</div>';
$_SESSION['ina'] = '';
}
echo "$message";
}
function errors($error){
if (!empty($error))
{
$i = 0;
while ($i < count($error)){
$showError.= "<div class=\"msg-error\">".$error[$i]."</div>";
$i ++;}
echo $showError;
}// close if empty errors
} // close function
?>
Any one with an idea of what I might be doing wrong?
$result containt rows only if the username and password matches
otherwise $result it will contans NULL
so each time if (mysql_num_rows($result) == 1) {}else{} else{} doesn't work and makes error i think.
so try this code
if (mysql_num_rows($result) == 1) {
// if the username and login match
// so here we check the status before granting the user access
$cs = mysql_fetch_array($result);
$sta = $cs['status'];
if($sta == 'suspended'){
$_SESSION['sus'] = 'Your account is being suspended';
}elseif($sta == "inactive"){
$_SESSION['ina'] = 'You\'re not yet authorized.';
}else{
// the username and password match,
// set the session
$_SESSION['authorized'] = true;
$_SESSION['user'] = $user;
// direct to admin
header('Location: '.DIRADMIN);
}
exit();
} else {
// define an error message
// if username and password don't match
$_SESSION['error'] = 'Sorry, wrong username or password';
}

How to get a user id from one php file and retrieve it in another php file

How do I get a user_id for a PHP file from another PHP file. I'm using $_SESSION['user_id'] to do it but it's not working for me. Can anyone show me how to do it and where the $_SESSION['user_id'] should be placed in the PHP files, or if there is a better way of doing it. I think I have it placed in the right place in the login.php file but not sure about fitness.php. I'm using them for my Android app. The two PHP files are below. Any help will be greatly appreciated, thank you.
login.php
<?php
session_start();
$error = NULL;
include_once('connection.php');
if(isset($_POST['txtUsername']) && isset($_POST['txtPassword'])){
$username = $_POST['txtUsername'];
$password = $_POST['txtPassword'];
$query = "SELECT username, password, user_id FROM user WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($conn, $query);
if($username == $error || $password == $error) {
echo "Login Failed <br>";
}
elseif($result->num_rows > 0){
$_SESSION['user_id'] = 'user_id';
if(isset($_POST['mobile']) && $_POST['mobile'] == "android"){
echo "success";
exit;
}
echo "Login Successful";
// header("location: login.php");
}
else{
echo "Login Failed <br>";
}
}
?>
fitness.php
<?php
session_start();
$error = NULL;
include_once('connection.php');
if(isset($_POST['pulseOne']) && isset($_POST['pulseTwo']) && isset($_POST['pulseThree'])){
$pulseOne = $_POST['pulseOne'];
$pulseTwo = $_POST['pulseTwo'];
$pulseThree = $_POST['pulseThree'];
$fitnessResult = 100;
$overall = 30000;
$fitnessScore = -1;
$fitnessScore = $pulseOne + $pulseTwo + $pulseThree;
if($fitnessScore != 0){
$fitnessResult = $overall/$fitnessScore;
$fitnessResult = round($fitnessResult, 0);
}
else{
$fitnessResult = NULL;
}
// $fitnessResult = mydivide($overall/$fitnessScore);
$date = date("Y-m-d");
$time = date("h:i:sa");
// $user_id = $_POST['user_id'];
$query = "INSERT INTO `fitness`(`fitnessScore`, `fitnessDate`,`fitnessTime`, `user_id`) VALUES ('$fitnessResult','$date','$time', 42)";
$result = mysqli_query($conn, $query);
if($pulseOne == $error || $pulseTwo == $error || $pulseThree == $error){
echo "Insert Failed";
}
elseif($result > 0){
if(isset($_POST['mobile']) && $_POST['mobile'] == "android"){
echo "success";
exit;
}
echo "Insert Successfully";
}
else{
if(isset($_POST['mobile']) && $_POST['mobile'] == "android"){
echo "Registration Failed";
exit;
}
echo "Insert Failed";
}
}
?>
So many things to note here, first of all restructure your If and else statements if you are using else if use them properly. you are using mysqli no prepared statements plain query, try to learn better way so your code dont stay vulnerable. Last but not the least you are facing this proble because you are trying to use Session variable value with post keyword, try this:
$user_id = $_SESSION['user_id'] ; and it will be solved.
you can do like this First save your session variable in another variable than try to insert in database
$user_id = $_SESSION['user_id'] ;
Try to echo it thisway
echo $user_id;
once you get it use it or insert it in database
change your code from
$_SESSION['user_id'] = 'user_id';
this to
$_SESSION['user_id'] = $row['user_id'];

Categories