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?
Related
I am currently making a login system with multilevel. I have table 'admin' includes 'level' field. I want to make admin redirect to page based on 'level' field on 'admin' table. If level is 1 will redirect to SIPP-Litbang/admin.php page, then if level is 2 will redirect to SIPP-Litbang/admin-pp-sipp-litbang.php.
The first step, I make method on class.admin.php page, here are the codes:
public function login($email, $password)
{
try {
$stmt = $this->conn->prepare("SELECT * FROM admin WHERE email_admin = :email AND pass_admin = MD5(:pass)
LIMIT 1");
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':pass', $password,PDO::PARAM_STR);
$stmt->execute();
$adminRow = $stmt->fetch();
if ($stmt->rowCount() == 1) {
$_SESSION['is_logged_in'] = true;
$_SESSION['adminSession'] = $adminRow['id_admin'];
$_SESSION['levelSession'] = $adminRow['level'];
return true;
} else {
return false;
}
}
catch(PDOException $e)
{
return FALSE;
}
}
public function cekSession(){
if (isset($_SESSION['adminSession'])&&$_SESSION['levelSession']==1) {
header('Location: \SIPP-Litbang\admin.php');
return true;
}
elseif (isset($_SESSION['adminSession'])&&$_SESSION['levelSession']==2) {
header('Location: \SIPP-Litbang\admin-pp-sipp-litbang.php');
return true;
}
}
And loginadmin.php page:
<?php
session_start();
include_once ('class.admin.php');
$admin = new Admin();
if (isset($_POST['login'])){
$user = trim(strip_tags($_POST['email']));
$pass = trim(strip_tags($_POST['pass']));
if ($admin->login($user, $pass)){
}
else {
echo "GAGAL LOGIN! Email atau Password Salah";
}
}
Login process has worked, for example admin with level 2 will header to SIPP-Litbang/admin-pp-sipp-litbang?modul=beranda. Then I want to display details of admin level 2, here are the codes from admin-pp-sipp-litbang.php page:
<?php
session_start();
require_once 'class.admin.php';
$user = new ADMIN();
$admin_level = isset($_SESSION['levelSession']);
$admin_id = isset($_SESSION['adminSession']);
$stmt = $user->runQuery("SELECT * FROM admin WHERE id_admin=:admin_id AND level=:level");
$stmt->bindParam(":admin_id",$admin_id);
$stmt->bindParam(":level",$admin_level);
$stmt->execute();
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
?>
I try to echo the name of admin with level 2, but It just displayed name of admin with level 1 . Am I missing something?
$admin_level = isset($_SESSION['levelSession']);
$admin_id = isset($_SESSION['adminSession']);
isset() returns true\false; in your case 'true' is being cast to 1, which explains the results you see.
what i assume you want here is::
if(isset($_SESSION['levelSession'])){
$admin_level =$_SESSION['levelSession'];
}
if(isset($_SESSION['adminSession'])){
$admin_id = $_SESSION['adminSession'];
}
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;
}
}
Hi guys i have loging via email , and i want to add login via email.
When i add (login=:login OR) in sql query, i got bug you can login by any password.
Here some code :
public function login($login,$upass)
{
try {
$stmt = $this->conn->prepare("SELECT * FROM Klient WHERE login=:login OR email=:login LIMIT 1");
$stmt->execute(array(':login' => $login));
$userRow = $stmt->fetch(PDO::FETCH_ASSOC);
if ($stmt->rowCount() == 1) {
if ($userRow['userStatus'] == "Y") {
if ($userRow['haslo'] = $upass) {
$_SESSION['userSession'] = $userRow['idKlient'];
return true;
} else {
header("Location: index.php?error");
exit;
}
} else {
header("Location: index.php?inactive");
exit;
}
} else {
header("Location: index.php?error");
exit;
}
} catch (PDOException $ex) {
echo $ex->getMessage();
}
}
EDIT:
i'm trying to add password_hash(), but when i login in my website is going down.
i tried to add password hash but my website is going down when i login in.
public function login($login, $upass)
{
try {
$stmt = $this->conn->prepare("SELECT * FROM Klient WHERE login=:user_login OR email=:user_login");
$stmt->execute(array(":user_login" => $login));
$userRow = $stmt->fetch(PDO::FETCH_ASSOC);
if ($stmt->rowCount() == 1) {
if ($userRow['userStatus'] == "Y") {
if ( password_verify($upass, $userRow['haslo'])) {
$_SESSION['userSession'] = $userRow['idKlient'];
return true;
} else {
header("Location: index.php?error");
exit;
}
} else {
header("Location: index.php?inactive");
exit;
}
} else {
header("Location: index.php?error");
exit;
}
} catch (PDOException $ex) {
echo $ex->getMessage();
}
}
You need to change here add param for email also
$stmt->execute(array(':login' => $login,':email' => $login));
if ($userRow['haslo'] = $upass) {
You're giving $userRow['haslo'] the password, you need to check it with ===
And please, use hashing not plain-text, check password_hash
You could try something like:
$stmt = $this->conn->prepare("SELECT * FROM Klient WHERE login = :login: OR email = :email: LIMIT 1")
$stmt->execute(array('login' => $login, 'email' => $upass));
And my suggestion is that you check variables before exec, something like:
if(isset($login) && isset($upass)) {
...
}
Hope this helps, cheers!
Do not try to use the same named parameter twice in a single SQL statement, for example
<?php
$sql = 'SELECT * FROM some_table WHERE some_value > :value OR some_value < :value';
$stmt = $dbh->prepare($sql);
$stmt->execute( array( ':value' => 3 ) );
?>
...this will return no rows and no error -- you must use each parameter once and only once. Apparently this is expected behavior (according to this bug report: http://bugs.php.net/bug.php?id=33886) because of portability issues.
Our php Side full work in my localserver (Xamp-apach-5.5.6)
but hosting side no work(apach-5.2.17)
Please help me.
public function login($username,$password)
{
session_start();
if($username==!NULL AND $password==!NULL)
{
global $pdo;
$password=md5($password);
$query = $pdo->prepare("SELECT * FROM employee_list WHERE username='$username' AND userpass='$password'");
$query->execute();
$row=$query->rowCount();
if($row==0)
{
$this->massage->loginmass("<span class='text-danger'>YOUR USERNAME AND PASSWORD NO MATCH.</span>");
}
else
{
$result = $query->fetch();
if($result['active_enactive']=="Active")
{
$_SESSION['mafizusernamerahman'] = $result['username'];
$_SESSION['mafizuserpassrahman'] =$result['userpass'];
$_SESSION['mafizaccess_permissionrahman'] = $result['access_permission'];
$_SESSION['mafizactive_enactiverahman'] = $result['active_enactive'];
$_SESSION['mafiznamerahman'] = $result['name'];
$_SESSION['mafizemployment_idrahman'] = $result['employment_id'];
$_SESSION['mafizfather_namerahman'] = $result['father_name'];
$_SESSION['developer'] = "Mafizur";
if($_SESSION['mafizaccess_permissionrahman']=="Admin")
header("location:all-employee.php");
elseif($_SESSION['mafizaccess_permissionrahman']=="User")
{
if (empty($result['defaltpass'])) {
header("location:user-profile.php");
}
else
header("location:defaltchange-password.php");
}
}
else
$this->massage->loginmass("<span class='text-danger'>YOUR ACCOUNT SUSPEND.</span>");
}
}
else
$this->massage->loginmass("<span class='text-danger'>PLEASE FILL UP YOURUSER NAME AND PASSWORD.</span>");
}
You need to be careful while using relative URLs in Location redirects.
So, it will be better if you print absolute URLs in the headers instead of relative URLs.
https://en.wikipedia.org/wiki/HTTP_location
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.