Check if user exists Registration - php

I am building a social app in Corona SDK with PHP being the back-end.
I am trying to sign up to the app but a block of code is getting skipped over.
if (!$errors) {
$stmt = $con->prepare("SELECT username, email FROM users WHERE username=? OR email=?");
$stmt->bind_param("ss", $_POST['username'], $_POST['email']);
$stmt->execute();
foreach ($stmt->get_result() as $row) {
foreach (['username', 'email'] as $field) {
if ($row[$field] == $_POST[$field]) {
echo "Sorry, that " . $field . " is already in use.";
die();
}
}
}
}
That code checks if the username or email that was entered is already in the DB. It works fine with my website but it doesn't work with the app. I commented out all of the other echo statements and verified that that specific block of code just doesn't run. Can someone help me ?
/*if ($_SERVER['REQUEST_METHOD'] != 'POST' || ! isset($_POST['Register'])) {
// Use full absolute URL header('Location: https://www.yoursite.com/index.php');
//header('Location: index.php');
echo "Not POST";
die();
} */
require 'config/connect.php';
$con = new mysqli(...$dbCredentials);
$username = $_POST['username'] ?? '';
$email = $_POST['email'] ?? '';
$pw = $_POST['pw'] ?? '';
$errors = [];
if (!trim($username)) {
echo 'Fill in username to sign up';
die();
}
if (!preg_match("/^[a-zA-Z0-9]{5,}$/", $username)) {
echo 'Invalid username, only letters and/or digits.';
die();
}
if (!trim($pw)) {
echo 'Fill in password to sign up';
die();
}
if (!trim($email)) {
echo 'Fill in email to sign up';
die();
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo 'Invalid email';
die();
}
if (!$errors) {
$stmt = $con->prepare("SELECT username, email FROM users WHERE username=? OR email=?");
$stmt->bind_param("ss", $_POST['username'], $_POST['email']);
$stmt->execute();
foreach ($stmt->get_result() as $row) {
foreach (['username', 'email'] as $field) {
if ($row[$field] == $_POST[$field]) {
echo "Sorry, that " . $field . " is already in use.";
die();
}
}
}
}
$ipAddress = $_SERVER['REMOTE_ADDR'];
if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
$ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
}
if (!$errors) {
$pw = password_hash($_POST['pw'], PASSWORD_BCRYPT, ['cost' => 14]);
$stmt = $con->prepare("INSERT INTO users (username, email, pw, ip_address)
VALUES (?, ?, ?, ?)");
$stmt->bind_param("ssss", $username, $email, $pw, $ipAddress);
$stmt->execute();
$_SESSION["user_id"] = $_POST['username'];
echo "success";
die();
} else {
echo 'something is wrong here.';
die();
}
$_SESSION['error'] = '<b><p style="color: #fff; font-size: 30px; top: 34%;right: 50%;position: absolute;">
' . $errors . '</p></b>';
//header('Location: index.php');
//exit();

You should the early returns concept. First check if there are errors, show error message and exit. If there are no errors then move ahead further to the desired case. This may help.
if ($errors) {
echo 'something is wrong here.';
die();
}

Too complicated! I would simplified that like:
SELECT COUNT(`username`) FROM `users` WHERE username=? OR email=?;
$stmt->bind_param("ss", $username, $email);
In PDO there is a function called fetchColumn() to get the count as int. Its either 0 or 1. There should be a similar function in mysqli. I think it's mysqli_fetch_field()
username, password and email can simplified as well:
if (empty(trim($username)) or !ctype_alnum($username))
{ die('Username is either empty or invalid! Only alphanumeric characters'); }
if (empty(trim($pw)))
{ die('Fill in password to sign up'); }
if (empty(trim($email)) or !filter_var($email, FILTER_VALIDATE_EMAIL))
{ die('Email is either empty or not a valid address!'); }
if (!$errors) { can't be false
$pw = password_hash($pw);
never store username in session always user id its way safer!
If this should not work try to place an var_dump($errors) before sql check.
If this should not work check database connection and bind params values

Related

PHP Login Code not working - Database Connection is okay

I'm trying to set up a Register + Login for one of my Sites. The Registration process works completely fine but the Login seems to fail every time.
This is the register.php
<?php
require_once "config.php";
require_once "session.php";
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
$fullname = trim($_POST['name']);
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$confirm_password = trim($_POST['confirm_password']);
$password_hash = password_hash($password, PASSWORD_BCRYPT);
if($query = $db->prepare("SELECT * FROM users WHERE email =?")) {
$error = '';
$query->bind_param('s', $email);
$query->execute();
$query->store_result();
if ($query->num_rows >0) {
$error .= '<p class="error">E-Mail already registered</p>';
}
if (empty($confirm_password)) {
$error .= '<p class="error">Passwords do not match.</p>';
}
if (empty($error)) {
$insertQuery = $db->prepare("INSERT INTO users (name, email, password) VALUES (?, ?, ?);");
$insertQuery->bind_param("sss", $fullname, $email, $password_hash);
$result = $insertQuery->execute();
if ($result) {
$error .= '<p class="success">Your Registration was succesful!</p>';
} else {
$error .= '<p class="error">Something went wrong!</p>';
}
}
}
$query->close();
$insertQuery->close();
mysqli_close($db);
}
?>
This is the Login.php
<?php
require_once "config.php";
require_once "session.php";
$error = '';
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
$email = trim($_POST['email']);
$password = trim($_POST['password']) ;
if (empty($email)) {
$error .= '<p class="error">Please enter email.</p>';
}
if (empty($password)) {
$error .= '<p class="error">Please enter password.</p>';
}
if (empty($error)){
if($query = $db->prepare("SELECT * FROM users WHERE email = ?")) {
$query->bind_param('s',$email);
$query->execute();
$row = $query->fetch();
if ($row) {
if (password_verify($password, $row['password'])) {
$_SESSION["userid"] = $row['id'];
$SESSION["user"] = $row;
header("location: index2.php");
exit;
}else{
$error.= '<p class="error">The password is not valid.</p>';
}
}else{
$error.= '<p class="error">Wrong mail.</p>';
}
}
$query->close();
}
mysqli_close($db);
}
?>
According to Online PHP Checker my Code should be correct. There are no Errors in Console and I really don't know what exactly i did wrong. Hope someone can help me with this!
This line is the issue, I expect:
$row = $query->fetch();
According to the documentation, the fetch() function returns true, false or null - it does not return a row of data. You need to use bind_result() to map the results from the query into variables.
https://www.php.net/manual/en/mysqli-stmt.fetch.php

password_verify() in php returns false for correct password

Here is the register.inc.php
<?php
include_once 'db_connect.php';
include_once 'psl-config.php';
include_once 'functions.php';
$error_msg = "";
sec_session_start();
if (isset($_POST['username'], $_POST['email'], $_POST['p'], $_POST['firstname'], $_POST['lastname'], $_POST['email'], $_POST['contactno'], $_POST['address'], $_POST['inviteid']
)) {
// Sanitize and validate the data passed in
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$email = filter_var($email, FILTER_VALIDATE_EMAIL);
$phone = filter_input(INPUT_POST,'contactno', FILTER_SANITIZE_STRING);
$firstname = filter_input(INPUT_POST, 'firstname', FILTER_SANITIZE_STRING);
$lastname = filter_input(INPUT_POST, 'lastname', FILTER_SANITIZE_STRING);
$inviteid = filter_input(INPUT_POST, 'inviteid', FILTER_SANITIZE_STRING);
$address = filter_input(INPUT_POST, 'address', FILTER_SANITIZE_STRING);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Not a valid email
$error_msg .= '<p class="error" style="color:red; font-size:16px;>* The email address you entered is not valid</p>';
}
$password = filter_input(INPUT_POST, 'p', FILTER_SANITIZE_STRING);
if (strlen($password) != 128) {
// The hashed pwd should be 128 characters long.
// If it's not, something really odd has happened
$error_msg .= '<p class="error" style="color:red; font-size:16px;>* Invalid password configuration.</p>';
}
// Username validity and password validity have been checked client side.
// This should should be adequate as nobody gains any advantage from
// breaking these rules.
//
$prep_stmt = "SELECT id FROM members WHERE email = ? LIMIT 1";
$stmt = $mysqli->prepare($prep_stmt);
// check existing email
if ($stmt) {
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
// A user with this email address already exists
$error_msg .= '<p class="error" style="color:red; font-size:16px;">* A user with this email address already exists.</p>';
$stmt->close();
}
} else {
$error_msg .= '<p class="error" style="color:red; font-size:16px;>* Database error Line 39</p>';
$stmt->close();
}
// check existing username
$prep_stmt = "SELECT id FROM members WHERE username = ? LIMIT 1";
$stmt = $mysqli->prepare($prep_stmt);
if ($stmt) {
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
// A user with this username already exists
$error_msg .= '<p class="error" style="color:red; font-size:16px;">* A user with this username already exists</p>';
$stmt->close();
}
} else {
$error_msg .= '<p class="error" style="color:red; font-size:16px;>* Database error line 55</p>';
$stmt->close();
}
// check existing username
$prep_stmt = "SELECT id FROM members WHERE myid = ? LIMIT 1";
$stmt = $mysqli->prepare($prep_stmt);
if ($stmt) {
$stmt->bind_param('s',$_POST['inviteid']);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 0) {
// A user with this us
$error_msg .= '<p class="error" style="color:red; font-size:16px;">* No user with this id exists</p>';
$stmt->close();
}
} else {
$error_msg .= '<p class="error" style="color:red; font-size:16px;>* Database error line 55</p>';
$stmt->close();
}
//1.86€y9.31€$Ac2w6xufmG.jI3F/5GZhDOdW1TzAPrnJ3oPF0seGHI6g03QopB4C
// TODO:
// We'll also have to account for the situation where the user doesn't have
// rights to do registration, by checking what type of user is attempting to
// perform the operation.
if (empty($error_msg)) {
// Create hashed password using the password_hash function.
// This function salts it with a random salt and can be verified with
// the password_verify function.
$passwords = password_hash($password,PASSWORD_BCRYPT);
// Insert the new user into the database
if ($insert_stmt = $mysqli->prepare("INSERT INTO members (username, email, password,firstname,lastname,phone,address,inviteid) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")) {
$insert_stmt->bind_param('ssssssss', $username, $email, $passwords, $firstname, $lastname, $phone, $address, $inviteid);
// Execute the prepared query.
if (! $insert_stmt->execute()) {
header('Location: ../error.php?err=Registration failure: INSERT');
}
}
/*if (login($_POST['email'],$_POST['p'], $mysqli) == true) {
// Login success
header('Location: dashboard.php');
}else{
// Login failed
//header('Location: login.php');
} */
// header('Location: dashboard.php');
//exit();
}
}
?>
process_login.php
<?php
include_once 'db_connect.php';
include_once 'functions.php';
include_once '../securimage/securimage.php';
//$securimage = new Securimage();
sec_session_start(); // Our custom secure way of starting a PHP session.
if (isset($_POST['email'], $_POST['p'])) {
$email = $_POST['email'];
$password = $_POST['p']; // The hashed password.
if (login($email, $password, $mysqli) == true) {
// Login success
// header("Location: ../protected_page.php");
header('Location: ../dashboard.php');
}else{
// Login failed
header('Location: ../login.php?error=1');
}
} else {
// The correct POST variables were not sent to this page.
header('Location: ../error.php?err=Could not process login');
exit();
}
Hi there I am trying to hash my passwords with password_hash() in PHP. This part is fine but to compare the hash is returning false no matter what. To log in I check the user account database and grab the password hash then compare it to the password typed in.Have checked all solutions here.
My code looks like this:
function login($email, $password, $mysqli) {
// Using prepared statements means that SQL injection is not possible.
if ($stmt = $mysqli->prepare("SELECT id, username, password, myid, firstname, lastname,status,ambLevel
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, $myid, $fname, $lname, $status,
$ambLevel);
$stmt->fetch();
var_dump($db_password);
var_dump($password);
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. We are using
// the password_verify function to avoid timing attacks.
if (password_verify($password,$db_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['firstname'] = $fname;
$_SESSION['lastname'] = $lname;
$_SESSION['myid'] = $myid;
$_SESSION['email'] = $email;
$_SESSION['status'] = $status;
$_SESSION['ambLevel'] = $ambLevel;
$_SESSION['login_string'] = hash('sha512',
$db_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;
}
}
}
Please kindly help. View my full source code here.
Works as expected...
<?php
$hash=password_hash("password", PASSWORD_DEFAULT);
if (password_verify("password", $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
?>
I've had the same issue, and resolved it by setting the password column in my DB to a sufficiently long (255) VARCHAR instead of CHAR or NCHAR variable. If this doesn't help, try var_dump at all the transfer points: when first hashing, taking it from the database itself, and after submitting your query.

Empty fields can get inserted into my database

I have the following code. I try to use my Submit button to insert the code into the database, but every time I use it and refresh the browser, empty fields get inserted into the database.
<?php
$servername = "localhost";
$username = "root";
$password = "";
//create connection
$cn = new mysqli($servername, $username, $password, "milege");
//check connection
if ($cn->connect_error) {
echo "Connection failed!". $cn->connect_error;
}
// once the button is clicked
if (isset($_POST['submitForm'])) {
//the values in the boxes
$name = $_POST['fname'];
$email = $_POST['email'];
$password = $_POST['password'];
$confpass = $_POST['confpass'];
$interest = $_POST['interest'];
$info = $_POST['info'];
//echo "connection successfully";
//Insert into table
$sql = "INSERT INTO miltb(name, email, password, interest, info, productorder) VALUES('$name', '$email', '$password', '$interest', '$info', 'none' )";
}
if ($cn->query($sql) == true) {
?><script>alert ("INSERTED SUCCESSFULLY!");</script><?php
} else {
echo "error: " . $sql . "\n" . $cn->error;
}
$cn->close();
?>
How would I fix it?
The reason empty fields get inserted in the database it's because you are not checking for empty fields, you need to check those empty fields first then if empty fields exists do not insert.
Well man there's a lot that you need to learn, you need to learn about
1.SQL Injections
2.mysqli prepared or pdo prepared statements.
3.Password hashing
Filter ,sanitize and validate user inputs
Never trust an input from the user, you must always treat a user input as if it comes from a dangerous hacker.
Then you code with prepared statements should look like this :
<?php
//create connection
$cn = new mysqli($servername, $username, $password, "milege");
//check connection
if ($cn->connect_error) {
echo "Connection failed!" . $cn->connect_error;
}
$error = "";
// once the button is clicked
if (isset($_POST['submitForm'])) {
// check for empty fiels
if (empty($_POST['fname'])) {
echo "Enter your name";
$error++;
} else {
$name = userInput($_POST['fname']);
}
if (isset($_POST['email'])) {
echo "enter email";
$error++;
} else {
$email = userInput($_POST['email']);
// validate email
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
echo "enter a valid email";
$error++;
}
}
if (empty($_POST['password'])) {
echo "enter password";
$error++;
} else {
$password = userInput($_POST['password']);
$hash = password_hash($password, PASSWORS_DEFAULT); //hash the password
}
if (!empty($_POST['confpass']) && $_POST['confpass'] !== $_POST['password']) { //password confirmation
echo "passwords does not match";
$error++;
}
if (empty($_POST['interest'])) {
echo "enter interests";
$error++;
} else {
$interest = userInput($_POST['interest']);
}
if (empty($_POST['info'])) {
echo "enter info";
$error++;
} else {
$info = userInput($_POST['info']);
}
if ($error > 0) { // if we have errors don't insert to db
echo "you have " . $error . " error(s) on your form plz fix them";
} else { // no errors lets insert
// prepare and bind
$sql = $cn->prepare("INSERT INTO miltb(name, email, password, interest, info) VALUES (?, ?, ?,?,?)");
$sql->bind_param("sssss", $name, $email, $hash, $interest, $info);
if ($sql->execute()) {
echo "INSERTED SUCCESSFULLY!";
} else {
echo "could not insert ";
}
}
$sql->close();
$cn->close();
}
function userInput($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Hope this will help and you will learn a thing or two, I stand to be corrected where I'm wrong
Use something like this to be sure values are inserted:
$name = isset($_POST['fname']) ? strval($_POST['fname']) : null;
if (empty($name)){
echo "Name can't be empty!";
exit();
}
Note: beware of SQL Injection. Using php function strval() is the least possible secutiry, but atleast use that, if nothing more.

PHP PDO Declare name as variable

So In my project I'm trying to declare a variable so it will display their full name if logged in. I'm assuming it would be a query to fetch the data from the table but I'm unsure on how to have it make sure it get's that certain user's name and not the first name on the table
Here's my registration code.
if( $user->is_logged_in() ){ header('Location: index.php'); }
//if form has been submitted process it
if(isset($_POST['submit'])){
//very basic validation
if(strlen($_POST['username']) < 3){
$error[] = 'Username is too short.';
} else {
$stmt = $db->prepare('SELECT username FROM members WHERE username = :username');
$stmt->execute(array(':username' => $_POST['username']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(!empty($row['username'])){
$error[] = 'Username provided is already in use.';
}
}
if(strlen($_POST['password']) < 3){
$error[] = 'Password is too short.';
}
if(strlen($_POST['passwordConfirm']) < 3){
$error[] = 'Confirm password is too short.';
}
if($_POST['password'] != $_POST['passwordConfirm']){
$error[] = 'Passwords do not match.';
}
//email validation
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
$error[] = 'Please enter a valid email address';
} else {
$stmt = $db->prepare('SELECT email FROM members WHERE email = :email');
$stmt->execute(array(':email' => $_POST['email']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(!empty($row['email'])){
$error[] = 'Email provided is already in use.';
}
}
//email validation
if(strlen($_POST['fullname']) < 2){
$error[] = 'Please enter a valid full name';
} else {
$stmt = $db->prepare('SELECT fullname FROM members WHERE fullname = :fullname');
$stmt->execute(array(':fullname' => $_POST['fullname']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(!empty($row['email'])){
$error[] = 'Email provided is already in use.';
}
}
//if no errors have been created carry on
if(!isset($error)){
//hash the password
$hashedpassword = $user->password_hash($_POST['password'], PASSWORD_BCRYPT);
//create the activasion code
$activasion = md5(uniqid(rand(),true));
try {
//insert into database with a prepared statement
$stmt = $db->prepare('INSERT INTO members (username,password,email,fullname,active) VALUES (:username, :password, :email, :fullname, :active)');
$stmt->execute(array(
':username' => $_POST['username'],
':password' => $hashedpassword,
':email' => $_POST['email'],
':fullname' => $_POST['fullname'],
':active' => $activasion
));
$id = $db->lastInsertId('memberID');
//send email
$to = $_POST['email'];
$subject = "Registration Confirmation";
$body = "Thank you for registering at demo site.\n\n To activate your account, please click on this link:\n\n ".DIR."activate.php?x=$id&y=$activasion\n\n Regards Site Admin \n\n";
$additionalheaders = "From: <".SITEEMAIL.">\r\n";
$additionalheaders .= "Reply-To: $".SITEEMAIL."";
mail($to, $subject, $body, $additionalheaders);
//redirect to index page
header('Location: index.php?action=joined');
exit;
//else catch the exception and show the error.
} catch(PDOException $e) {
$error[] = $e->getMessage();
}
}
}
Updated with the user class:
<?php
include('password.php');
class User extends Password{
private $_db;
function __construct($db){
parent::__construct();
$this->_db = $db;
}
private function get_user_hash($username){
try {
$stmt = $this->_db->prepare('SELECT password FROM members WHERE username = :username');
$stmt->execute(array('username' => $username));
$row = $stmt->fetch();
return $row['password'];
} catch(PDOException $e) {
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
}
}
public function login($username,$password){
$hashed = $this->get_user_hash($username);
if($this->password_verify($password,$hashed) == 1){
$_SESSION['loggedin'] = true;
return true;
}
}
public function logout(){
session_destroy();
}
public function is_logged_in(){
if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true){
return true;
}
}
}
Why not simply select them from the database?
Please don't mind me if I mix in a little pseudo code since I'm not very familiar with your variables.
First, you create/start a SESSION if the login credentials are correct.
if($login_credentials_correct){ //lol you know what I mean here
session_start();
$_SESSION['username'] = $_POST['username']; // or wherever it may have come from
}
Now that the session is on, you can perform a query somewhat similar to this
<?php
session_start(); // fixed
$username = $_SESSION['username'];
$stmt = $db->prepare('SELECT fullname FROM members where username= :username');
$stmt->execute(array(':username'=>$username));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$fullName = $row['fullName']; //I am not sure if this is the correct index.
//to make sure, use var_dump($row) and find out which index has the full name
echo $fullName; //voila.
?>
Now, this code only works if your username is unique. Lol. which site has no unique username.
Can you post your log in code? I'll try to answer with what you ave so far.
If you want users to have the ability to log in and have their data available for display do this
if(!($_SERVER['REQUEST_METHOD'] == "POST")){
//Code here for users trying to access page incorrectly
}else{
if(isset($_POST['username']) && ($_POST['username'] <= $UsernameMaxLength)){
$username=strip_tags(stripslashes($_POST['username'])); //Clean the data up
}else{
//Error handling code
}
if(isset($_POST['password']) && ($_POST['password'] <= $PasswordMaxLength)){
//I would advise you use SHA1() instead for password encryption, but I'll use what you used here
$password=$user->password_hash(strip_tags(stripslashes($_POST['password'])), PASSWORD_BCRYPT); //Clean the data up
}else{
//Error handling code
}
if(!isset($username) || !isset($password)){
//Error handling code
}else{
$stmt = $db->prepare('SELECT fullname FROM members where username= :username and password=:password');
$stmt->execute(array('username':$username,'password':$password));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//Code here to make sure there is a row with the number given and all that
//other jazz. In this code I'll assume all went well
if(All_went_well){
//Start your session to store variables you want
session_start();
$_SESSION['fullname']=$row['fullname'];
}
}
}
In your login method, save $username as a session value under $_SESSION['loggedin'] that you can retrieve later like this...
public function login($username,$password){
$hashed = $this->get_user_hash($username);
if($this->password_verify($password,$hashed) == 1){
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
return true;
}
}
Then have another method at the bottom of the file that goes something like...
public function get_username(){
if(isset($_SESSION['username'])){
return $_SESSION['username'];
}
}
Then you can call this method like $user->get_username() to get the current logged in users username. Then getting their fullname from the database would require a simple query with "WHERE username = :username". I you can add another method like this to make things easier...
public function get_fullname(){
if(issset($_SESSION['username']){
$stmt = $this->_db->prepare('SELECT fullname FROM members WHERE username = :username');
$stmt->execute(array('username' => $this->get_fullname()));
$row = $stmt->fetch();
return $row['fullname'];
}
}

What is wrong with my Register function?

Problem & Explanation
Hello I have just coded a function that first does checking if account exists in database with that name, and then if email exists in database with that entered email.
If not, return true + insert data.
But in this case, nothing happens on submit, it just shows the form, but doesn't inserts the data..
What is wrong with it?
function createAccount($name, $password, $email)
{
global $pdo;
$check_in = $pdo->prepare("SELECT * FROM users WHERE user_name = :username LIMIT 1");
$check_in->execute( array(':username' => $name) );
if (!$check_in->rowCount())
{
$check_in = email_exists($email);
if ($check_in === false)
{
$insert_in = $pdo->prepare
("
INSERT INTO
users
(user_name, user_password, user_email)
VALUES
(:name, :password, :email)
");
$insert_in->execute( array
(
':name' => $name,
':password' => $password,
':email' => $email
));
return true;
}
else
{
return 'exists';
}
}
else
{
return 'user_in_use';
}
}
function email_exists($email)
{
global $pdo;
$check = $pdo->prepare("SELECT * FROM users WHERE user_email = :email LIMIT 1");
$check->execute( array(':email' => $email) );
if ($check->rowCount())
{
return true;
}
else
{
return false;
}
}
This is how I make up the register:
# Creating shortcuts
if (isset($_POST['username']) && isset($_POST['password']) && isset($_POST['email']))
{
$name = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
}
# Creating errors array
$errors = array();
if (isset($_POST['submit']))
{
$check_in = createAccount($name, $password, $email);
if ($check_in === true)
{
echo 'Created account sucessfully!';
}
else if ($check_in == 'already_in_use')
{
echo 'Could not create account because name already in use..';
}
else if($check_in == 'exists')
{
echo 'Email already in use..';
}
}
Question:
What is wrong with this code & how do I fix this? I have no errors at all.
It just won't insert any data to the Database.
Yes, the PDO connection & statements are right, because the login works perfectly.
Thanks a lot!
EDIT!
if ($check_in === true)
{
echo 'Created account sucessfully!';
}
else if ($check_in == 'already_in_use')
{
echo 'Could not create account because name already in use..';
}
else if($check_in == 'exists')
{
echo 'Email already in use..';
} else {
echo 'Error is there...';
}
It's echoing 'Error is there...' apon submit!
I just want to slap myself!.....
The problem was: The fields were set as INT, therefore we could not store anything but ints...

Categories