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;
}
}
Related
I would like to output an error message on login if the website is under maintenance however my current code doesn't work and seems to just run as if the maintenance code isn't there. I would like it so if the maintenance column in MySQL database which i have already defined as $maintenance is empty then the user can login like normal however if it contains 1 then the user will see the error message however admins with their IP in the array can still login. I have defined $maintenance in a different file which is included already in my class.user.php. Code is below.
Settings.php
$auth_user = new USER();
$site_name = $auth_user->runQuery("SELECT * FROM `settings` LIMIT 1");
$site_name->execute();
while ($show = $site_name -> fetch(PDO::FETCH_ASSOC)){
$maintenance = $show['maintenance'];
}
Class.user.php
require_once('settings.php');
....other functions here
....other functions here
.....other functions here
.....
public function doLogin($uname,$umail,$upass)
{
try
{
$stmt = $this->conn->prepare("SELECT user_id, user_name, user_email, user_pass, status FROM users WHERE user_name=:uname OR user_email=:umail ");
$stmt->execute(array(':uname'=>$uname, ':umail'=>$umail));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() == 1)
{
if(password_verify($upass, $userRow['user_pass']))
{
session_regenerate_id(false);
return ["correctPass"=>true, "banned"=> ($userRow['status']== 1) ? true : false, "maintenance"=> ($maintenance== 1) ? true : false];
}
else
{
return ["correctPass"=>false];
}
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
Login.php
$validation = $login->doLogin($uname,$umail,$upass);
if($validation["correctPass"]){
if($validation["maintenance"]){
if (!in_array(#$_SERVER['REMOTE_ADDR'], array('1.1.1.1'))){
$error = "Website under maintenance";
}
}
if($validation["banned"]){
$error = "User has been banned";
}else{
if(Token::check($_POST['token'])) {
$stmtt = $login->runQuery("SELECT user_id FROM users WHERE user_name=:uname OR user_email=:umail ");
$stmtt->execute(array(':uname'=>$uname, ':umail'=>$umail));
$userRow=$stmtt->fetch(PDO::FETCH_ASSOC);
$_SESSION['user_session'] = $userRow['user_id'];
$success = "Logged in successfully, redirecting..";
header( "refresh:3;url=dashboard" );
} else {
$error = "Unexpected error occured";
}
}
}
else{
$error = "Incorrect username/email or password";
}
As others have pointed out in comments $maintenance is outside the scope of your doLogin function. If you are interested in just using it as a global variable, you can setup your doLogin function like this:
public function doLogin($uname,$umail,$upass)
{
global $maintenance;
...
Using the global keyword allows you to access variables outside the scope of the current function. A better way would probably be to pass the $maintenance variable into the function as a parameter like this:
public function doLogin($uname,$umail,$upass,$maintenance)
{
...
Then just use in in your Login.php file like this:
$validation = $login->doLogin($uname,$umail,$upass,$maintenance);
Do either of those options work for you?
I want to get and echo a users permission level.
I have a function where the users email is passed, the function then needs to get the users permission level and return it, so it can be echoed on another page.
I imagine the function will look though the database for the passed email, it then finds the users permission and returns with that.
In the 'User.class.php'
public static function permGetter($email)
{
try
{
$db = Database::getInstance();
$stmt = $db->prepare('SELECT permission FROM users WHERE email = :email LIMIT 1');
$stmt->execute([':permission'=>$permission]);
$user = $stmt->fetchObject('User');
if($user !== false)
{
return $permission;
}
}
catch (PDOException $exception)
{
error_log($exception->getMessage());
return false;
}
}
In the 'permRequest.php'
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once("../includes/init.php");
//Get passed from an external program
$email = $_GET['email'];
$pass = $_GET['pass'];
if($email && $pass !== null)
{
// Checks if the user's entered credential matches with those in database
if(Auth::getInstance()->login($email, $pass))
{
//Uses the passed email to get permission level in 'User.class.php'
if(User::permGetter($email))
{
echo 'Permission ' + (int) $permission;
}
}
else
{
//I use level 5 as a debug so i can see when it fails
echo 'Permission 5';
}
}
?>
Database
Here's an example on what my database looks like.
Edit 1
Okay messing about, I think i got closer to the solution.
First, #Lawrence Cherone, thanks for pointing out my mistake in my execute.
Okay I have changed my code in
User.class.php
public static function permGetter($email, $permission)
{
try
{
$db = Database::getInstance();
$stmt = $db->prepare('SELECT permission FROM users WHERE email = :email');
$stmt->execute([':email'=>$email]);
$row = $stmt->fetch(PDO::FETCH_NUM);
$permission = $row['permission'];
}
catch (PDOException $exception)
{
error_log($exception->getMessage());
return false;
}
}
I have made small changes to
permRequest.php
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once("../includes/init.php");
//Get passed from an external program
$email = $_GET['email'];
$pass = $_GET['pass'];
$permission = '';
if($email && $pass !== null)
{
// Checks if the user's entered credential matches with those in database
if(Auth::getInstance()->login($email, $pass))
{
//Uses the passed email to get permission level in 'User.class.php'
if(User::permGetter($email, $permission))
{
echo 'Permission ', $permission;
}
}
}
?>
But now i get an error. The error is this Notice: Undefined index: permission in /classes/User.class.php on line 56
So, I read up on it and it seemed like it should be emptied first, so I empty it in permRequest.php that's why I'm passing it too, but I still get this error after i emptied it?
However if i change
$row = $stmt->fetch(PDO::FETCH_NUM);
to
$row = $stmt->fetch(PDO::FETCH_ASSOC);
/* OR */
$row = $stmt->fetch(PDO::FETCH_BOTH);
I get no error but it simply says my email or password is incorrect, which it isn't I have double and triple checked it.
So I'm confused to which PDO::FETCH_ I should use. I have read this (Click here) and I would say that both ASSOC, BOTH and NUM would fit the purpose.
So why is one giving an error while the two other's simply fails the login?
Edit 2
Found the solution and i have written it as a Answer. Can't accept it for the next two days however.
I moved everything out of the User.class.php and moved it into permRequest.php. This solved my problem for some reason. So my code looks like this now
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL ^ E_NOTICE);
require_once("../includes/init.php");
$email = $_GET['email'];
$pass = $_GET['pass'];
if($email && $pass !== null)
{
if(Auth::getInstance()->login($email, $pass))
{
try
{
$db = Database::getInstance();
$stmt = $db->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute([':email' => $email]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$sub = $row['permission'];
echo 'Permission ', $sub;
}
catch (PDOException $exception)
{
error_log($exception->getMessage());
return false;
}
}
}
And I don't use the User.class.php for this function.
So my guess is something went wrong when returning $sub when it was in User.class.php
I am very new to php programming. I have written a sign up html file where the user enters his email and password. If the user has already registered, I am redirecting to sign-in screen and if the user is new use, I am persisting in the database. Now if the user enters wrong password, he will again be redirected to sign-in screen but this time I want to show a message on the screen, that the password entered is incorrect. The sign in screen should not display the message when the user navigates directly to the sign in screen.
The code snippet is shown below:
<?php
define('DB_HOST', 'hostname');
define('DB_NAME', 'db_name');
define('DB_USER','username');
define('DB_PASSWORD','password');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
function NewUser() {
$email = $_POST['email'];
$password = $_POST['password'];
$query = "INSERT INTO WebsiteUsers (email,pass) VALUES ('$email','$password')";
$data = mysql_query ($query)or die(mysql_error());
if($data) {
header('Location: reg-success.html');
}
}
function SignUp() {
if(!empty($_POST['email'])){
$emailQuery = mysql_query("SELECT * FROM WebsiteUsers WHERE email = '$_POST[email]'");
if($row = mysql_fetch_array($emailQuery)) {
$query = mysql_query("SELECT * FROM WebsiteUsers WHERE email = '$_POST[email]' AND pass = '$_POST[password]'");
if($row = mysql_fetch_array($query)) {
echo 'validated user. screen that is accessible to a registered user';
}else{
echo 'Redirect to the sign in screen with error message';
}
}else{
NewUser();
}
}
}
if(isset($_POST['submit']))
{
SignUp();
}
?>
Please let me know how to get this implementation using php
Here are a couple of classes that may help you prevent injection hacks plus get you going on how to do what you are trying to do in general. If you create classes for your tasks, it will be easier to re-use what your code elsewhere. I personally like the PDO method to connect and grab info from a DB (you will want to look up "binding" to help further prevent injection attacks), but this will help get the basics down. This is all very rough and you would want to expand out to create some error reporting and more usable features.
<?php
error_reporting(E_ALL);
// Create a simple DB engine
class DBEngine
{
protected $con;
// Create a default database element
public function __construct($host = '',$db = '',$user = '',$pass = '')
{
try {
$this->con = new PDO("mysql:host=$host;dbname=$db",$user,$pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
}
catch (Exception $e) {
return 0;
}
}
// Simple fetch and return method
public function Fetch($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
if($query->rowCount() > 0) {
$rows = $query->fetchAll();
}
return (isset($rows) && $rows !== 0 && !empty($rows))? $rows: 0;
}
// Simple write to db method
public function Write($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
}
}
// Your user controller class
class UserControl
{
public $_error;
protected $db;
// Save the database connection object for use in this class
public function __construct($db)
{
$this->_error = array();
$this->db = $db;
}
// Add user to DB
protected function Add()
{
$email = htmlentities($_POST['email'],ENT_QUOTES);
// Provided you have a php version that supports better encryption methods, use that
// but you should do at least a very basic password encryption.
$password = hash('sha512',$_POST['password']);
// Use our handy DBEngine writer method to write your sql
$this->db->Write("INSERT INTO WebsiteUsers (`email`,`pass`) VALUES ('$email','$password')");
}
// Fetch user from DB
protected function Fetch($_email = '')
{
$_email = htmlentities($_email,ENT_QUOTES);
$password = hash('sha512',$_POST['password']);
// Use our handy DBEngine fetcher method to check your db
$_user = $this->db->Fetch("SELECT * FROM WebsiteUsers WHERE email = '$_email' and password = '$password'");
// Return true if not 0
return ($_user !== 0)? 1:0;
}
// Simple fetch user or set user method
public function execute()
{
// Check that email is a valid format
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
// Save the true/false to error reporting
$this->_error['user']['in_db'] = $this->Fetch($_POST['email']);
// Asign short variable
$_check = $this->_error['user']['in_db'];
if($_check !== 1) {
// Add user if not in system
$this->Add();
// You'll want to expand your add feature to include error reporting
// This is just returning that it made it to this point
$this->_error['user']['add_db'] = 1;
}
else {
// Run some sort of login script
}
// Good email address
$this->_error['email']['validate'] = 1;
}
else
// Bad email address
$this->_error['email']['validate'] = 0;
}
}
// $_POST['submit'] = true;
// $_POST['email'] = 'jenkybad<script>email';
// $_POST['password'] = 'mypassword';
if(isset($_POST['submit'])) {
// Set up a db connection
$db = new DBEngine('hostname','dbname','dbuser','dbpass');
// Create instance of your user control
$_user = new UserControl($db);
// Execute instance
$_user->execute();
// Check for basic erroring
print_r($_user->_error);
} ?>
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
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.