check if username exists and generate new username if it does PHP - php

I am trying to write a simple function that checks if a username exists in the db and if so to call another function to generate a new username. My code seems to fall over though:
Username Function:-
$user1=create_username($fname, $company);
function create_username($surname, $company){
//$name_method=str_replace(" ", "", $surname);
$name_method=$surname.$forename;
$company_name_method=str_replace(" ", "", $company);
if(strlen($name_method)<=5)
{
$addition=rand(11,99);
$first=$addition.$name_method;
}
else
{
$first=substr($name_method,0,5);
}
if(strlen($company_name_method)<=5)
{
$addition2=rand(11,99);
$second=$addition2.$company_name_method;
}
else
{
$second=substr($company_name_method,0,5);
}
$middle=rand(100,1000);
$username=$first.$middle.$second;
return($username);
}
Check Username Function:
check_user($user1, $dbc, $fname, $company);
function check_user($user1, $dbc, $surname, $company){
$check_username="SELECT username FROM is_user_db WHERE username='$user1'";
$resultx=mysqli_query($dbc, $check_username) or die("Could not check username");
$num_rows=mysqli_num_rows($resultx);
if($num_rows>0)
{
$user1=create_username($fname, $company);
check_user($user1, $dbc, $fname, $company);
}
else
{
return($user1);
}
}
It just seems to return the original username.

You probably need to re-factor your code a little. Write out the steps on paper; that helps me. So far, I can see:
You want to check a username is unique on form submission
If it's not, generate a new username
So, check the username when your form is POSTed:
<?php
if (isset($_POST['submit'])) {
if (username_unique($_POST['username'])) {
// carry on processing form
}
else {
$suggested_username = suggest_username($_POST['username']);
// display form, with new suggested username?
}
}
And then write your functions:
<?php
// following on from code from above
function check_username($username) {
// get database connection (I use PDO)
$sql = "SELECT COUNT(*) AS count FROM users_tbl WHERE username = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute(array($username));
$row = $stmt->fetchObject();
return ($row->count > 0); // if 'count' is more than 0, username already exists
}
function suggest_username($username) {
// take username, and add some random letters and numbers on the end
return $username . uniqid();
}
Hopefully this will help. Obviously it'll need some modification to work in your set-up, but this is the general flow you'll need.

Related

Pass a $_POST value into a function parameter with a PDO variable

I have setup a pdo connection and pass that as a variable into a function. This all works fine and the function returns correctly. If I run the function in a conditional statement with the PDO variable and a name it runs correctly - if name is in database it echos correctly if not then it also echos correctly. What I want to do is to pass the value of a form post to the function so that it checks to see if it exists in the database. Here is my code:
The function checks to see if the column count is one.
function user_exists($pdo, $username) {
$stmt = $pdo->prepare('SELECT COUNT(uid) FROM users WHERE username = :username');
$stmt->execute(['username' => $username]);
$result = $stmt->fetchColumn();
return ($result == 1);
}
If the admin user exists in the database echo 'exists' - Just for testing.
if(user_exists($pdo,'admin') == true) {
echo "exists";
} else {
echo "doesnt exist";
}
Checks to see of both fields have been entered then I want it to check if the username entered is in the database, but I am doing something wrong.
if(!empty($_POST) === true) {
$username = $_POST['username'];
$pwood = $_POST['password'];
if(empty($username) === true || empty($pwood) === true) {
echo "You need to enter a username and password";
} else if (user_exists($pdo,$_POST['username']) == false){
echo 'We can\'t find that username. Please try again or register';
}
}
Better don't compare with bool values, just use
//...see below
require_once('UserRepository.php');
$ur = new UserRepostory($pdo);
if(!empty($_POST)) {
if (empty($username) || empty($pwood)) {
// something
} else if (!$ur->exists($_POST['username'])) { // your user_exists($pdo, $username) works fine, too
// something else
}
}
Especially the initial if(!empty($_POST) === true) { is hard to read and lead to errors 'cause of misunderstood operator priority.
Update based on the comments above, here is an example with a class:
// UserRepository.php
class UserRepository {
private $pdo;
// '\PDO' instead of 'PDO', see PHP Namespacing
public function __construct (\PDO $pdo)
{
$this->pdo = $pdo;
}
public function exists($username)
{
$sql = 'SELECT COUNT(uid) FROM users WHERE username = :username');
$stmt = $this->pdo->prepare($sql);
$stmt->execute(['username' => $username]);
$result = $stmt->fetchColumn();
return (bool) $result;
}
}

store MySQL SELECT result in php variable using Prepared statements

I am trying to user prepared statements to find a user record and store the users ID in a php variable to use later on. I would like to echo the variable contents. How do I check the result using Prepared statements?
My CODE:
if ((isset($_POST['overrideUsername'])) and (isset($_POST['overridePassword'])) and (isset($_POST['overrideUniqueID']))) {
$overridePasswordInput = $_POST['overridePassword'];
$overrideUsernameInput = $_POST['overrideUsername'];
$roleID = '154';
$overrideUniqueID = $_POST['overrideUniqueID'];
//Not sure how to properly compare stored passwords vs password given by user...
$overridePassword = mysqli_real_escape_string($overridePasswordInput);
$overrideUsername = mysqli_real_escape_string($overrideUsernameInput);
//connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if(mysqli_connect_errno() ) {
printf('Could not connect: ' . mysqli_connect_error());
exit();
}
$conn->select_db($dbname);
if(! $conn->select_db($dbname) ) {
echo 'Could not select database. '.'<BR>';
}
$sql1 = "SELECT users.id FROM users WHERE (users.login = ?) AND (users.password = ?)";
$stmt1 = $conn->prepare($sql1);
$stmt1->bind_param('ss', $overrideUsername, $overridePassword);
$stmt1->execute();
$stmt1->bind_result($userID);
$stmt1->get_result();
if ($stmt1->get_result()) {
echo $userID;
} else {
echo 'User credentials incorrect. Please try again';
}
$stmt1->close();
//Close the Database connection.
$conn->close();
}//End If statement
Further more, this is the pre-existing code the original programmer used to authenticate users into the program:
if(!defined("noStartup")){
$scriptname = basename($_SERVER["PHP_SELF"]);
$phpbmsSession = new phpbmsSession;
//Testing for API login
if(strpos($scriptname,"api_")!==false){
if(isset($_POST["phpbmsusername"]) && isset($_POST["phpbmspassword"])){
$phpbmsSession->loadDBSettings();
include_once("include/db.php");
$db = new db();
$phpbmsSession->db = $db;
include_once("common_functions.php");
$phpbmsSession->loadSettings($sqlEncoding);
$phpbms = new phpbms($db);
if(!$phpbmsSession->verifyAPILogin($_POST["phpbmsusername"],$_POST["phpbmspassword"],ENCRYPTION_SEED))
$error = new appError(-700,"","Login credentials incorrect",true,true,true,"json");
} else
$error= new appError(-710,"","No login credentials passed",true,true,true,"json");
} else {
$phpbmsSession->loadDBSettings($sqlEncoding);
include_once("include/db.php");
$db = new db();
$phpbmsSession->db = $db;
$phpbmsSession->loadSettings($sqlEncoding);
include_once("common_functions.php");
$phpbms = new phpbms($db);
if(!isset($noSession))
$phpbmsSession->startSession();
if (!isset($_SESSION["userinfo"]) && $scriptname != "index.php") {
if(isset($loginNoKick)){
if(!isset($loginNoDisplayError))
exit();
} else{
goURL(APP_PATH."index.php");
}
}
}
$db->stopOnError=true;
}//end if
And the verifying function:
function verifyAPIlogin($user,$pass){
$thereturn=false;
$this->db->stopOnError = false;
$querystatement = "SELECT id, firstname, lastname, email, phone, department, employeenumber, admin, usertype
FROM users
WHERE login!=\"Scheduler\" AND login=\"".mysql_real_escape_string($user)."\"
AND password=ENCODE(\"".mysql_real_escape_string($pass)."\",\"".mysql_real_escape_string(ENCRYPTION_SEED)."\")
AND revoked=0 AND portalaccess=1";
$queryresult = $this->db->query($querystatement);
if(!$queryresult) {
$error = new appError(-720,"","Error retrieving user record",true,true,true,"json");
return false;
}
if($this->db->numRows($queryresult)){
//We found a record that matches in the database
// populate the session and go in
$_SESSION["userinfo"]=$this->db->fetchArray($queryresult);
$querystatement="UPDATE users SET modifieddate=modifieddate, lastlogin=Now() WHERE id = ".$_SESSION["userinfo"]["id"];
$queryresult=# $this->db->query($querystatement);
if(!$queryresult) {
$error = new appError(-730,"","Error Updating User Login Time",true,true,true,"json");
} else
$thereturn=true;
}
return $thereturn;
}
}//end loginSession class
NOTE: I have already tested that my $_POST() values are successfully coming through to my script.
EDIT:: added more code to give a better overall picture of what I'm attempting to do. Any shared tuturials on password encryption/authenticating users would be greatly appreciated.
Thank you!
As I mentioned in the comment, PHP now has a couple built in methods to handle encryption and decryption of passwords that you might find helps solve your problem:
password_hash and
password_verify

how to get data from database and save to session array

public function getLoginInfo($username,$password){
$conn=DB::connect();
session_start();
$sql="select * from owner where o_email='".mysql_real_escape_string($username)."' and o_password='".mysql_real_escape_string($password)."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$_SESSION['email']=$username;
$_SESSION['password']=$password;
}
header("location:../owner/owner_dashboard.php");
} else {
header("location:../owner/owner_login.php");
}
$conn->close();
}
i have added username and password to my session array but i also want to save id into session array which is stored into databse as "o_id"
You are over complicate the process than necessary. mysql_ extensions are also deprecated.Therefore, you should not use them. use prepare statements which prevent against sql injections. In additional, there is no need for you to store the password in the session. Your password should be stored in the database as hashed so storing it in session wont be reliable to you. Once you find a match against the username and password you searched for, you only need to store the username in the session. In your application, you can compare against the username of logged in area. I modified your code to a much cleaner solution. I had to made few assumptions such as your conn is a PDO.
public function getLoginInfo($username,$password)
{
//start the session only if it has not started somewhere else
if (session_status() == PHP_SESSION_NONE)
{
session_start();
}
//try to query the database
try {
$conn = DB::connect();
$sql = 'Select * from owner where o_email= :email and o_password = :password';
$conn->prepare($sql);
$res = $conn->execute(array(':email' => $username, ':password' => $password));
//check if the data exist. only true if result set is greater than 0
if ($res->rowCount() > 0)
{
$_SESSION['email']=$username;
header("location:../owner/owner_dashboard.php");
exit("login success, redirecting to dashboard...");
}
//doesnt exit so go back to login
header("location:../owner/owner_login.php");
exit('Invalid username or password. Redirecting back to lgoin...');
}
//Error is only output for debugging purpose. I would encourage turn this off in production
catch(Exception $e)
{
print_r($e->getMessage());
}
}
First of all, it must be clear that if you are querying for logging
in, then query will return only one row, so using while is
meaningless.
public function getLoginInfo($username,$password){
$conn=DB::connect();
session_start();
$sql="select * from owner where o_email='".mysql_real_escape_string($username)."' and o_password='".mysql_real_escape_string($password)."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Edited from here
// output data of each row
$row = $result->fetch_assoc();
$arraydata[$row['id']] = $row;
$_SESSION['user_info']=$arraydata;
$_SESSION['current_loggedin_id']=$row['id'];
header("location:../owner/owner_dashboard.php");
} else {
header("location:../owner/owner_login.php");
}
$conn->close();
}

Search user using part of the name

I have this PHP code:
function getusers($user) {
$result = query("SELECT IdUser, username FROM login WHERE username='%s'",$user);
if (count($result['result'])>0) {
//authorized
print json_encode($result);
} else {
errorJson('Actualization failed');
}
}
But this only returns the user that matches the name exactly.
I'd like to return all users containing that name string, for example:
dani -> daniel, dani_56, dani563, elnenedani, ...
It is usually done by putting in PHP: %dani% but as I have put the %s to grab the variable $user, I do not know how to put it.
Any idea?
It is not a great Question. If you have searched well in Stackoverflow you would have go it the answer.. As you asked the Question the answer is.. Instead of Equal use LIKE:
function getusers($user) {
$result = query("SELECT IdUser, username FROM login WHERE username LIKE %'%s'%",$user);
if (count($result['result'])>0) {
//authorized
print json_encode($result);
} else {
errorJson('Actualization failed');
}
}
It seems the PHP code and DB is working well. Checkout the below links for the error:
iOS 5 JSON Parsing Results in Cocoa Error 3840
Cocoa error 3840 using JSON (iOS)
The Operation couldn't be completed. (Cocoa error: 3840.)
Cocoa Error 3840 - NSJSONSerialization
You should use the LIKE syntax. Make sure to include % to indicate wildcards:
query('SELECT IdUser, username FROM login
WHERE username LIKE "%' . $user . '%"')
My query() function is
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
I do not get fixed. This code is for an ios app that uses AFNetworking, might please that helps you know what happens because I do not get it

Member search function

Im trying to come up with MySQL logic for a search function I got on my page. Its a simple form where the user can choose to fill in search criteria. The criteria(s) is send as arguments to a function that generates the mysql logic. This is whats inside the PHP controller file:
case 'search':
if((empty($_POST['username'])) && (empty($_POST['firstname'])) && (empty($_POST['lastname']))
&& (empty($_POSt['agemin'])) && (empty($_POST['agemax'])) && (empty($_POST['country']))){
$members = get_all_username();
} else {
if(isset($_POST['username'])){
$otheruser = $_POST['username'];
} else { $otheruser = null; }
if(isset($_POST['agemin'])){
$ageMin = $_POST['agemin'];
} else { $ageMin = null; }
if(isset($_POST['agemax'])){
$ageMax = $_POST['agemax'];
} else { $ageMax = null; }
if(isset($_POST['country'])){
$country = $_POST['country'];
} else { $country = null; }
//if(isset($_POST['isonline']))
$members = search_members($otheruser, $ageMin, $ageMax, $country);
}
include('displaySearch.php');
break;
So if nothing is set a complete list of all the members is generated and displayed. This is the function that is called if any of the inputs is set:
function search_members($username, $ageMin, $ageMax, $country){
global $db;
$query = "SELECT username FROM profiles WHERE username = :username
AND age > :ageMin AND age < :ageMax AND country = :country";
$statement = $db->prepare($query);
$statement->bindValue(':username', $username); $statement->bindValue(':ageMin', $ageMin);
$statement->bindValue(':ageMax', $ageMax); $statement->bindValue(':country', $country);
$statement->execute();
if($statement->rowCount() >= 1){
return $statement->fetchAll();
} else {
return false;
}
}
The mysql logic is obviously wrong. I need a set of conditions (in the MySQL logic if possible) that checks the PHP variables for value and if there is none it should not be accounted for when querying the database. So if only the username is set in the form the other variables should not be included in the SQL logic.
I've looked up the MySQL IF() condition but Im still not able to come up with proper code that does what I need. If someone could point me in the right direction I would be able to do the rest myself. Any other approach for solving this kind of problem is also welcome.
If i understand your problem, then the simple way is to use if else to build sql query, for example
$sql = "SELECT username FROM profiles WHERE 1 "
if (!is_null($username)) {
$sql .= " AND username = :username ";
}
// All other checks

Categories