Connecting to a database setting a cookie, using a function in php - php

I want to be able to connect to my database and have my function search the database for the logged in user and set a cookie, using the users username.
I want to do this using PHP.
I want to do this so that I can call the username whenever I want to display it.
I am very new at php so please bear with me.
Even if there is a link to a post about this, that would be helpful
Edit (This is what I tried so far):
function storeUsername{
$sql = "SELECT username, id FROM users WHERE email = '".escape($email)."' AND active = 1";
$result = query($sql);
if(row_count($result) == 1) {
$row = fetch_array($result);
$username = $row['username'];
{
setcookie('username', $username, time() + 500000);
}
$_SESSION['username'] = $username;
return true;
} else {
return false;
}
return true;
} else {
return false;
}
}

Related

storing user_id in session variable

so I have this site where drivers can login and register.
at the moment i can store the username in a session variable, im trying to do the same for the user_id so the user can later retrieve it when adding more details for a job.
heres what I got so far:
function selectUser($conn, $username, $password, $userID)
{
$query = "SELECT * FROM login WHERE username = :username";
$stmt = $conn->prepare($query);
$stmt->bindValue(':username', $username);
//$stmt->bindValue(':user_ID', $userID);
$stmt->execute();
if ($row = $stmt->fetch(PDO::FETCH_OBJ))
{
if (md5($password) == $row->password) {
$_SESSION['username'] = $username;
$_SESSION['user_ID'] = $userID;
// $_SESSION['password'] = $password;
echo "Welcome, you are now logged in as " . $username;
return true;
}
return false;
}
else
{
//echo "Your details were not found";
return false;
}
}
when the driver accesses another page:
<?php
if(!isset($_SESSION))
{
session_start();
}
require_once ("config.inc.php");
try
{
$conn = new PDO(DB_DATA_SOURCE, DB_USERNAME, DB_PASSWORD);
}
catch(PDOException $exception)
{
echo "Oh no, there was a problem" . $exception->getMessage();
}
if(isset($_SESSION["username"]))
{
echo "Welcome, you are now logged in as <b>".$_SESSION['username']."</b> <img class='clientView' src='images/loginIcon.png' alt='client'>"; }
else {
echo "You are currently not logged in";
}
$login = $_SESSION['user_ID'];
$query = "SELECT * FROM login WHERE user_ID = :login";
$term = $conn->prepare($query);
$term->bindValue(':login', $login);
$term->execute();
$login = $term->fetch(PDO::FETCH_OBJ);
print_r($_SESSION);
?>
tested it using print r and for some reason it doesnt seem to be collecting the user_ID.
am i doing something wrong?
upon test: https://snag.gy/6bGd5m.jpg
when calling the function:
$username=trim($_POST['username']);
$password=$_POST['password'];
$username= htmlspecialchars($username);
$validForm = true;
if (empty($_POST["username"]))
{
$validForm=false;
}
if (empty($_POST["password"]))
{
$validForm=false;
}
if (!$validForm) {
$error = "please ensure all fields are filled in";
include("add.php");
return false;
}
$conn=getConn();
$successLogin=selectUser($conn,$username,$password);
if($successLogin)
{
header( 'Location: profile.php');
}else{
$error = "The details you have entered are incorrect";
include("add.php");
}
Debug.
Where do you store the value in the session state?:
$_SESSION['user_ID'] = $userID;
Ok, so where does $userID come from?:
function selectUser($conn, $username, $password, $userID)
{
//...
Ok, so where does the function parameter come from?:
selectUser($conn,$username,$password)
Nowhere. You never supplied a value to be stored in session, so no value was stored in session.
It seems unlikely that you actually want to supply the User ID to the function. Instead, you probably want to supply just the username and password as you currently do and then get the User ID from the database. Which might look more like this:
$_SESSION['user_ID'] = $row["user_ID"];
Or perhaps:
$_SESSION['user_ID'] = $row->user_id;
Or however you get values from your $row object.
But basically the important lesson here is... When a value isn't what you expect it to be, trace back where that value came from. Chances are you have a false assumption somewhere.

MySQL stored functions don't seem to work in PHP

I have to develop a administrative system at my work (we usually don't do that, but one client have a very specific need, so we skipped from WordPress to pure PHP, MySQL and HTML5), I'm using PHP and MySQL, but i can't get the stored functions on MySQL working in PHP, I had tested it in phpMyAdmin and it works fine.
All I'm trying to do right now is a login webpage.
My code:
require 'connect.php';
function query($query) {
$connection = connect_db();
$result = mysqli_query($connection,$query);
return $result;
}
function validateUser($email, $password) {
$connection = connect_db();
$query = "SELECT email, password FROM usuario WHERE email =". $email ."AND password =" . $password ."";
$result = mysqli_query($connection,$query);
return $result;
}
function login($email, $password) {
$validate = validateUser($email,$password);
if($validate == 1) {
session_start();
//NOT IMPORTANT
header('Location:http://www.google.com/');
}
} else {
echo 'error';
}
}

php session variable randomly changes

I have a website that has a membership system. When users log in, I validate username/password from the database and start a session, $_SESSION['userid'] that contains their id (I have not implemented anything using cookies yet)
I have a problem, the system works fine most of the times, but some users have reported that they eventually find themselves logged in to some other random users account. That probably means that $_SESSION['userid'] changes without any reason to something else and I'm pretty sure I'm not doing anything to change it.
Any ideas why this could be happening ?
edit : Summary of what I am doing
This method start the session
function startSession($id){
$_SESSION['logged_in'] = 1;
$_SESSION['userid'] = $id;
}
This method checks login
function isLoggedIn(){
return isset($_SESSION['logged_in']) && isset($_SESSION['userid']) && $_SESSION['userid']!=" " && $_SESSION['logged_in']==1;
}
This is the logout method
function logout(){
$_SESSION['logged_in'] = 0;
$_SESSION['userid'] = 0;
unset($_SESSION['logged_in']);
unset($_SESSION['userid']);
session_destroy();
if (!isLoggedIn()){ return "S3"; }
else { return "E3"; }
}
And this is how I check if the user is logged in most places
if (isLoggedIn()){ $profileid = $_SESSION['userid']; }
This is the login function, this is where I call startSession
function login($username, $password){
$pdo = newPDO();
$username = sanitize_string($username);
$password = sha1(sanitize_string($password));
$query = $pdo->prepare("SELECT id FROM ".TABLE_PROFILE." WHERE nick=:nick AND pass=:pass LIMIT 1");
$query->execute(array(':nick'=>$username, ':pass'=>$password));
$result = $query->fetch(PDO::FETCH_ASSOC);
if (count($result['id']) == 1){
startSession($result['id']);
loginExecution();
return "S1";
}
else{ return "E1"; }
}
The problem is in your login function
Your script is not checking username and password for any data, and if the username and password is empty or incorrect, your client will gets the firs available id from database.
function login($username, $password){
$pdo = newPDO();
$username = sanitize_string($username);
$password = sanitize_string($password);
// Check data for existing
if (empty($username)) throw new Exeption('Empty username');
if (empty($password)) throw new Exeption('Empty password');
$password = sha1($password);
$query = $pdo->prepare("SELECT id FROM ".TABLE_PROFILE." WHERE nick=:nick AND pass=:pass LIMIT 1");
$query->execute(array(':nick'=>$username, ':pass'=>$password));
$result = $query->fetch(PDO::FETCH_ASSOC);
if (count($result['id']) == 1){
startSession($result['id']);
loginExecution();
return "S1";
}
else{ return "E1"; }
}
P.s. Always check incoming data, before SQL queries
Realistically the only thing I can think of that would cause this is something setting $_SESSION['userid'] to another members id. Assuming this is what you are using to check which members information to show. Are you perhaps doing something if the $_SESSION['userid'] variable is not set that may end up setting $_SESSION['userid'] incorrectly? i.e. if their php session is reset.

Remember Me, avoid rehashing stored password

I have been working very hard to write the most (hopefully) state of the art log-in and remember me features of my script with security in mind.
After hours of testing and getting everything to work i have bumped into a problem with a simple but awkward solution. User logs in, if remember me is checked, cookie is created, when user comes back to website the initiate function checks for cookie, if cookie is present and matches the auth_key value in database, the function will pull user login info (email, password) and use the login function to log the user back on. Problem is that the code/tutorial i was using is designed for an un-encrypted database password (for example purpose i suppose) and the system is trying to "bcrypt hash" an already hashed password.
I can think of two dirty fixes, the dirtiest is to create a secondary login function that avoids hashing the password, the still dirty one is to add a parameter to login() that specifies if the password is hashed or not and the script can "if" it accordingly.
Is there a better way?
public function login($email, $password, $remember = false) {
global $bcrypt; // Again make get the bcrypt variable, which is defined in init.php, which is included in login.php where this function is called
$query = $this->db->prepare("SELECT password, id, email, username, accountlevel FROM users WHERE email = ?");
$query->bindValue(1, $email);
try{
$query->execute();
$data = $query->fetch();
$stored_password = $data['password']; // stored hashed password
$id = $data['id']; // id of the user to be returned if the password is verified, below.
$email = $data['email']; //Stored User email.
$username = $data{'username'}; //Username.
$accountlevel = $data['accountlevel'];
if($bcrypt->verify($password, $stored_password) === true){ // using the verify method to compare the password with the stored hashed password.
// Check if user wants account to be saved in cookie
if($remember)
{
// Generate new auth key for each log in (so old auth key can not be used multiple times in case of cookie hijacking).
$cookie_auth = $bcrypt->randString(10) . $email;
$auth_key = $bcrypt->genHash($cookie_auth);;
$auth_query = $this->db->prepare("UPDATE users SET auth_key = ? WHERE id = ?");
$auth_query->bindValue(1, $auth_key);
$auth_query->bindValue(2, $id);
try{
$auth_query->execute();
setcookie("auth_key", $auth_key, time() + 60 * 60 * 24 * 7, "/", "touringlegends.com", false, true);
}catch(PDOException $e){
die($e->getMessage());
}
}
session_regenerate_id(true);
$session_id = $id;
$session_username = $username;
$session_level = $accountlevel;
$_SESSION['user_id'] = $session_id;
$_SESSION['user_level'] = $session_level;
$_SESSION['user_name'] = $session_username;
$_SESSION['user_lastactive'] = time();
return true; // returning true.
}else{
return false;
}
}catch(PDOException $e){
die($e->getMessage());
}
}
public function initiate()
{
global $general;
$logged_in = false;
if(isset($_SESSION['user_name']))
{
$logged_in = true;
}
// Check that cookie is set
if(isset($_COOKIE['auth_key']))
{
$auth_key = $general->safe_var($_COOKIE['auth_key']);
if($logged_in === false)
{
// Select user from database where auth key matches (auth keys are unique)
$auth_key_query = $this->db->prepare("SELECT username, password FROM users WHERE auth_key = ? LIMIT 1");
$auth_key_query->bindValue(1, $auth_key);
try{
$auth_key_query->execute();
$data = $auth_key_query->fetch();
if($auth_key_query === false)
{
// If auth key does not belong to a user delete the cookie
setcookie("auth_key", "", time() - 3600);
}
else
{
// Go ahead and log in
$this->login($data['username'], $data['password'], true);
}
}catch(PDOException $e){
die($e->getMessage());
}
}
else
{
setcookie("auth_key", "", time() - 3600);
}
}
}

NEW to PHP... Need Help... Regarding nested functions

i'm playing around and trying to incorporate a nested function into my login script. The functions are all below. Also, beneath my functions is the portion of the login script im trying to incorporate them in. However, everytime I try to log in, it says invalid username. However if I user function a and b in the login script instead of function d, everything works fine. Can some tell me where i',m going wrong? Thanks.
//a -username
function username_check($username){
$usercheck = "SELECT user_id FROM users WHERE username ='$username'";
$userqry = mysql_query($usercheck) or die ("Could not match data because ".mysql_error());
$num_rows = mysql_num_rows($userqry);
return ($num_rows == 1) ? true : false;
}
//b - password
function password_check($password, $username){
$passwordcheck = "SELECT password FROM users WHERE username ='$username'";
$passwordqry = mysql_query($passwordcheck) or die ("Could not match data because ".mysql_error());
while($retrievepassword = mysql_fetch_array($passwordqry))
{
$password = md5($password);
return ($password != $retrievepassword['password']) ? true : false;
}
}
//c -email
function email_check($email){
$emailcheck = "SELECT user_id FROM users WHERE email = '$email'";
$emailqry = mysql_query($emailcheck) or die ("Could not match data because ".mysql_error());
$num_rows = mysql_num_rows($emailqry);
return ($num_rows == 1) ? true : false;
}
//d -username + password + email check? all in one? DOESNT WORK
function user_check($username = NULL, $password = NULL, $email = NULL) {
if(($email !=NULL)) {
email_check($email);
}
elseif(($username !=NULL) && ($password!=NULL)){
password_check($password,$username);
}
elseif(($username !=NULL) ) {
username_check($username);
}
}
//LOGIN SCRIPT
if (user_check($username1) ==false) {
$logerrors[] = 'Invalid username';
}
elseif (user_check($password1, $username1)) {
$logerrors[] = 'Incorrect password';`
well for one, function d doesn't return any values.

Categories