I doing simple log in system. Username and passwords are saved in txt file (array format).
When I m log in I got "Fatal error: Maximum execution time of 30 seconds exceeded". here is my code. Thank for any hint.
$clean = array();
if(isset($_POST["submit"])){
if(!empty($_POST['username']) && !empty($_POST['password'])) {
$user = isset($_POST['username']);
$pass = isset($_POST['password']);
$toread = fopen('filewriting.txt','r');
while(!feof($toread))
{
$username = isset($clean['username']);
$password = isset($clean['password']);
}
if($user == $username && $pass == $password)
{
$_SESSION['sess_user']=$user;
/* Redirect browser */
header("Location: page2.php");
}
} else {
echo "Invalid username or password!";
}
} else {
echo "All fields are required!";
}
The below lines are not correct
$user = isset($_POST['username']);
$pass = isset($_POST['password']);
isset() returns true or false and hence the variables will be set to true or false
http://php.net/manual/en/function.isset.php
You have same
$username = isset($clean['username']);
$password = isset($clean['password']);
And values of $user and $pass is setting as true or false in all cases and further down the line its failing. Correct these first.
Related
This question already has answers here:
PHP: check if any posted vars are empty - form: all fields required
(9 answers)
Closed 2 years ago.
I have a select action and I want to check if the fields username and password are both empty. My issue is that if one of them is empty echo msg pops but, but if both are empty it goes straight to the next page.
<?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();
if ($_POST['submit']) {
include_once("connexion.php");
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$sql = "SELECT id, username, password FROM users where username = '$username' and password ='$password'";
$query = mysqli_query($dbCon,$sql);
if ($query) {
$row = mysqli_fetch_row($query);
$userId = $row[0];
$dbUsername = $row[1];
$dbPassword = $row[2];
}
if ($username == $dbUsername && $password == $dbPassword) {
$_SESSION['username'] = $username;
$_SESSION['id'] = $userId;
header('location:../index-2.php');
} else {
echo "wrong username or password";
}
}
?>
Edit : I used Dharmesh Goswami solution :
if ($username == $dbUsername && !empty($username) && $password == $dbPassword && empty($password) )
It works like a charm ! Thank you.
Just check in if condition that both are not empty.
if ($username == $dbUsername && !empty($username) && $password == $dbPassword && !empty($password) )
{
$_SESSION['username'] = $username;
$_SESSION['id'] = $userId;
header('location:../index-2.php');
}else
{
echo "wrong username or password";
}
You can apply empty() condition right after form posted.
if (isset($_POST['submit'])) {
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$username = trim($username);
$password = trim($password);
if (empty($username) || empty($password)) {
// Print your error.
}
}
|| will check if any one or both the fields are empty.
You can use the empty() function to check if input string is empty or not. To check if one of the fields is empty, you could use the XOR(^) operator. Failing which, the control should pass to AND(&&) operator which checks if both the fields are empty. If that fails too, you could say that none of the fields is empty. Hope this helps.
if(isset($_POST['submit']){
if(empty($_POST['username'] ^ empty($_POST['password']){
// code here to perform task if one field is left empty
} else if(empty($POST['username'] && empty($_POST['password']){
// code here to perform task if both fields are empty
} else {
// code here to perform task when none of the fields is empty
}
}
You do like that
extract($_POST);
if($_POST['submit']) :
if($Username == "" && $Password == ""):
$_SESSION['error'] = "Can't Be Blanked User Name Or Password";
endif;
endif;
I would suggest using mysqli_real_escape_string
if(!empty($_POST['username'])) $username = mysqli_real_escape_string($dbCon, $_POST['username']);
same for password
$sql = 'SELECT id, username, password FROM use...';
$result = $dbCon->query($sql);
$count = $conn->affected_rows;
if ($count == 1)
{
$_SESSION['username'] = $username;
$_SESSION['id'] = $userId;
header('location:../index-2.php');
}else echo "wrong username or password";
also, wouldn't save username in sessions. Look up more on securing session.
I'm working on a log in form that users a text file (users.txt) to validate username/password against. I cannot use MYSQL for this.
The text file records are in this format:
user one:user1#email.com:user1:password1
user two:user2#email.com:user2:password2
If it validate just the USERNAME only, then it successfully checks the user: if ($currUser == $userUsername) {$valid = true; break;}BUT if I then try to validate both username and password I get the wrong result.($currUser == $userUsername && $currPass == $userPass) {$valid = true; break;} Results in "Invalid username or password"
I can't figure out what I'm doing wrong? When I echo the username and passwords they are a match!!!
SCRIPT:
if(isset($_POST['submit'])){
$form_is_submitted = true;
//FORM PROCESSING
if(isset($_POST['userName']) && isset($_POST['password'])) {
$currUser = $_POST['userName'];
$currPass = $_POST['password'];
$valid = false;//flag
while (!feof($fileHandle)) {
$userRow = fgets($fileHandle);
$userDetails = explode(':', $userRow);
if (!isset($userDetails[2])) {
$userDetails[2] = null;
}
if (!isset($userDetails[3])) {
$userDetails[3] = null;
}
$userUsername = $userDetails[2];
$userPass = $userDetails[3];
if ($currUser == $userUsername /*&& $currPass == $userPass*/) {
$valid = true;
//break;
}
}
if ($valid) {
echo "<br> $userUsername logged in sucessfully<br>";
} else {
echo "<br>Invalid user name or password<br>";
//FOR DEGUGGING ONLY!
echo $currUser . $userUsername;
echo $currPass . $userPass;
echo $_POST['password'];
echo $_POST['userName'];
}
} else {
$errors_detected = true;
$errors['not set'] = "Please enter username and password";
}
}
the fgets() function returns a line INCLUDING the linefeed \n (and the carriage return \r if its there). that means you have to remove those.
just change this:
$userPass = $userDetails[3];
to this:
$userPass = trim($userDetails[3]);
and it should work
I am using PHPASS to store password encrypted and compare when login.
here is the code
ob_start();
$userName = $password = "";
$userNameErr = $passwordErr = $loginErr = "";
$hasher = new PasswordHash(8, false);
if (isset($_POST['subEmployee'])) {
if (empty($_POST['user_name'])) {
$userNameErr = "User name is required";
} else {
$userName = check_input($_POST['user_name']);
if (!preg_match("/^[0-9_a-zA-Z]*$/", $userName)) {
$userNameErr = "Only letters, numbers and '_' allowed";
}
}
if (empty($_POST['password'])) {
$passwordErr = "Password is required";
}else{
$password = check_input($_POST['password']);
}
$active = 1;
$loginUser = $db->prepare("SELECT password FROM users WHERE user_name=? AND activity=?");
$loginUser->bind_param('si', $userName, $active);
if ($loginUser->execute()) {
$results = $loginUser->get_result();
if ($results->num_rows == 1) {
$row = $results->fetch_object();
$stored_hash = "*";
$stored_hash = $row->password;
$check = $hasher->CheckPassword($password, $stored_hash);
if ($check) {
$_SESSION['name'] = $row->first_name;
$_SESSION['userId'] = $row->id;
$_SESSION['user'] = 1;
print_r($_SESSION);
header("Location:?pid=4");
} elseif (!empty($_POST['user_name']) && !empty($_POST['password'])) {
$loginErr = "'Invalid Login Information'";
}
}
}
}
so far it always give the same message 'Invalid Login Information' I have made the registration form that store my password like this.
$hasher = new PasswordHash(8, false);
$hash = md5(rand(0, 1000));
if (empty($_POST['password'])) {
$error ['passwordErr'] = "Password is required";
} elseif (strlen($_POST['password']) < 8) {
$error ['passwordErr'] = "<span class='notAllowed'>Chose password with at last eight characters</span>";
} elseif (strlen($_POST['password']) > 72) {
$error ['passwordErr'] = "<span class='notAllowed'>Password max 72 characters</span>";
} elseif ($_POST['password'] !== $_POST['confirm']) {
$error ['passwordErr'] = "Password don't matching";
} else {
$password = $hasher->HashPassword($password);
}
when I checked my database the password seems hashed to me and the user name is there and everything is alright
but still getting this message as 'Invalid Login Information'.
does this two lines is right
$loginUser = $db->prepare("SELECT password FROM users WHERE user_name=? AND activity=?");
$loginUser->bind_param('si', $userName, $active);
does the login code OK.
I try this too
Update
I updated my code
if (isset($_POST['subEmployee'])) {
$error=array();
$hash_cost_log2 = 8;
$hash_portable = FALSE;
$hasher = new PasswordHash($hash_cost_log2, $hash_portable);
if (empty($_POST['user_name'])) {
$userNameErr = "User name is required";
} else {
$userName = check_input($_POST['user_name']);
if (!preg_match("/^[0-9_a-zA-Z]*$/", $userName)) {
$userNameErr = "Only letters, numbers and '_' allowed";
}
}
if (empty($_POST['password'])) {
$passwordErr = "Password is required";
} else {
$password = $_POST['password'];
}
$active = 1;
$loginUser = $db->prepare("SELECT password FROM hired_person_info WHERE user_name=? AND activity=?");
$loginUser->bind_param('si', $userName, $active);
if ($loginUser->execute()) {
$results = $loginUser->get_result();
if ($results->num_rows == 1) {
$row = $results->fetch_object();
$stored_hash = "*";
$stored_hash = $row->password;
$check = $hasher->CheckPassword($password, $stored_hash);
if ($check) {
$_SESSION['name'] = $row->first_name;
$_SESSION['userId'] = $row->id;
$_SESSION['user'] = 1;
print_r($_SESSION);
header("Location:?pid=4");
} elseif (!empty($_POST['user_name']) && !empty($_POST['password'])) {
$loginErr = "'Invalid Login Information'";
}
} else {
$loginErr = "'We didn't find any users'";
}
}
}
add this from the manual of PHPass
$hash_cost_log2 = 8;
$hash_portable = FALSE;
$hasher = new PasswordHash($hash_cost_log2, $hash_portable);
still no luck can somebody tell me where am mistaking here
Edit
this is my check_input() code
function check_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
and I am using PHP 5.3.29
Thanks
These are some points i would check:
1) In your registration handler you check directly the POST variable, but for hashing you take a variable $password, i would access the input always in the same way, for example:
$password = $hasher->HashPassword($_POST['password']);
2) The function check_input() is not recommended for passwords, since you calculate a hash-value and this hash-value is "safe" anyway. Even for other user input, one should validate it as you did, but escaping should be done as late as possible, and only for the particular output. So the function htmlspecialchars() should not be called for user input, but always before outputting to HTML.
3) In your login handler you access the password once with the POST variable and once with the variable $password. The variable $password is set only in an if statement, so if the input is empty you fill the error but you continue with an uninitialized $password variable. Either fill the variable just at the beginning, or always use the POST variable.
4) Since you are using PHP 5.3.29 you can use the new function password_hash() with the compatibility pack. I do not think that the PHPass library is the problem here, nevertheless here is an example for the new function.
// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);
// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);
5) Another often made mistake is, that the database field for storing the hash-value is too short, it needs a length of varchar(60). Maybe you could provide one of your password-hashes (of course only an example)?
This library requires PHP >= 5.3.7 OR a version that has the $2y fix backported into it (such as RedHat provides).
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 the following code designed to begin a session and store username/password data, and if nothing is submitted, or no session data stored, redirect to a fail page.
session_start();
if(isset($_POST['username']) || isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
}
if(isset($_SESSION['username']) || isset($_SESSION['password'])){
$navbar = "1";
$logindisplay = "0";
$username = $_SESSION['username'];
$password = $_SESSION['password'];
} else {
header('Location:http://website.com/fail.php');
}
$authed = auth($username, $password);
if( $authed == "0" ){
header('Location:http://website.com/fail.php');
}
Its not working the way it should and is redirecting me to fail even though i submitted my info and stored it in the session. Am i doing something wrong?
NOTE the authed function worked fine before i added the session code.
what about using this to setup session
session_start();
if( isset($_POST['username']) && isset($_POST['password']) )
{
if( auth($_POST['username'], $_POST['password']) )
{
// auth okay, setup session
$_SESSION['user'] = $_POST['username'];
// redirect to required page
header( "Location: index.php" );
} else {
// didn't auth go back to loginform
header( "Location: loginform.html" );
}
} else {
// username and password not given so go back to login
header( "Location: loginform.html" );
}
and at the top of each "secure" page use this code:
session_start();
session_regenerate_id();
if(!isset($_SESSION['user'])) // if there is no valid session
{
header("Location: loginform.html");
}
this keeps a very small amount of code at the top of each page instead of running the full auth at the top of every page. To logout of the session:
session_start();
unset($_SESSION['user']);
session_destroy();
header("Location: loginform.html");
First, don't store the password in the session. It's a bad thing. Second, don't store the username in the session until after you have authenticated.
Try the following:
<?php
session_start();
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$authed = auth($username, $password);
if (! $authed) {
header('Location: http://website.com/fail.php');
} else {
$_SESSION['username'] = $username;
}
}
if (isset($_SESSION['username'])) {
$navbar = 1;
$logindisplay = 0;
} else {
header ('Location: http://website.com/fail.php');
}
Just some random points, even though they may not actually pertain to the problem:
Don't store the password in plaintext in the session. Only evaluate if the password is okay, then store loggedIn = true or something like that in the session.
Check if the password and the username are $_POSTed, not || (or).
Don't pass password and username back and forth between $password and $_SESSION['password']. Decide on one place to keep the data and leave it there.
Did you check if you can store anything at all in the session? Cookies okay etc...?
To greatly simplify your code, isn't this all you need to do?
if (isset($_POST['username'] && isset($_POST['password'])) {
if (auth($_POST['username'], $_POST['password'])) {
$_SESSION['user'] = /* userid or name or token or something */;
header(/* to next page */);
} else {
// display "User credentials incorrect", stay on login form
}
} else {
// optionally: display "please fill out all fields"
}
Here are a few other things, which may or may not help you, by the way :
Do you have error_reporting on ? (see also)
Do you have display_errors on ?
Is session_start the first thing you are doing in your page ? There must be nothing output before
Are the cookies created on the client-side ?
header Location indicates the browser it has to go to another page ; it doesn't stop the execution of the PHP script. You might want to (almost always anyway) add "exit" after it.
Headers are not function calls. They put a directive into the HTTP headers, and the last one to execute is the one which will be processed. So let say if you have something like this
if ($bAuthed)
{
header("location: login.php");
}
// error case
header("location: error-login.php");
You will always be redirected to error-login.php no matter what happens. Headers are not function calls!
The solution to my specific problem above
session_start();
if(isset($_POST['username']) || isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
}
if(isset($_SESSION['username']) || isset($_SESSION['password'])){
$navbar = "1";
$logindisplay = "0";
$username = $_SESSION['username'];
$password = $_SESSION['password'];
$authed = auth($username, $password);
if( $authed == "0" ){
header('Location:http://website.com/fail.php');
}
} else {
header('Location:http://website.com/fail.php');
}
Don't use else section in second if statement.
session_start();
if(isset($_POST['username']) || isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
}
if(isset($_SESSION['username']) || isset($_SESSION['password'])){
$navbar = "1";
$logindisplay = "0";
$username = $_SESSION['username'];
$password = $_SESSION['password'];
}
$authed = auth($username, $password);
if( $authed == "0" ){
header('Location:http://website.com/fail.php');
}