Get ID from table inside session user id - php

Hi I am trying to get value from userID column in my table inside the sessein array.
in my register class I have the following code:
<?php
class Users {
public $username = null;
public $password = null;
public $salt = "Zo4rU5Z1YyKJAASY0PT6EUg7BBYdlEhPaNLuxAwU8lqu1ElzHv0Ri7EM6irpx5w";
public function __construct( $data = array() ) {
if( isset( $data['username'] ) ) $this->username = stripslashes( strip_tags( $data['username'] ) );
if( isset( $data['password'] ) ) $this->password = stripslashes( strip_tags( $data['password'] ) );
}
public function storeFormValues( $params ) {
//store the parameters
$this->__construct( $params );
}
public function userLogin() {
$success = false;
try{
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$stmt->execute();
$valid = $stmt->fetchColumn();
if( $valid ) {
$success = true;
$_SESSION['userID'] = $user->user_id;
}
for which syntaxis I am not very sure that it will sessionize the UserID value of the logged user.
and in the login where the array is created I have
<?php
session_start();
include_once("config.php"); //include the settings/configuration
?>
<?php
//else look at the database and see if he entered the correct details
} else {
session_start();
$usr = new Users;
$usr->storeFormValues( $_POST );
if( $usr->userLogin() ) {
header( 'Location: cursos.php' ) ;
$_SESSION["loggedIn"] = true;
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
$_SESSION['userID'] = $_POST['userID'];
but it gives me every time NULL result how to fix it ?

first of all if you're posting the form you should use $_POST['userID'] and first check it if you retrieving the value in your $_POST['userID'] then you have to start session like this
session_start();
$_SESSION['userID'] = $_POST['userID']
but the first one code i understand you're using codeigniter or OOP $user->user_id the first $user is your variable and second one is user_id which may be your access modifier also check $user->user_id it has value then do same
session_start();
$_SESSION['userID'] = $user->user_id;

Related

I want to fetch user id from wp_user table. I wrote following code but it is not working

I want the code which creates user if it is not present in db and it is working fine but if user is authentic then I want to give access to wordpress site.Control is going in Else block but I am not able to fetch ID of user from email with following code which written in else block. What should I do to achieve that?
if($bearer_token){
global $wpdb;
$name = $_POST['log'];
$email = $_POST['log'];
//$table_name = $wpdb->prefix . "wpuser";
include_once(ABSPATH . '/var/www/html/wp-config.php');
$connection = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
$link = mysqli_select_db($connection, DB_NAME);
if($link){
// echo "Success";
////////////////
$db_name = $wpdb->prefix . "users";
// echo $table_name;
$wpdb->insert( $db_name, array(
'name' => $name,
'email' => $email
) );
///////////////
}else{
echo "Fail";
}
}else{
echo "Error";
}
//////////////////////////
if($bearer_token){
add_action( 'init', function () {
$username = $_POST['log'];
$password = $_POST['pwd'];
$email_address = $_POST['log'];
//$url = "0.0.0.0:8000"
// echo "if inside";
if ( ! username_exists( $username ) )
{
$user_id = wp_create_user( $username, $password, $email_address );
echo $user_id;
$user = new WP_User( $user_id );
$user->set_role( 'contributor' );
}elseif (username_exists($username)==True) {
// $user = get_user_by( 'user_email', $email_address );
// $user = wp_get_current_user();
$userdata = WP_User::get_data_by( 'user_login', $username );
if ( !$userdata )
return false;
$user = new WP_User;
$user->init( $userdata );
return $user;
# code...
}else{
echo "Errorrr";
}
}
);
}else{
echo "Unauthenticate user";
}
I am not sure if you have decided on how you will differentiate between first login by a user and all the subsequent logins by the same user. But if you want to create a new user every time you encounter a new email, the simplest way would be to pass your login credential to wp_authenticate($username, $password) and you can override this to perform custom check as follow:
add_action( 'wp_authenticate' , 'check_custom_authentication', 10, 2 );
function check_custom_authentication ( $username, $password ) {
if ( ! username_exists( $username ) ) {
return;
}
// use wp_set_password function here to set password by getting user id from the login detail we have.
}

How to check if user already exist?

class Users {
public $username = null;
public $password = null;
public $salt = "Zo4rU5Z1YyKJAASY0PT6EUg7BBYdlEhPaNLuxAwU8lqu1ElzHv0Ri7EM6irpx5w";
public function __construct( $data = array() ) {
if( isset( $data['username'] ) ) $this->username = stripslashes( strip_tags( >$data['username'] ) );
if( isset( $data['password'] ) ) $this->password = stripslashes( strip_tags( >$data['password'] ) );
}
}
public function storeFormValues( $params ) {
$this->__construct( $params );
}
public function register() {
$correct = false;
try {
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "INSERT INTO users(username, password) VALUES(:username, :password)";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$stmt->execute();
return "Registration Successful <br/> <a href='index.php'>Login Now</a>";
}catch( PDOException $e ) {
return $e->getMessage();
}
}
}
I would like to check if a user already exist in my database, because it lets me create accounts with same username anytime.
Thanks.
I would recommend a few things to help here.
1) Make your username column unique in the database. This would prevent usernames that are not unique from being inserted.
2) Once you have a unique index on username, attempt the insert, and check for success on the insert. Since you can get the error code from mysql, if the query was not successful and the error code is due to a duplicate value...throw the username already exists error.
This is the basic idea of how to return if the username exists.
public function username($username)
{
$sth = $this->db->prepare("SELECT id, username FROM table WHERE username = ?");
$sth->execute(array($username));
$row = $sth->fetch();
if(username == $row['username'])
{
do code here since username does not exist
} else {
echo 'username already exists';
}
}
$sell= mysql_query("select * from `signup` where emailid='$email'");
$cntc=mysql_num_rows($sell);
if($cntc==0) {
$sql=mysql_query("INSERT INTO `signup`(`firstname`,`lastname`,`emailid`,`dob`,`companyname`,`phoneno`,`password`) VALUES ('$name','$lastname','$email','$dob','$comname','$phone','$pass')");
if($sql) {
echo'inserted successfully';
}
} else {
echo'Email is already exist. ';
}

Set userid into the session array how?

Hello I am posting maybe 4th question about this issue but nobody can help me so far, so let's start from the begining, what I need is simple I need to: Set userID variable from column name "userID' inside table named "users" into the Sessions array: $_SESSION['userID']
here is my login page code:
<?php
session_start();
include_once("config.php"); //include the settings/configuration
?>
<?php if( !(isset( $_POST['login'] ) ) ) { ?>
<?php
//else look at the database and see if he entered the correct details
} else {
session_start();
$usr = new Users;
$usr->storeFormValues( $_POST );
if( $usr->userLogin() ) {
header( 'Location: cursos.php' ) ;
$_SESSION["loggedIn"] = true;
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
and here is my user class which operates the function login:
public function userLogin() {
$success = false;
try{
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$stmt->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
$success = true;
if ($result!==false) { // Check there is a match
$_SESSION['userID']= $result['userID'];
}
$success = true;
$con = null;
return $success;
}catch (PDOException $e) {
echo $e->getMessage();
return $success;
The code is working fine I just want to add addition to it which will get the userID value from the column of the users table inside the database ans store it to the $_SESSION['userID'] after user is loged in.
So any idea how to reach this goal in my code ? thanks!
If you just want the UserID from the table, you're going to have to do a $stmt->fetch() to load it first, then you can store it in your SESSION.
So after the execute in function userLogin() do:
$result = $stmt->fetch(PDO::FETCH_ASSOC);
If the user was found $result will then contain all of the fields from the users table. So:
if ($result!==false) { // Check there is a match
$_SESSION['userID']= $result['userID'];
}

Login redirecting to specific page based on user name

I'm in the process of learning PHP and MySQL.
I would like from the script to recognize a specific name and redirect it to admin.php. For example "if Username is Brian redirect him to admin.php, if the username is everything except Brian, redirect him to account.php".
Both Brian and the other persons must be registered in the database to be able to login. I thought on redirect based on MySQL user id, but I don't know how to write the code. Or if you know another simple solution.
Here is the script:
<?php
class Users {
public $username = null;
public $password = null;
public $salt = "";
public function __construct( $data = array() ) {
if( isset( $data['username'] ) ) $this->username = stripslashes( strip_tags( $data['username'] ) );
if( isset( $data['password'] ) ) $this->password = stripslashes( strip_tags( $data['password'] ) );
}
public function storeFormValues( $params ) {
//store the parameters
$this->__construct( $params );
}
public function userLogin() {
$success = false;
try{
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT userID FROM users WHERE username='username' AND password= :password AND userTypeId = 1 LIMIT 1";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$stmt->execute();
$valid = $stmt->fetchColumn();
if( $valid ) {
$success = true;
}
$con = null;
return $success;
}catch (PDOException $e) {
echo $e->getMessage();
return $success;
}
}
And this is the script from index.php (where the user writes his name and password)
<?php
} else {
$usr = new Users;
$usr->storeFormValues( $_POST );
if( $usr->userLogin() ) {
echo "Welcome";
} else {
echo "Incorrect Username/Password";
}
}
?>
Rather than recognizing a name (which you would have to parse) I believe it would be more efficient (and easier to implement) if you instead direct by user number (or whatever you're calling your primary key).
So if your user name is "Brian" and is the first user, with user number 1 then point to your table where the 1 is located, assuming it's stored as the integer 1 and not the string "1" instead.
Computers generally have an easier time dealing with integers rather than arrays. You can do it by string, but it's always going to be more work for you and the machine.
As far as redirecting goes, upon logging in, just do a check:
if user number is equal to [Brian's user number] then redirect to admin.php
else redirect to account.php
(Also you'll want to make sure that admin.php requires Brian be the logged in user, or anybody else could just navigate there manually)
The method $user->userLogin should return the id of current login user when successful login and return FALSE when failure login . then redirect to a admin.php or or account.php depend the returned id
First, try to fetch username and correct binding name for username:
$sql = "SELECT username FROM users WHERE username = :username AND ...
instead of:
$sql = "SELECT userID FROM users WHERE username='username' AND ...
//^ //^
Also just return fetched username on successful status. It returns a single column from the next row of a result set or FALSE if there are no more rows.
return $stmt->fetchColumn();
And then check logged in username by if condition to redirect desired page:
$usr = new Users;
$usr->storeFormValues( $_POST );
$username = $usr->userLogin();
if( $username !== false ) {
if(strtolower($username) == "brian"){
header("Location: admin.php");
} else {
header("Location: account.php");
}
} else {
echo "Incorrect Username/Password";
}

Login function doesn't seem to be functioning correctly

I've been sitting here pondering this for a good 30 minutes now and I just can't see what's wrong.
I've added prints but it just doesn't seem to be contacting the database correctly or not pulling the data from it correctly.
$conf['sql_host'] = 'localhost';
$conf['sql_user'] = 'root';
$conf['sql_pass'] = '';
$conf['sql_data'] = 'c_webauth';
mysql_connect( $conf['sql_host'], $conf['sql_user'], $conf['sql_pass'] ) or die( 'Connection failed: '.mysql_error() );
mysql_select_db( $conf['sql_data'] );
function login( $user, $pass ){
session_regenerate_id();
if ( isset( $_SESSION['user_id'] ) ) {
unset( $_SESSION['user_id'] );
}
$qry = mysql_query( "SELECT user_id, user, user_group, user_name FROM c_users where user='$user' AND pass='".md5($pass)."'" );
if ( mysql_num_rows( $qry ) > 0 ) {
session_regenerate_id();
while ( $data = mysql_fetch_array( $qry ) ) {
$_SESSION['user_id'] = $data['user_id'];
$_SESSION['user_group'] = $data['user_group'];
$_SESSION['user'] = $data['user'];
$_SESSION['user_name'] = $data['user_name'];
// Debug
echo $_SESSION['user_id'];
echo $_SESSION['user_group'];
echo $_SESSION['user'];
echo $_SESSION['user_name'];
session_start( );
}
}
}
login( "username", "password" );
Anychance you can see whats wrong?
Everyone has mentioned that I had my session_start(); in the wrong place, but the echo's print nothing, absolutely no errors anywhere.
You are calling session_start() at the end instead before doing session checks
session_start( ); it should used before session use
You have put session_start( ) at bottom , after you have assigned SESSION variables
Put this function on top of the page and remove from bottom.
You need to put session_start() at the top of your code, because its at the bottom all $_SESSION variables are undeclared so they wont return a value. One session_start() is at the top you'll get the global $_SESSION variables and you'll also be able to set them. I advise that you create a script called config.php that has session_start() and you can include it in all your scripts instead of add session_start() everytime.
Hope this helps you out :D
<?php
session_start();
$conf['sql_host'] = 'localhost';
$conf['sql_user'] = 'root';
$conf['sql_pass'] = '';
$conf['sql_data'] = 'c_webauth';
mysql_connect( $conf['sql_host'], $conf['sql_user'], $conf['sql_pass'] ) or die( 'Connection failed: '.mysql_error() );
mysql_select_db( $conf['sql_data'] );
function login( $user, $pass ){
session_regenerate_id();
if ( isset( $_SESSION['user_id'] ) ) {
unset( $_SESSION['user_id'] );
}
$qry = mysql_query( "SELECT user_id, user, user_group, user_name FROM c_users where user='$user' AND pass='".md5($pass)."'" );
if ( mysql_num_rows( $qry ) > 0 ) {
session_regenerate_id();
while ( $data = mysql_fetch_array( $qry ) ) {
$_SESSION['user_id'] = $data['user_id'];
$_SESSION['user_group'] = $data['user_group'];
$_SESSION['user'] = $data['user'];
$_SESSION['user_name'] = $data['user_name'];
// Debug
echo $_SESSION['user_id'];
echo $_SESSION['user_group'];
echo $_SESSION['user'];
echo $_SESSION['user_name'];
}
}
}
login( "username", "password" );
?>
I've fixed your code for you.

Categories