Verifying if given Username already exist in a txt file, using php - php

I have an assignment where i need to create a register page and verify if a user doesn't exist already in a txt file. I found some answers online and tried to apply them but doesn't seem to work for me. everything works except the part that he needs to verify.
here is my code: this is my code
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage ="";
$link_Create = "CreateAnAccount.php";
$Username = $_POST['userName'];
$password = $_POST['Password'];
if(empty($_POST['userName']))
{
echo "<li>You forget to enter a UserName</li><a href='".$link_Create."'>Start again</a>";
header("Location:PopUp.html");
exit;
}
if(empty($_POST['Password']))
{
echo "<li>You forget to enter a Password</li><a href='".$link_Create."'>Start again</a>";
header("Location:PopUp.html");
exit;
}
if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!##$%]{4,24}$/', $password))
{
echo "<li>Your Password input was wrong, please notice Paswword most be at least 4 characters long, have at least one letter and at least one digit. </li><a href='".$link_Create."'>Start again</a>";
header("Location:PopUp.html");
exit;
}
if(empty($errorMessage)){
$userlist = fopen("login.txt","r");
$success = true;
foreach ($userlist as $user) {
$user_details = explode('|', $user);
if ($user_details[0] == $Username) {
$success = false;
break;
}
}
fclose($userlist);
if ($success==true) {
$writer = fopen("login.txt", "a") or die("Unable to open file.");
fwrite($writer,$Username."|");
fwrite($writer,$password."\n");
fclose($writer);
echo "<br>You have been logged in. <br>";
header("Location:PopUp.html");
exit;
}
else {
echo "<li>This User Name already exist!</li><a href='".$link_Create."'>Start again</a>";
header("Location:PopUp.html");
exit;
}
}
}
?>
Let me know if there is the need of my html code but i don't think it has any effect on the issue.
Thank you very much I appreciate the help.

You have problem with iterating over resource which return fopen function
$userlist = fopen("login.txt","r");
$success = true;
foreach ($userlist as $user) {
$user_details = explode('|', $user);
if ($user_details[0] == $Username) {
$success = false;
break;
}
}
Try to replace it with this iterating over each line of userlist file:
$file = new \SplFileObject("login.txt");
// Loop until we reach the end of the file
while (!$file->eof()) {
$user = $file->fgets();
$user_details = explode('|', $user);
if ($user_details[0] == $Username) {
$success = false;
break;
}
}

Related

PHP if statement execute both if and ELSE if

as you can see by my code, if the variable $uname and $password are not equal to the values they should be in the text file im reading from, it should print and error. Unfortunately it does not. When the values are correct however it prints both the success message and the failure message on the same line instead of just the success message. I am sure I'm overlooking something very simple but still need to ask. The code is below. Thanks in advance!
<?php
if (isset($_POST['submit'])) {
$uname = $_POST['uname'];
$pass = $_POST['pass'];
$password = sha1($pass);
$filename = "pass.txt";
$contents = file($filename, FILE_IGNORE_NEW_LINES );
foreach ($contents as $value) {
$details = explode(':', $value);
if ($uname == $details[0]&& $password == $details[1]) {
echo" Welcome, Access Has Been Granted!";
} else {
echo "Please Check User Name and Or Password";
exit;
}
}
}
?>
Your password check is inside a loop, and that loop will repeat for every line in pass.txt -- even if a line is totally empty. You should modify your code so that a $password_success variable defaults to FALSE and is only set to true if a valid, matching user/password line exists. Then, outside the loop, check $password_success exactly once.
<?php
if (isset($_POST['submit'])) {
$uname = $_POST['uname'];
$pass = $_POST['pass'];
$password = sha1($pass);
$filename = "pass.txt";
$contents = file($filename, FILE_IGNORE_NEW_LINES );
$password_success = FALSE;
foreach ($contents as $value) {
$details = explode(':', $value);
if (sizeof($details) == 2) {
if ($uname == $details[0]&& $password == $details[1]) {
$password_success = TRUE;
break; // this will stop our password file looping
}
} else {
// skip invalid password file line
}
}
if ($password_success) {
echo" Welcome, Access Has Been Granted!";
exit;
} else {
echo "Please Check User Name and Or Password";
exit;
}
}

Why is my PHP 7.1 script saying that login credentials are incorrect even if they are correct?

I am making a login script in PHP and almost everything seems to work fine, if I make an account, it works, but if I try to sign in with the credentials of that account.
I get the alert that the credentials are wrong.
I saved also the password here in a text file and I agree with you that it's stupid, but it is for a school assignment so it won't matter.
Personally I think that there's something wrong with my login script, but I'm not sure. (And because it's for school I need to stick as close as possible to the code layout.)
Here's the code:
signup.php
<?php
if (isset($_POST["submit"])) {
$username = htmlspecialchars($_POST["usrname"]);
$email = htmlspecialchars($_POST["mail"]);
$password = htmlspecialchars($_POST["pass"]);
$passwordConfirm = htmlspecialchars($_POST["passconfirm"]);
trim($username);
trim($email);
function checkUserData() {
// things to do .A
// things to do .B
// things to do .C
// check if passwords are the same #### this doesn't seem to work correct. Why not?
if ($password != $passwordConfirm) {
echo "<script>alert('passwords are not matching');
location.href='signup.html';
</script>";
return false;
}
elseif ($password == $passwordConfirm) {
return true;
}
}
if (checkUserData()) {
// saving user
$file = fopen("users.txt", "ab");
if (!$file) {
echo "Couldn't open file!";
}
$profile = $username . "*" . $password . "*" . $email . "\n";
fwrite($file, $profile, strlen($profile));
if (fclose($file)) {
echo "<script>alert('Account is created');
location.href='login.html';
</script>";
}
elseif (!fclose($file)) {
echo "Couldn't close file!";
} else {
echo "An error ocurred while creating an account, try again later.";
}
}
}
?>
login.php
<?php
$username = htmlspecialchars($_POST["usrname"]);
$password = htmlspecialchars($_POST["pass"]);
$file = fopen("users.txt", "r");
if (!$file) {
echo "Couldn't open file!";
}
while (!feof($file)) {
$account = fgets($file);
$account = explode("*", $account);
if ($account[1] == $username && $account[2] == $password) {
session_start();
$_SESSION["USER"] = $username;
$_SESSION["STATUS"] = 1;
$_SESSION["ID"] = $_COOKIE["PHPSESSID"];
echo "<script>
alert('You are now logged in as ".$_SESSION['USER'].".');
location.href='welcome.php'
</script>";
}
}
echo "<script>
alert('Username or password incorrect');
location.href='login.html'
</script>";
?>
it seems the $account array's index starts from 0.
change your code in login file at line 13 to
if ($account[0] == $username && $account[1] == $password)
should solve it.
PHP manual for explode

PHP displaying error code once

When a user clicks login, "Wrong Email Or Password" Is displayed for each user that is in Database Array. Could someone point me in the right direction to Only Display Error code once if user input wrong email/password?
I'm Using Flintstone to store Users.
if (isset($_POST['login'])) {
$TempEmail = strtolower($_POST['email']);
$TempPass = $_POST['password'];
// Get Keys From DB;
$keys = $users->getKeys();
// Check If DB is Empty
if (!empty($keys)) {
foreach ($keys as $key) {
$user = $users->get($key);
$email = strtolower($user['Email']);
$password = $user['Password'];
$hash = password_verify($TempPass, $password);
try {
if (($TempEmail === $email) && ($hash === true))
{
$_SESSION['use']=$email;
// On Successful Login redirects to home page
header("Location:/home/");
}
else
{
echo "Wrong Email Or Password";
//break;
}
} catch (Exception $e) {
return $e->getMessage();
}
}
} else {
echo "DB Is Empty";
exit;
}
}
Simply move echo "Wrong Email Or Password" right after the foreach-loop instead of inside it. If the email is found and the password matches, the user will still be redirected before the code reaches that point.
foreach ($keys as $key) {
// Your current code, minus the echo.
}
// This is after the foreach and will only be executed if there were
// no match for the email and password.
echo "Wrong Email Or Password";
Just remember to add an exit; after your header('Location:....'); to stop PHP from executing anything more.
The foreach loop goes through all the $keys, hence it echoes "Wrong Email Or Password" for every wrong key.
Save the outcome of a successfull query in a variable i.e. $success = false. If the correct login was found, set it to true. After the foreach loop you can write
if(!$success){echo "Wrong password"};
I think this is more user-friendly:
$login = false;
foreach ($keys as $key) {
$user = $users->get($key);
$email = strtolower($user['Email']);
$password = $user['Password'];
$hash = password_verify($TempPass, $password);
try {
if ($TempEmail === $email) {
if ($hash === true) {
$login = true;
$_SESSION['use'] = $email;
// On Successful Login redirects to home page
header("Location:/home/");
} else {
break;
}
}
} catch (Exception $e) {
return $e->getMessage();
}
}
if (!$login) {
echo "Wrong Email Or Password";
}

Record data as array in txt file

I need to create very simple register/login system in PHP. User details must be stored in array in txt file. For some reasons even when PHP not show any error details are not saved to txt file. Any hint?
$fullname='';
$email ='';
$username ='';
$password = '';
$error = '';
$form_is_submitted = false;
$errors_detected = false;
$clean = array();
$errors = array();
if (isset($_POST['submit'])) {
$form_is_submitted = true;
if (ctype_alnum ($_POST['fullname'])) {
$clean['fullname'] = $_POST['fullname'];
} else {
$errors_detected = true;
$errors[] = 'Please enter your Full Name!';
}
if (ctype_alnum ($_POST['email'])) {
$clean['email'] = $_POST['email'];
} else {
$errors_detected = true;
$errors[] = 'You have enter an invalid e-mail address. Please, try again!';
}
if (ctype_alnum ($_POST['username'])) {
$clean['username'] = $_POST['username'];
} else {
$errors_detected = true;
$errors[] = 'Please enter your user name!';
if (ctype_alnum ($_POST['password'])) {
$clean['password'] = $_POST['password'];
} else {
$errors_detected = true;
$errors[] = 'Please enter a valid password!';
}
}
if ($form_is_submitted === true
&& $errors_detected === false) {
$fp = fopen('filewriting.txt', 'w');
fwrite($fp, print_r($clean, TRUE));
fclose($fp);
} else {
echo $errors;
}
There are a few things wrong with your code.
There is a missing brace for
if (isset($_POST['submit'])) {$form_is_submitted = true;
so it needs to read as
if (isset($_POST['submit'])) {
$form_is_submitted = true;
}
You are using ctype_alnum so when it comes to an email address, the # and the dot do not count as alpha-numerical characters a-z A-Z 0-9; either remove it if(ctype_alnum ($_POST['email'])) which proved to be successful in testing this.
You can also use another function such as FILTER_VALIDATE_EMAIL
I quote from the PHP manual:
Return Values
Returns TRUE if every character in text is either a letter or a digit, FALSE otherwise.
This block has a misplaced brace
if (ctype_alnum ($_POST['username'])) {
$clean['username'] = $_POST['username'];
} else {
$errors_detected = true;
$errors[] = 'Please enter your user name!';
if (ctype_alnum ($_POST['password'])) {
$clean['password'] = $_POST['password'];
} else {
$errors_detected = true;
$errors[] = 'Please enter a valid password!';
}
}
Which should read as
if (ctype_alnum ($_POST['username'])) {
$clean['username'] = $_POST['username'];
} else {
$errors_detected = true;
$errors[] = 'Please enter your user name!';
} // was missing
if (ctype_alnum ($_POST['password'])) {
$clean['password'] = $_POST['password'];
} else {
$errors_detected = true;
$errors[] = 'Please enter a valid password!';
}
// } // was misplaced - commented out to show you
otherwise it would not have written the password (as part of the array) to file.
Plus this $error = ''; should "probably" read as $errors = ''; but that didn't stop it from writing the data to file.
As for the Array message, remove the square brackets [] from all instances of $errors[]
I think
fwrite($fp, print_r($clean, TRUE));
should be
fwrite($fp, $clean, TRUE);
or
file_put_contents($fp, $clean);

redirect based on user role stored in mysql database

I've made a website that users can now successfully login to but depending on which group the user is in, I would like to redirect them to different pages after logging in. I have a database with a row "training_group" and if for example, they are in group 2013_1, they would be directed to homepage_20131.php after logging in.
I've been looking for tutorials online and have found a possible solution with a switch function? but I am unsure of how/where to implement this. I just started learning php and would be grateful for any advice given!
Right now, my login page looks like this:
<?php
include 'core/init.php';
if (empty($_POST) === false) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) === true || empty($password) === true) {
$errors[] = 'please input a username and password first! ';
} else if (user_exists($username) === false) {
$errors[] = 'We could not locate you in our database.';
}
$login = login($username, $password);
if ($login === false) {
$errors [] = 'That username/password combination is incorrect';
}
else {
$_SESSION['user_id'] = $login;
header('Location:logged_in/templates/logged_in_home.php');
exit ();
}
}
else {
$errors [] = 'No data received';
}
include 'includes/overall/header.php';
if (empty ($errors) === false) {
?>
<h2>We tried to log you in, but...</h2>
<?php
echo output_errors($errors);
}
include 'includes/overall/footer.php';
?>
Here are a couple snippets that might get you going in the right direction.
function login($username, $password){
//... your login code .. database call
if($validLogin){
$user_id = id from database;
$group_id = id from database;
$return = array('user_id' => $user_id, 'group_id' => $group_id);
}
else{
$return = false;
}
return $return;
}
$userinfo = login($username, $password);
if ($userinfo === false) {
$errors [] = 'That username/password combination is incorrect';
}
else {
$_SESSION['user_id'] = $userinfo['user_id'];
$_SESSION['group_id'] = $userinfo['group_id'];
$page = 'homepage_' . str_replace('_', '', $userinfo['group_id'] . '.php';
header('Location:' . $page);
exit ();
}

Categories