how to confirm logged in to pages? - php

I wonder how to make every pages that need go through login page. If the person doesn't log in, it will redirect to login page.
I include a function
confirm_logged_in();
in every page but it keeps asking for the login even after I log in. Please tell me how to fix that It only needs to log in once but still the keeps people from entering a direct link manually.
I do have session_start(); in every page!
Here the code for login page
$username = "";
if (isset($_POST['submit'])) {
$required_fields = array("username", "password");
validate_presences($required_fields);
if (empty($errors)) {// Attempt Login
$username = $_POST["username"];
$password = $_POST["password"];
$found_admin = attempt_login_admin($username, $password);
$found_client = attempt_login_client($username, $password);
if ($found_admin) {
$_SESSION["admin_id"] = $found_admin["admin_id"];
$_SESSION["username"] = $found_admin["username"];
redirect_to("admin.php");
}elseif($found_client){
$_SESSION["client_id"] = $found_client["client_id"];
$_SESSION["username"] = $found_client["username"];
redirect_to("client.php");
} else{// Failure
$_SESSION["message"] = "Username/password not found.";
}
}
}
Here the code for functions:
function redirect_to($new_location) {
header("Location: " . $new_location);
exit;
}
function logged_in() {
return isset($_SESSION['admin_id'] );
}
function confirm_logged_in() {
if (!logged_in()) {
redirect_to("login.php");
}
}
function find_admin_by_username($username) {
global $connection;
$safe_username = mysqli_real_escape_string($connection, $username);
$query = "SELECT * ";
$query .= "FROM users ";
$query .= "WHERE status='admin' ";
$query .= "AND username = '{$safe_username}' ";
$query .= "LIMIT 1";
$admin_set = mysqli_query($connection, $query);
confirm_query($admin_set);
if($admin = mysqli_fetch_assoc($admin_set)) {
return $admin;
} else {
return null;
}
}
function find_client_by_username($username) {
global $connection;
$safe_username = mysqli_real_escape_string($connection, $username);
$query = "SELECT * ";
$query .= "FROM users ";
$query .= "WHERE status='client' ";
$query .= "AND username = '{$safe_username}' ";
$query .= "LIMIT 1";
$client_set = mysqli_query($connection, $query);
confirm_query($client_set);
if($client = mysqli_fetch_assoc($client_set)) {
return $client;
} else {
return null;
}
}
function attempt_login_admin($username, $password) {
$admin = find_admin_by_username($username);
if ($admin) {
// found admin, now check password
if (password_check($password, $admin["hashed_password"])) {
// password matches
return $admin;
} else {
// password does not match
return false;
}
} else {
// admin not found
return false;
}
}

$found_admin = attempt_login_admin($username, $password);
$found_client = attempt_login_client($username, $password);
if ($found_admin) {
$_SESSION["admin_id"] = $found_admin["admin_id"];
$_SESSION["username"] = $found_admin["username"];
redirect_to("admin.php");
}elseif($found_client){
$_SESSION["client_id"] = $found_client["client_id"];
$_SESSION["username"] = $found_client["username"];
redirect_to("client.php");
}
I don't understand if the functions attempt_login_admin() and attempt_login_client() return a bool or an array. If you fix that, It should work. You can return a bool in the associative array by assigning the return bool value to $found_admin['bool'] and verifying the bool in the if-block by if($found_admin['bool']) { ... }.

Related

User logs in and is redirected to a page specific to them

Hey im creating a site with users that need to log in. For some reason after the user logs in with a successful combination of email and password, they are redirected to a blank index.php instead of the user_page.php that I have created. I know there are other questions similar to this, I have looked through them but was unable to implement their corrections into my own code.
$errors = array();
$message = "";
$email = "";
$password = "";
if(isset($_POST["submit"])) { //THIS CHECKS LOG IN INFORMATION
//form was submitted
//$email = trim($_POST["email"]);
//$password = trim($_POST["password"]);
//header('Location: user_page.php?id=' . $_SESSION['user_id']);
//Validations
$required_fields = array("email", "password");
validate_presences($required_fields);
foreach ($required_fields as $field){
$value = trim($_POST[$field]);
if (!has_presence($value)) {
$errors[$field] = ucfirst($field) . " can't be blank"?><br/><?php ;
}
}
if (empty ($errors)) {
//try to login in
$email = trim($_POST["email"]); //set the variables for use in the function so they can be used as a value in the form, if its been submitted prev it echos back
$password = trim($_POST["password"]);
$found_email = attempt_login($email, $password); //function find user or return null or false
if ($found_email) {
// Success
// Mark user as logged in
$_SESSION["email_id"] = $found_email["id"]; //better than using a cookie which is visible in browser
$_SESSION["email"] = $found_email["email"]; //always know what the user name can use it browser or return the value back
redirect_to("user_page.php");
} else {
// Failure
$_SESSION["message"] = "Email/password not found.";//do not alert as to which field was incorrect
}
}
} else {
/*$email = "";
$password = "";
$message = "";*/
} //if isset end
I have a separate page with validations and functions that come from my learning source. if any other information is needed let me know. Thank You!
functions
<?php
function redirect_to($new_location)
{
header("Location: " . $new_location);
exit;
}
function mysql_prep($string)
{
global $connection;
$escaped_string = mysqli_real_escape_string($connection, $string);
return $escaped_string;
}
function password_encrypt($password)
{
$hash_format = "$2y$10$"; // Tells PHP to use Blowfish with a "cost" of 10
$salt_length = 22; // Blowfish salts should be 22-characters or more
$salt = generate_salt($salt_length);
$format_and_salt = $hash_format . $salt;
$hash = crypt($password, $format_and_salt);
return $hash;
}
function generate_salt($length)
{
// Not 100% unique, not 100% random, but good enough for a salt
// MD5 returns 32 characters
$unique_random_string = md5(uniqid(mt_rand(), true));
// Valid characters for a salt are [a-zA-Z0-9./]
$base64_string = base64_encode($unique_random_string);
// But not '+' which is valid in base64 encoding
$modified_base64_string = str_replace('+', '.', $base64_string);
// Truncate string to the correct length
$salt = substr($modified_base64_string, 0, $length);
return $salt;
}
function password_check($password, $existing_hash)
{
// existing hash contains format and salt at start
$hash = crypt($password, $existing_hash);
if ($hash === $existing_hash) {
return true;
} else {
return false;
}
}
function find_all_users()
{
global $connection;
$query = "SELECT * ";
$query .= "From users ";
$query .= "ORDER BY position ASC";
$result = mysql_query($connection, $query);
confirm_query($user_set);
return $user_set;
}
function find_user_by_email($email)
{
global $connection;
$safe_email = mysqli_real_escape_string($connection, $email);
$query = "SELECT * ";
$query .= "FROM users ";
$query .= "WHERE email = '{$safe_email}' ";
$query .= "LIMIT 1";
$email_set = mysqli_query($connection, $query);
confirm_query($email_set);
if ($email = mysqli_fetch_assoc($email_set)) {
return $email;
} else {
return null;
}
}
function find_email_by_id($email_id)
{
global $connection;
$safe_email_id = mysqli_real_escape_string($connection, $email_id);
$query = "SELECT * ";
$query .= "FROM email ";
$query .= "WHERE id = {$safe_email_id} ";
$query .= "LIMIT 1";
$email_set = mysqli_query($connection, $query);
confirm_query($email_set);
if ($email = mysqli_fetch_assoc($email_set)) {
return $email;
} else {
return null;
}
}
function attempt_login($email, $password)
{
$email = find_user_by_email($email);
if ($email) {
// found user, now check password
if (password_check($password, $email["hashed_password"])) {
// password matches
return $email;
} else {
// password does not match
return false;
}
} else {
// user not found
return false;
}
}
function logged_in()
{
return isset($_SESSION['email_id']);
}
// function confirm_logged_in()
// {
// if (!logged_in()) {
// redirect_to("index.php");
// }
// }
?>

Session in PHP Function

I'm new in php i create one function from where i'm login my session now i want to use this function for multiple time like for admin login too how i can use this function for multiple session. I updated my answer as per instruction of PacMan. Rightnow I'm doing it like this:
Code For USER & Admin Login:
//Check Wheather User Logged in or Not
if (isset($_SESSION['LoggedID']) && !empty($_SESSION['LoggedID'])){
$tableName = "prd_rgistration";
$id = $_SESSION['UserLogin'];
}else{
$tableName = "user_register";
$id = $_SESSION['AdminID'];
}
//Check Wheather User Logged in or Not
function Logged(){
if(LoggedIn()){
global $conn;
return $conn->query(sprintf('SELECT * FROM ' + $tableName + ' WHERE id = \'%d\'',$id))->fetchObject();
}else{
return (object)array();
}
}
function LoggedIn(){
return isset($id) && intval($id);
}
function redirect($Location){
header(sprintf('Location: %s',$Location),true,301);
exit;
}
if(LoggedIn()){
$User = Logged();
}
Admin Login Page Code
if($email_err == "" && $password_err == ""){
$Code = 0;
try{
$get_data = $conn->query("SELECT * FROM `user_register` WHERE `reg_email` = '$email' AND `reg_pass` = '$password' LIMIT 1");
if($get_data->rowCount() > 0){
$_SESSION['AdminID'] = $get_data->fetchObject()->id;
redirect('/domain.com/temp/admin/index.php');
}else{
$error = '<div class="alert alert-info">Invalid Email/Password</div>';
}
}catch(PDOException $E){
$Code = $E->getCode();
}
}
User Login Page Code
if($email_err == '' && $user_pass_err == ''){
$Code = 0;
try{
$get_data = $conn->query("SELECT * FROM `prd_rgistration` WHERE `email_db` = '$email' AND `password_db` = '$user_pass' LIMIT 1");
if($get_data->rowCount() > 0){
$_SESSION['UserLogin'] = $get_data->fetchObject()->id;
redirect('/domain.com/temp/index.php');
//redirect('/domain.com/index.php');
}else{
$error = '<div class="alert alert-info">Invalid Email/Password</div>';
}
}catch(PDOException $E){
$Code = $E->getCode();
}
}
Now It's giving Error Undefined AdminID and also not login user.
i can suggest you to follow this procedure it may be helpful , by changing the table name to a variable
if (isset($_SESSION['LoggedID']) && !empty($_SESSION['LoggedID'])){
$tableName = "prd_rgistration";
$id = $_SESSION['LoggedID'];
}else if(isset($_SESSION['adminID']) && !empty($_SESSION['adminID'])){
$tableName = "admin";
$id = $_SESSION['adminID']
}
//Check Wheather User Logged in or Not
function Logged(){
if(LoggedIn()){
global $conn;
return $conn->query(sprintf('SELECT * FROM '$tableName' WHERE id = \'%d\'',$id))->fetchObject();
}else{
return (object)array();
}
}
and here is it you have parametred only one function for both of usses admin and user login

pull from session user info

ok I have a user login that uses email address and password when they login I want to pull there session data
like username and anything else from there record
I use this
<?php
if(isset($_SESSION['email'])) {
echo $_SESSION['email'];
}
?>
it works and pulls there email address but how do I get there username? I tried changing email to username and nothing shows
my login setup
/* login functions */
function login_user($email, $password, $remember)
{
$sql = "SELECT user_pwd, uid FROM users WHERE user_email = '" . escape($email) . "' AND active = 1";
$result = query($sql);
if (row_count($result) == 1) {
$row = fetch_array($result);
$db_password = $row['user_pwd'];
if (password_verify($password, $db_password)) {
if ($remember == "on") {
setcookie("email", $email, time() + 86400,'/');
}
$_SESSION['email'] = $email;
return true;
} else {
return false;
}
return true;
} else {
return false;
}
}
/* User Logged in Function */
function logged_in(){
if (isset($_SESSION['email']) || isset($_COOKIE['email'])) {
return true;
} else {
return false;
}
}
You need to make small changes in login_user() function.
function login_user($email, $password, $remember)
{
$sql = "SELECT user_pwd, uid, username FROM users WHERE user_email = '" . escape($email) . "' AND active = 1";
$result = query($sql);
if (row_count($result) == 1) {
$row = fetch_array($result);
$db_password = $row['user_pwd'];
if (password_verify($password, $db_password)) {
if ($remember == "on") {
setcookie("email", $email, time() + 86400,'/');
}
$_SESSION['email'] = $email;
$_SESSION['username'] = $row['username'];
return true;
} else {
return false;
}
return true;
} else {
return false;
}
}
Now you can use below code to get username in session. But make sure you must have username field in users table.
if(isset($_SESSION['username'])) {
echo $_SESSION['username'];
}

Cannot validate right? Why? New to PDO

I cant seem to validate right when i have an empty field or when the username is wrong or doesnt match. please any help or pointing me would be very helpful. I tried (empty but it doesnt seem to work when i fill in one field and the other is empty its says all fields are empty. and for the wrong credentials its not working at all.
INDEX.PHP
<?php
session_start();
include_once 'php/classes/class.user.php';
$user = new User();
$log = $_SESSION['uid'];
if ($user->get_session($log)){
header("Location: profile.php?uid=".$log."");
}
if (isset($_REQUEST['submit'])) {
extract($_REQUEST);
$login = $user->check_login($emailusername, $password);
if(!empty($login)){
if($emailusername != $login){
if($password != $login){
if ($login) {
// Registration Success
$log_id = $_SESSION['uid'];
header("location: profile.php?uid=".$log_id."");
}
}else
echo "Incorrect Password";
}else
echo "Incorrect Email";
}else
echo "Fill in fields";
}
?>
USERS.PHP
<?php
include "db_config.php";
class User{
public $db;
public function __construct(){
$this->db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
}
}
/*** for login process ***/
public function check_login($emailusername, $password){
$password = md5($password);
$sql2="SELECT uid from users WHERE uemail='$emailusername' or uname='$emailusername' and upass='$password'";
//checking if the username is available in the table
$result = mysqli_query($this->db,$sql2);
$user_data = mysqli_fetch_array($result);
$count_row = $result->num_rows;
if ($count_row == 1) {
// this login var will use for the session thing
session_start();
$emaildb == $_SESSION['uemail'];
$_SESSION['login'] = true;
$_SESSION['uid'] = $user_data['uid'];
return true;
}
else{
return false;
}
}
/*** for showing the username or fullname ***/
public function get_fullname($uid){
$sql = "SELECT * FROM users WHERE uid = $uid";
$result = mysqli_query($this->db, $sql);
$user_data = mysqli_fetch_array($result);
echo $user_data['fullname'], "<br/>";
echo $user_data['uemail'], "<br/>";
echo $user_data['uid'], "<br/>";
}
public function check_user($uid){
$sql5 = "SELECT * from users WHERE uid='$uid'";
$result1 = mysqli_query($this->db, $sql5);
$count_row1 = $result1->num_rows;
return ($count_row1 == 1);
}
/*** starting the session ***/
public function get_session(){
return $_SESSION['login'];
}
public function user_logout() {
$_SESSION['login'] = FALSE;
session_destroy();
}
}
Based on what you have, this is what you would need.
session_start();
include_once 'php/classes/class.user.php';
$user = new User();
// You need a conditional incase this session isn't set
$log = (isset($_SESSION['uid']))? $_SESSION['uid']:false;
if($log !== false && $user->get_session($log)){
header("Location: profile.php?uid=".$log."");
exit;
}
if(isset($_POST['submit'])) {
// This function should be validating your login so you don't need
// any comparisons after the fact.
$login = $user->check_login($_POST['email'], $_POST['password']);
if($login !== false)
header("location: profile.php?uid=".$log_id."");
exit;
else {
foreach($user->error as $kind => $err) {
echo '<h2>'.$kind.'</h2>'.'<p>'.$err.'</p>';
}
}
}
Your user class: You can throw error reporting into this class if you want to.
class User{
public $db;
public $error;
public function __construct(){
$this->db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
$this->error['db'] = "Error: Could not connect to database.";
echo $this->error['db'];
exit;
}
}
/*** for login process ***/
public function check_login($emailusername='', $password=''){
// Validate that your email is a real one
if(filter_var($emailusername,FILTER_VALIDATE_EMAIL) !== false) {
$password = md5($password);
// --> You can prepare, bind, and execute your values here replacing what you have now....<--
$sql2 = "SELECT uid from users WHERE uemail='$emailusername' or uname='$emailusername' and upass='$password'";
//checking if the username is available in the table
$result = mysqli_query($this->db,$sql2);
$user_data = mysqli_fetch_array($result);
$count_row = $result->num_rows;
if ($count_row == 1) {
$emaildb == $_SESSION['uemail'];
// this login var will use for the session thing
$_SESSION['username'] = $user_data['uemail'];
// $_SESSION['uemail'] = $user_data['uemail'];
$_SESSION['uid'] = $user_data['uid'];
$_SESSION['login'] = true;
}
else
$this->error['account'] = 'ERROR: Invalid Username/Password';
}
else
$this->error['email'] = 'ERROR: Invalid Email Address';
return (!isset($_SESSION['uemail']))? false:true;
}
/*** for showing the username or fullname ***/
public function get_fullname($uid){
// --> You can prepare, bind, and execute your values here replacing what you have now....<--
$sql = "SELECT * FROM users WHERE uid = $uid";
$result = mysqli_query($this->db, $sql);
$user_data = mysqli_fetch_array($result);
echo $user_data['fullname'], "<br/>";
echo $user_data['uemail'], "<br/>";
echo $user_data['uid'], "<br/>";
}
public function check_user($uid){
// --> You can prepare, bind, and execute your values here replacing what you have now....<--
$sql5 = "SELECT * from users WHERE uid='$uid'";
$result1 = mysqli_query($this->db, $sql5);
$count_row1 = $result1->num_rows;
return ($count_row1 == 1);
}
/*** starting the session ***/
public function get_session(){
return $_SESSION['login'];
}
public function user_logout() {
$_SESSION['login'] = FALSE;
session_destroy();
}
}
$login is a boolean variable, while $emailusername and $password are strings, why you compare them.

Create a function out of this php code

I just need some help creating a php function out of this code or in other words just to wrap this code in a php function :
if (isset($_GET['id'])){
$username = mysql_real_escape_string($_GET['id']);
if(ctype_alnum($username)){
$check = mysql_query("SELECT username,first_name FROM users WHERE username='$username'");
if(mysql_num_rows($check)===1){
$get = mysql_fetch_assoc($check);
$username = $get['username'];
$firstname = $get['first_name'];
echo '<div id="mini_profile">This is '.$username.'\'s profile.</div>';
}else{
header("Location: index.php");
exit();
}
}
}
Thanks.
Really easy :)
function yourFunc() {
if (isset($_GET['id'])){
$username = mysql_real_escape_string($_GET['id']);
if(ctype_alnum($username)){
$check = mysql_query("SELECT username,first_name FROM users WHERE username='$username'");
if(mysql_num_rows($check)===1){
$get = mysql_fetch_assoc($check);
$username = $get['username'];
$firstname = $get['first_name'];
echo '<div id="mini_profile">This is '.$username.'\'s profile.</div>';
}else{
header("Location: index.php");
exit();
}
}
}
}
function getMyDivElement($name) {
$username = mysql_real_escape_string($name);
if(ctype_alnum($username)) {
$check = mysql_query("SELECT username,first_name FROM users WHERE username='{$username}'");
if(is_resource($check) && ($get = mysql_fetch_assoc($check))) {
$username = $get['username'];
$firstname = $get['first_name']; //You need this?
return '<div id="mini_profile">This is '.$username.'\'s profile.</div>';
}
}
return null;
}
//usage
if (isset($_GET['id'])) {
$div = getMyDivElement($_GET['id']);
if($div) {
echo $div;
} else {
header("Location: index.php");
exit();
}
}
Another way to do it is to return the echo statement as a string.
The idea of creating a function is to provide reuseable code. This means you are encapsulating the logic, allowing you to change the inner workings of the code without it affecting the actual usage of the function and to avoid tedious repetition.
In your example you should think about the areas that fall into this category. I personally can see that several functions that could be made here.
Example, not run but should give you ideas.
<?php
function getUser($username)
{
if (is_string($username) && strlen($username)) {
$query = "
SELECT
username, firstname
FROM
users
WHERE
username = :username
";
$result = executeQuery($query, array("username" => $username));
return $result->fetch();
}
}
function getDatabase($host, $db, $user, $password)
{
return new PDO("mysql:host=$host;dbname=$dbname, $user, $pass");
}
function executeQuery($sql, array $params = array())
{
$db = getDatabase();
$conn = $db->prepare($sql);
return $conn->execute($params);
}
function validateInput($input)
{
return ctype_alnum($input);
}
function advanceTo($page, $params)
{
header("Location: $page.php");
exit();
}
if (isset($_GET["username"])){
if (validateInput($_GET["username"])) {
$user = getUser($_GET["username"]);
if (! empty($user)) {
// authUserAndSetSessionForUser($user);
/** This page is then directed to and welcome message shown **/
advanceTo("user-home-page", array($user));
} else {
advanceTo("index");
}
}
}
?>

Categories