Please help me I want my program to choose a site if it has not yet username then it will proceed it to ch_uname.php. Then if the login credentials have already username then it will be preceded to index_profile.php. Thank you in advance.
if(mysql_num_rows($runcreds)> 0 ) //checking log in forms
{
if(mysql_num_rows($run_uname)>=1 ) //if username has already avalaible(proceed)
{
$_SESSION['Email_add']=$email;
echo "<script>window.open('modules/index_profile.php','_self')</script>";
}
if(mysql_num_rows($run_uname)<1)//choouse username if has not yet username
{
$_SESSION['Email_add']=$email;
echo "<script>window.open('forms/ch_uname.php','_self')</script>";
//modules/index_profile.php
}
}
else
{
echo "<script>alert('Admin details are incorrect!')</script>";
}
}
Here is a basic demonstration (using a PDO connection) of what I think you are looking for? I am assuming some stuff here because you don't give enough info before your code snippet:
session_start();
// I will use PDO because I cannot bring myself to use mysql_ in this demonstration
// Initiate connection (assigning credentials assumed)
$con = new PDO("mysql:host=$mysqlDB;dbname=$mysqlTable", $mysqlUser, $mysqlPass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT));
if(isset($_POST['login'])) {
$username = trim($_POST['username']);
// Stop if empty
if(empty($username)) {
// You can echo or assign to a variable to echo down the page
echo 'Username cannot be empty';
return;
}
// Set up prepared statement
$query = $con->prepare("select Email_add,password from `users` where username = :username");
$query->execute(array(":username"=>$username));
// Loop through returned
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
// If the loop comes up blank, assign false (0)
$result = (isset($result) && !empty($result))? $result:0;
// If username exists
if($result != 0) {
// I am assuming you have some form of super secure hash method for passwords...
$password = bcrypt($_POST['password']);
// If passwords match, create session
if($result[0]['password'] == $password) {
$_SESSION['Email_add'] = $result[0]['Email_add'];
// You probably don't need javascript to redirect
header('Location: modules/index_profile.php');
exit;
}
else {
// Password doesn't match
// You can echo or assign to a variable to echo down the page
echo 'Invalid Username/Password';
}
}
// This would mean the username doesn't exist
else {
header('Location: forms/ch_uname.php');
exit;
}
}
Related
I am newbie in PHP.
I have simple authentication script. It works incorrect: user "test" (100% existing in table in DB) can not pass auth (error text - "User is not found!").
Use PHP7, MySQL, connection method is PDO.
Need some help please.
$data = $_POST;
// check if button is pressed
if (isset($data['enter-auth'])) {
// check fileds
$errors = array();
if (trim($data['login_auth']) == '' ) {
$errors[] = 'Enter login';
}
if (($data['password_auth']) == '' ) {
$errors[] = 'Enter password';
}
// If all fields are filled, save user's data in vars
$login = $data['login_auth'];
$password = password_hash($data['password_auth'], PASSWORD_DEFAULT);
// ... and look in table
try {
if (empty($errors)) {
// Check if login and password exists in table
$stmt = $pdo->prepare("SELECT count(*) FROM users WHERE login=? AND password=?");
$stmt->execute([$login, $password]);
$count = $stmt->fetchColumn();
// If login and pwd found in table counter will be > 0, so ...
if ($count > 0) {
// ... then we can check if password is correct
if (password_verify($data['password_auth'], $password)) {
// if entered and stored passwords match, user is welcome
$_SESSION['auth_name'] = $data['login_auth'];
echo '<div style="color: green;">Welcome, '.$_SESSION['auth_name'].';
echo 'Exit';
header('Location: /a/index.php');
} else {
$errors[] = 'Password is incorrect';
echo '<p id="message">Wrong password!</p>';
}
} else {
$errors[] = 'User not found';
echo '<p id="message">User is not found!</p>';
}
} else {
echo '<div style="color: red;">'.array_shift($errors).'</div>';
}
} catch(PDOException $e) {
echo $e->getMessage();
}
// close condition check if button is pressed
}
Notes:
I tryed debugging this script using var_dump.
If I use fetchAll() when searching in table, any entered ldin is accepted (even if there is no such user).
Used try/catch construction with debug aim, I've heard that in production it is deprecated because of security reason.
Found mistakes, rewrote the code according to https://phpdelusions.net/pdo_examples/password_hash
So, correct fragment is:
try {
if (empty($errors)) {
$stmt = $pdo->prepare("SELECT login, password FROM users WHERE login=?");
$stmt->execute([$login]);
$user = $stmt->fetch();
if ($user && password_verify($data['password_auth'], $user['password'])) {
$_SESSION['auth_name'] = $data['login_auth'];
echo '<div style="color: green;">Welcome, '.$_SESSION['auth_name'].';
echo 'Exit';
header('Location: /a/index.php');
} else {
$errors[] = 'Login or password error';
echo '<p id="message-auth">Login or password is incorrect!</p>';
}
} else {
echo '<div style="color: red;">'.array_shift($errors).'</div>';
}
} catch(PDOException $e) {
echo $e->getMessage();
}
I have a login system for a member/admin site. The login is working perfectly, but I want to verify the user and give error messages if it's not the correct user or password. So far, with what I have, it will not give any error messages although I'm not getting any errors either.
function error_message(){ $error = '';
$loginName = isset($_REQUEST['loginName']) ? $_REQUEST['loginName'] : "";
$password = isset($_REQUEST['password']) ? $_REQUEST['password'] : "";
{$results = connect($loginName);
$loginName === $results['email'];
$passwords = password_verify($password,$results['password']);
if(!$results) {$error = 'Username not found'; echo $error; header ('Location: home.php');} //if no records returned, set error to no username
else //if found {if ((isset($password)) !== (isset($passwords))) //check password, if matched log him in
{ $error = 'Password is wrong'; echo $error; header('Location: home.php');} //if not matched then set error message
}
}
if(isset($error)) {echo $error; }//if there is an error print it, this can be anywhere in the page
}
This is my connection and how it is logging in:
function connect($loginName) {
global $db;
$query = "SELECT email, level, password FROM members WHERE email ='$loginName'";
$result = $db->query($query);
$results = $result->fetch(PDO::FETCH_ASSOC);
return $results;
}
Login:
function login($loginName, $password) {
$results = connect($loginName);
if(!$results) {
header('Location: /tire/admin/home.php?err=1');
}
if ($loginName === $results['email'] && password_verify($password,$results['password'])) {
$_SESSION['loginName'] = $loginName;
if ($results['level'] === 'a') { // 1 == Administrator
$_SESSION['level'] = 'Administrator';
header('Location: /tire/admin/home.php');
} elseif ($results['level'] === 'm') { // 1 == Member
$_SESSION['level'] = 'Member';
header('Location: /tire/member/home.php');
exit;
}
}
header('Location: /tire/admin/home.php');
}
Wow, that's some nasty code we have here. Let's get started:
Let's first take a look in the connect function:
Gets the row where the email matches the loginName provided.
Return the array with the desired row.
That's correct.
Now let's take a look to the login function:
Retrieves the row where the email matches loginName.
If there is no row (email does not match any user), redirects to home.php of ¿ADMIN? with the variable $err = 1.
Recheck the email (what for?) and verify the password.
If password is correct, it checks permissions and redirects to the correspondent home.php.
Notice that if there is no matches for a permission, it redirects you to admin home.php.
Notice that if the password is incorrect, you do nothing.
I will improve this code:
function login($loginName, $password) {
$results = connect($loginName);
if(!$results) {
header('Location: /tire/error.php?code=1');
}
if (password_verify($password,$results['password'])) {
$_SESSION['loginName'] = $loginName;
if ($results['level'] === 'a') { // 1 == Administrator
$_SESSION['level'] = 'Administrator';
header('Location: /tire/admin/home.php');
} elseif ($results['level'] === 'm') { // 1 == Member
$_SESSION['level'] = 'Member';
header('Location: /tire/member/home.php');
exit;
}
} else {
header('Location: /tire/error.php?code=2');
}
}
And then in error.php (or whatever place you would like to show the errors, it's just an example):
switch($_GET['code']){
case 1:
$error = "Email invalid";
break;
case 2:
$error = "Password invalid";
break;
}
print $error
That being said, I will strongly recommend you to read about exceptions and implement the logic based on that. It's far more clean than the code above, but I didn't want to change your code so drastically.
See: http://php.net/manual/en/language.exceptions.php
There is definitely a logical flaw somewhere in this code, but I can't find it. The issue is that regardless of input, it echo's success (simulating a redirect to the main page). I don't know why. Here's the code:
$signIn = new UserService($dbuser, $dbpass, $dbhost, $dbname); //Create new class instance
$signIn->sec_session_start(); //Begin session
$_SESSION['token'] = $token; //Store token valualbe in super global variable
//***************************************************************************************//
//***************************************************************************************//
//Begin Login Functions
if(isset($_POST['username'], $_POST['password'],$_POST['siteToken'])) {
//Assign POST submissions to passable php variables
$username = $_POST['username'];
$password = $_POST['password'];
$passedToken = $_POST['siteToken'];
//Check Token Values (prevent CSRF attacks)
/*
if($passedToken != $_SESSION['token']) {
$error = "CSRF attack detected. Please close your browser and try again.";
$signIn->csrfAttackLog($username);
echo $error;
exit();
}
*/
//Test if both fields are not null
if($username == "" || $password = "")
{
$error = "Not all fields were entered<br />";
echo $error;
exit();
}
//Start login process
else
{
$success = $signIn->login($username, $password);
if ($success == true)
{ //Login Successful
echo "Success!"; //Direct to main page.
exit();
}
//Specific login failure determination
else
{
switch ($success){
case 1:
$error = "Your account has been locked.";
echo $error;
break;
case 2:
$error = "Invalid Username/Password (2)";
echo $error;
break;
case 3:
$error = "Invalid Username/Password";
echo $error;
break;
case 4:
$error = "Invalid Username/Password (3)";
echo $error;
break;
}
}
}
Here's the login class method:
public function login($username, $password)
{
//****************//
$this->username = $username;
$this->password = $password;
$user_Id = "";
$user = "";
$hashPassword = "";
$dbPassword = "";
$salt = "";
$userBrowser = "";
//**************// Local declerations
$this->connect(); //connect to database
if ($stmt = $this->dbh->prepare("SELECT UserId, Username, Pass, Salt FROM user WHERE Username = :param1 LIMIT 1")) //Prepared procedure
{
$stmt->bindParam(':param1', $this->username); //Bind $this->username to parameter
$stmt->execute(); //Execute the prepared query
if ($stmt->rowCount() == 1) //If the user exists
{
$this->user = $stmt->fetch(PDO::FETCH_ASSOC); //Grab the variables from the selected database row
$user_Id = $this->user['UserId']; //Transfer variables from array to local variables
$user = $this->user['Username'];
$dbPassword = $this->user['Pass'];
$salt = $this->user['Salt'];
if($user_Id = "")
echo "Why";
//Check if account has been locked
if($this->checkBrute($user_Id, $this->dbh) == true)
{
//Account is locked
return 1; //Used in userControl as a switch condition: Indicates a locked account
//Possibly send an email here
} else {
$hashPassword = hash('sha512', $this->password.$salt); //Hash the password with the unique salt
if($dbPassword == $hashPassword)
{ //Check if the password in the database matches the password the user submitted
//Password is correct!
$userBrowser = $_SERVER['HTTP_USER_AGENT']; // Get the user-agent string of the user
$_SESSION['p_id'] = $user_Id; //Store user id to global session variable
$_SESSION['userName'] = $user; //Store username to global session variable
$_SESSION['loginString'] = hash('sha512', $hashPassword.$userBrowser); //Hash the concentanation of the hashedpassword (password + salt) and userBrowser
//Login succesful!!!!!!
return true;
} else {
//Password is not correct
//Record this attempt in the database
$now = time();
$userIp = $_SERVER['REMOTE_ADDR'];
$insert = $this->dbh->query("INSERT INTO loginattempts (UserId, UserIp, EventTime) VALUES ('$user_Id', 'userIP', '$now')");
if($insert == false){
return 2; //Used in userControl as a switch condition: Indicated a failure to log failed login attempt
} else {
return 3; //Used in userControl as a switch condition: Indicates an inccorect password
}
}
}
}
else
{
//No user exists
return 4;
}
}
}
I know the SQL queries work: I've tested them outside this code. I don't understand why it keeps returning true. PHP hasn't thrown any exceptions or errors (and yes, I've read many times "don't write your own login functions. Use one that already works." This is not a public site. I'm just doing it for the heck of it). Any help is appreciated.
Your login code has various return codes - true if everything works, or numbers to indicate various error states. You're then checking the return value with:
if ($success == true)
PHP isn't strongly typed, so it will cast return values to a boolean for that comparison; and any non-0 integer will evaluate to true. To do a type check, as well as a value check, you need to use the strict comparison operator:
if ($success === true)
That will evaluate true if $success is both true and a boolean.
I have a login script where a page (index.php) can request the user to login (protect.php) however all that I see on index.php is a blank white screen with no source and no error messages. I should at least be seeing login.php to ask the user to log in. This script worked for a few minuets than just decided to stop working
This exact script has worked before in many other web apps that I have created however this one does not work. After hours of debugging I am still unable to find a solution to this problem.
index.php:
<?php
$allow=array('0','1','2');
require("users/protect.php");
?>
<script>window.location="/setup.php";</script>
protect.php:
<?php
session_start();
// --------------------------------THE VARIABLES---------------------------------- //
#include ("config.php");
// ----------------------------------THE CODE ------------------------------------ //
function clearance ($user_value, $pass_value, $level_value, $userlevel_value, $table_value, $column1, $column2, $path) { // Function to see if user can login
$check = mysql_query ("SELECT $userlevel_value FROM $table_value WHERE email='$user_value' AND password='$pass_value'"); // Query to see if user exists
$verify = mysql_num_rows ($check);
$get = mysql_fetch_array ($check);
if (count ($level_value) != 0) { // If the allow array contains userlevels
if (in_array ($get[$userlevel_value], $level_value) && $verify > 0) { // Search allow to see if userlevels match
$_SESSION['username'] = $user_value; // Register sessions
$_SESSION['password'] = sha1 ($pass_value); // sha1 password for extra security
$_SESSION['userlevel'] = $get[$userlevel_value];
}
} else {
if ($verify == 0) { // If attempt fails then redirect to login page
$_SESSION = array();
$error = "Sorry but your login details were incorrect";
#include ("login.php");
exit;
}
if ($verify > 0) { // If attempt is good then register the user
$_SESSION['username'] = $user_value;
$_SESSION['password'] = sha1 ($pass_value);
}
}
}
function protect ($level_value, $password_value, $userlevel_value, $table_value, $column1, $path) { // Function to keep pages secure
if (!isset ($_SESSION['username'])) { // If session doesn't exist then get user to login
if (isset ($_POST['username']) && isset ($_POST['password'])) {
$error = "Sorry but your login details were incorrect";
}
$_SESSION = array();
#include ("login.php");
exit;
} else { // If user is logged in check to see if session is valid and that they have the required userlevel
$check = mysql_query ("SELECT $password_value, $userlevel_value FROM $table_value WHERE $column1='$_SESSION[username]'"); // Query to see if user exists
$verify = mysql_num_rows ($check);
$get = mysql_fetch_array ($check);
if ($verify == 0) {
$_SESSION = array();
$error = "Sorry but your login details were incorrect";
#include ("login.php");
exit;
}
if ($verify > 0 && count ($level_value) != 0) {
if (!in_array ($get[$userlevel_value], $level_value)) { // Check to see if the users userlevel allows them to view the page
$error = "Sorry but your login details were incorrect";
#include ("login.php");
exit; // Ensure no other data is sent
}
}
}
}
if (isset ($_POST['username']) && isset ($_POST['password'])) { // If user submits login information then validate it
clearance ($_POST['username'], $_POST['password'], $allow, $userlevel, $table, $username, $password, $path);
}
protect ($allow, $password, $userlevel, $table, $username, $path);
mysql_close ($link); // Close the database connection for security reasons
// -----------------------------------THE END ------------------------------------ //
?>
Am using this code for authenticating my URL.
Its working fine in my localhost but when I load onto the server(goDaddy), its repeatedly asking for the username and password.
I wanna take control of those username and password fields and connect them to my database.
For that am using code like this:
$conid = mysql_connect("localhost", "root", "");
if(!$conid) {
die("sorry unable to establish a connection".mysql_error());
}
echo "connected succesfully<br>";
mysql_select_db("passurl", $conid);
$rr = mysql_query("select password from validate where username='$user' ");
while($row = mysql_fetch_array($rr)) {
$x = $row['password'];
}
if($x == $password) {
//take into the website
}
so when the username & password are entered by user, on successful authentication it takes into that page.
Am using PHP-MYSQL, as I've preliminary knowledge in it, am newbie to programming.
kindly help me in fixing the above two issues with the suitable tested code.
Edit:
Issue one is working locally and am using the same code as provided in the link. Issue two is am trying to retrieve those username and password fields from my local database so as login can be granted, on my localhost(if it works on later stage I'll take the database to online).
Edit-2:
ty.php contains code like
<?php
$auth_realm = 'Access restricted';
require_once 'auth.php';
echo "You've logged in as {$_SESSION['username']}<br>";
echo '<p>LogOut</p>'
?>
<center><h1>now you see the protected content</h1></center>
and auth.php contains
<?php
$_user_ = 'test';
$_password_ = 'test';
session_start();
$url_action = (empty($_REQUEST['action'])) ? 'logIn' : $_REQUEST['action'];
$auth_realm = (isset($auth_realm)) ? $auth_realm : '';
if (isset($url_action)) {
if (is_callable($url_action)) {
call_user_func($url_action);
} else {
echo 'Function does not exist, request terminated';
};
};
function logIn() {
global $auth_realm;
if (!isset($_SESSION['username'])) {
if (!isset($_SESSION['login'])) {
$_SESSION['login'] = TRUE;
header('WWW-Authenticate: Basic realm="'.$auth_realm.'"');
header('HTTP/1.0 401 Unauthorized');
echo 'You must enter a valid login and password';
echo '<p>Try again</p>';
exit;
} else {
$user = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : '';
$password = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : '';
$result = authenticate($user, $password);
if ($result == 0) {
$_SESSION['username'] = $user;
} else {
session_unset($_SESSION['login']);
errMes($result);
echo '<p>Try again</p>';
exit;
};
};
};
}
function authenticate($user, $password) {
global $_user_;
global $_password_;
if (($user == $_user_)&&($password == $_password_)) { return 0; }
else { return 1; };
}
function errMes($errno) {
switch ($errno) {
case 0:
break;
case 1:
echo 'The username or password you entered is incorrect';
break;
default:
echo 'Unknown error';
};
}
function logOut() {
session_destroy();
if (isset($_SESSION['username'])) {
session_unset($_SESSION['username']);
echo "You've successfully logged out<br>";
echo '<p>LogIn</p>';
} else {
header("Location: ?action=logIn", TRUE, 301);
};
if (isset($_SESSION['login'])) { session_unset($_SESSION['login']); };
exit;
}
?>
so once we hit ty.php it asks for username and password and on successful validation it shows the protected down. All this is working fine in localhost but its not working on the server.
Can someone pls help me out of this
Thanks in advance :)
You need to create a database username and password on your goDaddy hosting service, root and empty password can't get you through. The root is the default username for your local server and you didn't set any password for it, hence "" works for you as password. You must set up a username and a password on your remote server for it to work.
mysql_connect("your-host-server", "a-username", "a-secret-password"); // Password can't be empty and username can't be root, hope you understand
You are looping over the paswords, but only checking a single value after your loop.
Your code is:
while($row = mysql_fetch_array($rr)) {
$x = $row['password'];
}
if($x == $password) {
//take into the website
}
It should be:
while($row = mysql_fetch_array($rr)) {
if ($password == $row['password']) {
// take into the website
}
}