Using a variable to direct traffic - php

I am mostly sure that my error is with the variable not being gotten from the table. However I can not see the error I am asking for that data at the same time I am asking for the username and password. The table consists of [username],[password],[company]. The goal is to have the user get directed based on the name in company after the username and password have been verified. I keep getting the echo at the end.
Here is the code
function RegisterUser($usename, $password, $company)
{
// hash the pwd
$hpwd = hash('sha256',$password);
$q ='insert into users values(username, password, company) values(?,?,?)';
$stmt = PDO::prepare($q);
$stmt->exectue(array( $username, $hpwd, $company));
}
// validate user and return the company if successfull
function ValidateUser($username, $password, &$company)
{
$hpwd = hash('sha256',$password);
$q ='select company from users where username=? AND password=?';
$stmt = PDO::prepare($q);
$stmt->exectue(array( $username, $hpwd));
if( ($company = $stmt->fetch(PDO::FETCH_COLUMN)) === false )
{
$company = header( 'Location: login.php' );
}
elseif($company == "monkeynones"){
header( 'Location: admin1.php' );
}

Your query is wrong:
$sql = "SELECT 'password' and 'company' from users where 'username' = '$username';";
should be
$sql = "SELECT `password`, `company` from `users` where `username` = '$username'";
Use backticks, not quotes, around identifiers. and is replaced by a comma, and the trailing semicolon in the query isn't required.

It is so important that new programmers learn to do username/password authentication properly I felt it necessary to write this longer post.
Firstly, as eicto pointed out, the mysql extension is both deprecated and should really not even be used ever.
So to the metal.
visit php.net and learn about PDO
Never store unencoded passwords.
here is what you should do:
set up PDO:
// you need to store $link somewhere. in a class preferrably
function InitPDO(&$link)
{
// havet the database handle all strings as UTF-8.
$options = array('PDO::MYSQL_ATTR_INIT_COMMAND' => 'set names utf8');
$link = new PDO ( 'mysql:host='.$config['dsn_host'].';dbname='.$config['dsn_db'], $config['username'], $config['password'], $options ) ;
// If there is an error executing database queries, have PDO to throw an exception.
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$link->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
upon registration of user.
function RegisterUser($username, $password, $company)
{
// hash the pwd
$hpwd = hash('sha256',$password);
$q ='insert into users values(username, password, company) values(?,?,?)';
$stmt = $link->prepare($q);
$stmt->execute(array( $username, $hpwd, $company));
}
// validate user and return the company if successfull
function ValidateUser($username, $password, &$company)
{
$hpwd = hash('sha256',$password);
$q ='select company from users where username=? AND password=?';
$stmt = $link->prepare($q);
$stmt->execute(array( $username, $hpwd));
if( ($company = $stmt->fetch(PDO::FETCH_COLUMN)) === false )
{
$company = 'invalid'; // because user auth failed';
}
//else all is good
}
example test usage.
// assumes there is a 'login.php' and a 'invalid.php' file
$link = null;
InitPDO( $link );
RegisterUser('tester','password','login');
VerifyUser('tester','password', $redir );
if( file_exists( $redir . '.php' ) )
{
header( 'Location: '. $redir . '.php' );
exit;
}
echo 'error. no valid page found to fullfill query';

Related

How to apply the bcrypt also how to fetch data

When I try to login it doesn't display any information, it didn't get the data in database.
if($_SERVER['REQUEST_METHOD']=='POST'){
//filter this variable for security
$username = strip_tags(mysqli_real_escape_string($conn, trim($_POST['username'])));
$password = strip_tags(mysqli_real_escape_string($conn, trim($_POST['password'])));
$stmt = $conn->prepare("SELECT id FROM students WHERE s_id = ?");
$stmt->bind_param("s",$username);
$stmt->execute();
$user = $stmt->fetch();
if($user == FALSE) {
die("Incorrect");
}else {
$password_hash = $user['password'];
$validPassword = password_verify($password, $password_hash);
if($validPassword){
echo "success";
} else{
//$validPassword was FALSE. Passwords do not match.
echo 'Incorrect username / password combination!<br/>';
echo $user['password'];
}
}
}
Your query only selects the id. Change your query to select your id and password.
$stmt = $conn->prepare("SELECT * FROM students WHERE s_id = ?");
Then you will have your hashed password $user['password'] in the results.
I'd be tempted to wrap everything in a try/catch block and raise exceptions at key points to determine where the code breaks. Also I think the result from the query should be bound to a variable prior to fetching the results using $stmt->bind_result
When using a prepared statement I'd suggest that you do NOT use mysqli_real_escape_string nor use trim as it would be perfectly valid for a password to start or end with a space - the database engine will process the statement in a manner that is safe.
if( $_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['username'],$_POST['password']) ){
try{
$args=array(
'username' => FILTER_SANITIZE_STRING,
'password' => FILTER_SANITIZE_STRING
);
$_POST=filter_input_array( INPUT_POST, $args );
extract( $_POST );
$stmt = $conn->prepare("select `password` from `students` where `s_id` = ?");
if( $stmt ){
$stmt->bind_param( "s", $username );
$result = $stmt->execute();
if( $result ){
/* There should be only 1 record - bind to a variable */
$stmt->bind_result( $pwdhash );
/* fetch the results of the query */
$stmt->fetch();
/* is the password correct? */
$validpassword = password_verify( $password, $pwdhash );
echo $validpassword ? 'Success' : 'Error: Incorrect username or password';
$stmt->close();
} else {
throw new Exception('No results returned');
}
} else {
throw new Exception('failed to prepare sql query');
}
} catch( Exception $e ){
exit( $e->getMessage() );
}
}

Problems php and MySQL

I have 2 tables, user log that is where the people make a register with their email and password, and another table with the name user where the people make complete their own profile.
How can I make with an SQL query to insert the data that insert in the form?
Taking into account that table user makes reference with table user log with the id...
I mean
User log
Id
Email
Password
User
Id
User_id fk id reference userlog(id)
Name
Surname
This is the code wich i made the log in
<?php
session_start();
if (isset($_SESSION['usuario'])) {
header('Location: index.php');
}
$errores = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = filter_var(strtolower($_POST['email']), FILTER_SANITIZE_STRING);
$password = $_POST['password'];
$password = hash('sha512', $password);
try {
$conexion = new PDO('mysql:host=localhost;dbname=DATABASE, 'USER', 'PASS');
} catch (PDOException $e) {
echo "Error:" . $e->getMessage();;
}
$statement = $conexion->prepare('
SELECT * FROM userlog WHERE email = :email AND password = :password'
);
$statement->execute(array(
':email' => $email,
':password' => $password
));
$resultado = $statement->fetch();
if ($resultado !== false) {
$_SESSION['usuario'] = $resultado;
header('Location: index.php');
} else {
$errores .= '<li>Datos Incorrectos</li>';
}
}
I make a var_dump() to see what the array in $resultado bring, and it brign me the data of the table, but, when I want to use the data to fill an input it fails
If your data will be coming from POST method, please always use precautions to avoid SQL injection..
I will be using a very elementary example. You can enhance this one for your own use.
$servername = "localhost";
$username = "yourUser";
$password = "yourPass";
$dbname = "youtDB";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$sql = "INSERT INTO Userlog (email, password)
VALUES ('some_email#example.com', 'some_safe_password')";
$conn->exec($sql);
$last_id = $conn->lastInsertId();
$userSql = "INSERT INTO Userlog (userId, name, lastName) VALUES ($last_id, 'some_name', 'some_lastName')";
$conn->exec($userSql);
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
You can pass your data by using post method.
try this code.
$sql = "INSERT INTO users (Userlog, Id, Email, Password)
VALUES ('".$_POST["Userlog"]."','".$_POST["Id"]."','".$_POST["Email"].",'".$_POST["Password"]."')";

How to show data from database only from currently logged user?

I want to show data from database to only currently logged user. So for example, if I want to show him when did he created his account, how can I show him only this value? And I mean this value of only his account. Not all.
I tried
<?php
$dbhost = '';
$dbuser = '';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = "Select date from members"
mysql_select_db('');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "{$row['date']} <p> ";
}
?>
But this shows ALL dates from that table. I want to show date of currently logged user only.
Thanks
EDIT :
Users log in with email and pass (which is hashed)
Here is my function for login
function login($email, $password, $mysqli) {
// Using prepared statements means that SQL injection is not possible.
if ($stmt = $mysqli->prepare("SELECT id, username, password, salt
FROM members
WHERE email = ?
LIMIT 1")) {
$stmt->bind_param('s', $email); // Bind "$email" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
// get variables from result.
$stmt->bind_result($user_id, $username, $db_password, $salt);
$stmt->fetch();
// hash the password with the unique salt.
$password = hash('sha512', $password . $salt);
if ($stmt->num_rows == 1) {
// If the user exists we check if the account is locked
// from too many login attempts
if (checkbrute($user_id, $mysqli) == true) {
// Account is locked
// Send an email to user saying their account is locked
return false;
} else {
// Check if the password in the database matches
// the password the user submitted.
if ($db_password == $password) {
// Password is correct!
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
// XSS protection as we might print this value
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
$_SESSION['user_id'] = $user_id;
// XSS protection as we might print this value
$username = preg_replace("/[^a-zA-Z0-9_\-]+/",
"",
$username);
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['login_string'] = hash('sha512',
$password . $user_browser);
// Login successful.
return true;
} else {
// Password is not correct
// We record this attempt in the database
$now = time();
$mysqli->query("INSERT INTO login_attempts(user_id, time)
VALUES ('$user_id', '$now')");
return false;
}
}
} else {
// No user exists.
return false;
}
}
}
Use a the WHERE column='value' code at the end of your SQL (see: http://www.tizag.com/mysqlTutorial/mysqlwhere.php)
Example:
If you know the user's ID that is used in your database, store that in a variable (here called $usersIDnr).
Then use the columns name (userID for example) to use in the following code at the end of your SQL:
WHERE userID='$usersIDnr'

How to get $_SESSION['id'] from a session

Hello I have 2 tables in my database one for courses and one for users, each of them has an id column.
I am trying to create a relationship between them, one user subscribe to one course. The result I am trying to store inside a 3rd table called subscription, which has a column for the course ID and column for user id.
The users are registering after passing log-in which is connected with a new session. After user click subscribe link which is
<a href='subscribe.php?id=".$row['id']."'>subscribe!</a>
they are taken to the backend php page where it is the inserted into database information:
<?php
session_start();
?>
$userid = $_SESSION['userID'];
$cursoid = $_GET['id'];
mysql_connect("localhost", "username", "password") or die(mysql_error()) ;
mysql_select_db("test") or die(mysql_error()) ;
mysql_query("INSERT INTO `subscriptions`
(curso_id, user_id)
VALUES ('$cursoid', '$userid ')")
or die(mysql_error());
at this point I have obtained the id of the course and it is inserted inside it, the problem is for the user ID I am not getting anything. How I can get the id for the current logged in user ?
here is the code of my class for the login function:
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;
}
$con = null;
return $success;
}catch (PDOException $e) {
echo $e->getMessage();
return $success;
$user = $stmt->fetchObj();
if( $user->user_id > 0 ) {
$success = true;
// User has been successfully verified, lets sessionize his user id so we can refer to later
$_SESSION['userID'] = $user->user_id;}
}
}
and finally here is the code of the login function:
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['id'] = $_POST['id'];
You should NOT be using sessionIds as userIds, instead you should be using the primary key of the user table after you have inserted the user row. Also, probably being pedantic, but you should rename your user variable to $user, $usr makes me wince.
Another way to get session id is: session_id
-- Edit --
public function userLogin() {
....
$user = $stmt->fetchObj();
if( $user->user_id > 0 ) {
$success = true;
// User has been successfully verified, lets sessionize his user id so we can refer to later
$_SESSION['userId'] = $user->user_id;
}
}
// We sessionized user id after validation, so we now have access to it
$userid = $_SESSION['userId'];
// Using straight mysql api is frowned upon, this should be converted to PDO before production use
mysql_query("INSERT INTO `subscriptions` (curso_id, user_id) VALUES ('$cursoid', '$userid ')")
or die(mysql_error());
Every time you want to work with a session, you must call session_start function at the beginning of the file. You called it in login function, but don't call in subscribe.php. Try this:
session_start();
$userid = $_SESSION['id'];
$cursoid = $_GET['id'];
//rest of the code
Also you have a minor error here as well, you had a space in this line VALUES ('$cursoid', '$userid ')")
mysql_query("INSERT INTO `subscriptions`
(curso_id, user_id)
VALUES ('$cursoid', '$userid')")
or die(mysql_error());

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";
}

Categories