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;
}
}
Related
$con = mysqli_connect('localhost', 'login', '*mypass*', 'login');
$check = "SELECT * FROM users";
$rs = mysqli_query($con, $check);
if(isset($_POST['submit'])) {
$username = strtolower($_POST['username']);
$password = hash('sha512', $_POST['password']);
if($username && $password){
while($data = mysqli_fetch_array($rs)){
if($username == $data[1]){
if($password == $data[2]){
session_start();
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $username;
$exp = time() + (60*60*24*365);
setcookie('user', $username, $exp);
echo "test";
header("location: dash.php");
exit();
} else {
error("Incorrect Password");
}
}
}
} else {
error("Please insert your username and password");
}
}
In this code, the content of the if statement ( if($password == $data[2]) ) doesn't run correctly: only the echo function works, all the other doesn't!
Is there a solution to this issue?
I use PHP 7.0
POST:
echo "test"; was added only for testings purposes, the code doesn't work with or without it.
Looking at this part:
if($username && $password){
while($data = mysqli_fetch_array($rs)){
if($username == $data[1]){
if($password == $data[2]){
You should be careful when reading $data. Put simply, the $data array is indexed on a per-row basis starting from 0, so $data[1] and $data[2] refer to the entire second and third resultset rows, but you're not actually reading any result fields.
The right and cleaner way would be:
if($username && $password){
$data = mysqli_fetch_array($rs);
foreach ($data as $row)
{
$username = $row['field_name_with_username];
$password = $row['field_name_with_password];
... then whatever you need to do afterwards with those variables
}
If you rather stay away from the foreach looping, you can use while or for, but you need to define an interation counter (i.e. $i = 0; before entering the loop and $i++; just before the end of each iteration) and on each pass access $data[$i]['field_name_with_username'] and $data[$i]['field_name_with_password']
This is not an answer but something to try to check sessions are working.
Place the following code in its own file:
<?php
session_start();
if(isset($_SESSION['test_counter'])) {
$_SESSION['test_counter']++;
} else {
$_SESSION['test_counter'] = 1;
}
echo $_SESSION['test_counter'];
It should first display 1, and then increment the integer upon refresh.
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
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;
}
}
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 wanted to build a super-simple login-script with a text-file. Text-file contains
password username name
Between the password, username and name is a tab. I read the file, explode it by tab, and then check the user input against the lines.
But I always get (one) Undefined offset error. I think it is because of the explode function, but I don't know why...
Here's my code:
if(!empty($_POST['login_inputEmail']) || !empty($_POST['login_inputPassword']))
{
$log = 0; //not logged in
$username = $_POST['login_inputEmail'];
$password = $_POST['login_inputPassword'];
$userdatei = fopen ("documents/user.txt","r");
while (!feof($userdatei))
{
$zeile = fgets($userdatei,800);
$userdata = explode("\t", $zeile);
if ($username == $userdata[1] && $password == trim($userdata[0]))
{
$log = 1; //logged in
}
}
fclose($userdatei);
}
Add is_array() and isset() in your code to avoid errors. Refer this
if(!empty($_POST['login_inputEmail']) || !empty($_POST['login_inputPassword']))
{
$log = 0; //not logged in
$username = $_POST['login_inputEmail'];
$password = $_POST['login_inputPassword'];
$userdatei = fopen ("documents/user.txt","r");
while (!feof($userdatei))
{
$zeile = fgets($userdatei,800);
$userdata = explode("\t", $zeile);
if(is_array($userdata))
{
if(isset($userdata[1]) && isset($userdata[0]))
{
if ($username == $userdata[1] && $password == trim($userdata[0]))
{
$log = 1; //logged in
}
}
}
}
fclose($userdatei);
}