PHP Read txt file and check if username password exists - php

I have a bunch of passwords and usernames stored in a txt file and i need to check for matches. I know this is not a safe method but its for leaning purposes.
This code writes the usernames and passwords to a txt file
if(isset($_POST['register'])) //
{
$user = $_POST['username'];
$password=$_POST['password'].PHP_EOL;
$fh = fopen("file.txt","a+");
fwrite($fh,$user." ".$password); //write to txtfile
fclose($fh);
}
Here's the code im having trouble with.
Username and Passwords are stored like this in results
username1 passwords1 username2 password2 etc.
So I need to check if result[0] = userinput AND if it exists check if result[1] = passwordInput and so on.
if(isset($_POST['Logg']))
{
//$_SESSION['username']=$user;
//$_SESSION['password']=$password;
$file = file_get_contents("file.txt"); // Returns a string
$result = explode(" ",$file);
$boolC= false;
for($i=0; $i< count($result); $i++)
{
if($result[$i] === $user)
{
$boolC=true;
$i =$i+1;
if($boolC === true)
{
if($result[$i]===$password)
{
echo 'Password and Username Correct';
}
}
}
}
}

Consider the possibility of having a space in the password so as any symbols. Perhaps you should split on a line break ("\n").
if( $result[$i] === $user && $result[$i+1] === $password )
The first part of the statement has to be true for the second one to be evaluated.
The $i variable is never changed
$file = "username1 passwords1 username2 password2";
$result = explode(" ",$file);
$user = "username1";
$password = "passwords1";
for($i=0; $i< count($result); $i++){
if($result[$i] === $user && $result[$i+1] === $password)
{
echo 'Password and Username Correct';
}
}

Before you go ahead and try to correct this code, I strongly suggest you stay away from storing passwords in a plain text file. It is a huge security hole in your system.
Another architecture issue I can see is that your code would fail if the username or passwords contain a space in them. You probably should use line jumps as a delimiter instead (\n).

I think there is nothing wrong with the logic of the original post.
You should print all the variables to check whether they hold the correct value or not.
the "$user" and "$password" variables are global or not since they would not be known within the braces of the other if block i.e in the block where you check $_POST['logg']

Related

How to have an else statement after a loop with an if statement?

I am trying to make a registration system with text files and I need help with using an else statement after the loop that checks if the username is taken.
I am generally just trying to find out how to have an else statement after a loop with an if statement, if I find out that out my problem is basically solved. Here is the code:
while($i < count($logindata)-1) {
if ($_POST['username'] == $user[$i]['username']) {
set_message(" That username is taken", "danger");
}
$i++;
}
else {
if (!empty($_POST['username']) && !empty($_POST['password'])) {
file_put_contents('logininformation.txt', $_POST['username'] . "?=%&$##[}[}+-789409289746829" . $_POST['password'] . "\n", FILE_APPEND);
set_message("Account created!", "success");
} else {
set_message(" You have not put in a username and/or password","danger");
}
}
I expect to be able to have an else statement after the loop and it working.
A loop is not a condition, therefore it does not have an else part either. It is correct that the loop runs while the condition evaluates to true, but as soon as the condition does not evaluate to true, the loop is ended.
Therefore, to check whether the loop was not triggered at all, you have to find a different way, e.g. write a condition on its own.
For the sake of argument, you COULD save a flag and evaluate that afterwards, but in most cases I would not recommend that:
$i = 0;
$loopDidRun = false;
while ($i < 10) {
$i++;
$loopDidRun = true;
}
if (!$loopDidRun) {
echo "loop did not run, therefore the 'else case', but not really";
}
Your logic is severely flawed.
$failed=false;
if(empty($_POST['username']) || empty($_POST['password'])){
$failed=true,
set_message(" You have not put in a username and/or password","danger");
}else{
while($i<count($logindata)-1){
if($_POST['username']==$user[$i]['username']){
$failed=true;
set_message("That username is taken","danger");
break;
}
$i++;
}
}
if(!$failed){
file_put_contents('logininformation.txt',$_POST['username']."?=%&$##[[}+-789409289746829".$_POST['password']."\n",FILE_APPEND);
set_message("Account created!","success");
}
However all I am doing here is fixing bad code. Before anything you need to filter the $POST input given to disallow just any input, passwords etc. should not be stored in plain text, and this is not the proper way of creating a factory for this. You should find better, and secure, examples online and work from them.

How to read a file line by line in php and compare it with an existing string?

I tried to write this program to compare a user-name in a file with an entered user-name to check whether it exists, but the program doesn't seem to work. Please help. The program was supposed to open a file called allusernames to compare the usernames. If the user name was not found, add it to the file.
<?php
$valid=1;
$username = $_POST["username"];
$listofusernames = fopen("allusernames.txt", "r") or die("Unable to open");
while(!feof($listofusernames)) {
$cmp = fgets($listofusernames);
$val = strcmp($cmp , $username);
if($val == 0) {
echo ("Choose another user name, the user name you have entered has already been chosen!");
$valid=0;
fclose($listofusernames);
break;
} else {
continue;
}
}
if($valid != 0) {
$finalusers = fopen("allusernames.txt", "a+");
fwrite($finalusers, $username.PHP_EOL);
fclose($finalusers);
?>
you need to replace linefeed/newline character from each line to compare.
while(!feof($listofusernames)) {
$cmp = fgets($listofusernames);
$cmp = str_replace(array("\r", "\n"), '',$cmp);
$val = strcmp($cmp , $username);
if($val == 0) {
echo ("Choose another user name, the user name you have entered has already been chosen!");
$valid=0;
fclose($listofusernames);
break;
} else {
continue;
}
}
i have added following line in you code
$cmp = str_replace(array("\r", "\n"), '',$cmp);
I havent tested this but I wonder if you could use something like
<?php
$user = $_POST["username"];
$contents = file_get_contents("allusernames.txt");
$usernames = explode("\n",$contents);
if(in_array($user,$usernames))
{
echo "Choose another username";
}
else
{
$contents .= "\n".$user;
file_put_contents("allusernames.txt",$contents);
}
I think things like file get contents etc. need a certain version of PHP but they do make things a lot nicer to work with.
This also assumes that your usernames are seperated by new lines.
Yo can do this more simple with this code:
<?php
$username = $_POST["username"];
$listofusernames = 'allusernames.txt';
$content = file($listofusernames);
if(in_array($username, $content)) {
echo ("Choose another user name, the user name you have entered has already been chosen!");
} else {
$content[] = $username . PHP_EOL;
file_put_contents($listofusernames, implode('', $content));
}
?>

get textarea value, separate by new line, save to database php

I have a textarea in my html named add-list. I want to get the value of the textarea per line break and then save it to my database. The problem is, when it saves the input to the database, the second and succeeding entries have a whitespace before the input.
Here is my function for getting the value:
public function add(){
$checker = false;
$names = $this->input->post('add-list');
if (strpos($names, "\n") == TRUE ) { //newline found
$names = nl2br(trim($this->input->post('add-list')));
$namesArray = explode('<br />', $names);
foreach($namesArray as $name) {
$checker = false;
$checker = $this->checkDatabase($name); //check if name already exists in database
if ($checker) {
echo "<script type='text/javascript'>alert('A site in your list already exists. Duplicate sites are not allowed.');</script>";
}
if (!$checker) {
$this->data_model->addCommunity($name);
}
}
$this->index();
redirect(base_url());
}
else if (strpos($names, "\n") == FALSE) {
$checker = $this->checkDatabase($names);
if ($checker) {
echo "<script type='text/javascript'>alert('" . $names . " already exists. Duplicate sites are not allowed.'); window.location.href='".base_url()."'</script>";
}
if (!$checker) {
$this->data_model->addCommunity($names);
$this->index();
redirect(base_url());
}
}
}
What I get in my database is like this:
firstName
secondName //there's a whitespace before 's'
Help me please!!!
Why do you go all the way through nl2br and then explode instead of using explode with a line break? But just use the search or a search engine, e.g. Explode PHP string by new line (long time no PHP, so I might not be quite right).

MySQL password() function to PHP

I tried researching this but still have no answer for it. A program my friend designed writes to the MySQL db passwords using the MySQL password() function.
I am looking for a way to use this through the web front I designed but still have no luck. Does anyone have any suggestions?
The passwords look just like this example
mysql> SET old_passwords = 0;
mysql> SELECT PASSWORD('mypass');
+-------------------------------------------+
| PASSWORD('mypass') |
+-------------------------------------------+
| *6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4 |
+-------------------------------------------+
I just need to figure out how to turn this into a function i.e
function password_hash
Here's the rest the login query for an example
if (isset($_POST["username"], $_POST["password"], $_POST[$CONF["LOGIN_SIGNAL_TRIGGER"]])) {
/*
If we got a login signal, a password and a username, we will
proceed to check login information. We will first extract
the user row from the db.
*/
$user = myF(myQ("
SELECT `username`,`password`,`id`,`disable_until`,`active`
FROM `[x]users`
WHERE LCASE(`username`)='".strtolower($_POST["username"])."'
"));
if (!$user["id"]) $GLOBALS["LOGIN_FAIL_TYPE"] = "e.user";
elseif ($user["active"] != 1 && $CONF["LOGIN_REQUIRE_ACTIVE"]) $GLOBALS["LOGIN_FAIL_TYPE"] = "e.active";
else {
/*
If the user's account 'disabled' value is greater than
the actual date value, and that the bruteforce protection
system is enabled, we will show an error message
*/
if (($user["disable_until"] > date("U")) && ($CONF["LOGIN_BRUTEFORCE_PROTECT:ENABLE"])) {
$GLOBALS["LOGIN_FAIL_TYPE"] = "e.bruteforce";
(isset($_SESSION["loginFailCount"])?session_unregister('loginFailCount'):false);
}
/*
Account is not disabled
*/
else {
if ((isset($_SESSION["loginFailCount"])) && ($_SESSION["loginFailCount"] > $CONF["LOGIN_BRUTEFORCE_FAILCOUNT"])) {
myQ("UPDATE `[x]users`
SET `disable_until` = ".(date("U")+$CONF["LOGIN_BRUTEFORCE_DISABLE_DURATION"])."
WHERE LCASE(`username`)='".strtolower($_POST["username"])."'
LIMIT 1"
);
(isset($_SESSION["loginFailCount"])?session_unregister('loginFailCount'):false);
$GLOBALS["LOGIN_FAIL_TYPE"] = "e.bruteforce";
}
else {
/*
All the information correct, we will proceed to login
*/
if ($user["password"] == md5(trim($_POST["password"]))) {
$_SESSION["id"] = (integer)$user["id"];
session_write_close();
/*
Update the last login key
*/
$me_last_login = me("last_login");
myQ("UPDATE `[x]users` SET `last_login`='".date("U")."' WHERE `id`='".me('id')."'");
/*
Route the user
*/
if (!$GLOBALS["WAP_MODE"]) {
header("Location: ".(!$me_last_login?$CONF["LOGIN_FIRST_ROUTE_TO"]:$CONF["LOGIN_ROUTE_TO"]));
} else header("Location: {$CONF["WAP_LOGIN_ROUTE_TO"]}");
}
else {
(isset($_SESSION["loginFailCount"])?$_SESSION["loginFailCount"]++:$_SESSION["loginFailCount"]=1);
$GLOBALS["LOGIN_FAIL_TYPE"] = "e.password";
}
}
}
}
}
if ((isset($_GET[$CONF["LOGOUT_SIGNAL_TRIGGER"]])) && (!isset($_POST[$CONF["LOGIN_SIGNAL_TRIGGER"]]))) {
/*
Handle admin swapping
*/
if (isset($_SESSION["swap_id"])) {
$_SESSION["id"] = $_SESSION["swap_id"];
session_unregister("swap_id");
header("Location: ?L=admin.index");
}
else {
(isset($_SESSION["id"])?session_unregister('id'):false);
(isset($_SESSION["SELF_USER_DATA"])?session_unregister('SELF_USER_DATA'):false);
header("Location: {$CONF["LOGOUT_ROUTE_TO"]}");
}
}
OP asked how to do this in php. This is how to do it in php:
function sqlPassword($input) {
$pass = strtoupper(
sha1(
sha1($input, true)
)
);
$pass = '*' . $pass;
return $pass;
}
Added for posterity (No reason you would use this, use it if mysql decides to deprecate the PASSWORD function?, for informative purposes only) the mysql equivalent of the php equivalent
SELECT
UPPER(
CONCAT('*', SHA1(UNHEX(SHA1('password'))))
)
Also see MySQL Hashing Function Implementation
If I understand you correctly there is no need to reproduce PASSWORD() in php do all your validation in one go on mysql side using PASSWORD() in your select like this
SELECT `username`,`password`,`id`,`disable_until`,`active`
FROM `[x]users`
WHERE `username` = 'user1'
AND `password` = PASSWORD('password')
Here is SQLFiddle demo
Unless you use case sensitive collation don't use LCASE() on username column in your statements. It prevents MySql from using an index (indices) if any is defined on that column and cause a full scan on the table.
On a side note: your code is vulnerable to sql-injections. Consider to use prepared statements.
Copy-paste from a password encoder interface for a Symfony2 app I wrote that migrated from an old system using the MySQL PASSWORD function:
function mysqlPassword($raw) {
return '*'.strtoupper(hash('sha1',pack('H*',hash('sha1', $raw))));
}
My version of the pre-MySQL 4.1 code.
/* PHP implementation of MySQL pre-4.1 password function.
Based on Perl Crypt::MySQL C code */
function mysql_old_password_hash($password) {
$len = strlen($password);
$add = 7;
$nr = 1345345333;
$nr2 = 0x12345671;
$tmp = 0;
foreach (str_split($password) as $chr) {
if ($chr == " " || $chr == "\t") {
continue;
}
$tmp = ord($chr);
$nr ^= ((($nr & 0x3f)+$add)*$tmp) + ($nr << 8);
$nr2 += ($nr2 << 8) ^ $nr;
$nr2 &= 0xffffffff; # We need to limit this to 32-bit
$add += $tmp;
}
// Strip sign bit
$nr &= 0x7fffffff;
$nr2 &= 0x7fffffff;
return sprintf("%08x%08x",$nr,$nr2);
}
For post-4.1, pre-5.7.something versions, look at sjagr or chiliNUT's answers.
The only reason to use this is in order to check passwords in a database that was written in spite of MySQL's advice not to use PASSWORD() for your own applications.
first use mysql_escape_string($_POST['password']) to escape the password.
then use that as a variable inside the sql query in
WHERE password_field = PASSWORD(USER_SUPPLIED_PASSWORD)

String comparison regardless of case

I'm trying to find different variations of "Username" or "Password" , as shown below, in an case-insensitive manner:
$unVar1 = "username";
$unVar2 = "user name";
$usernameVariations1 = strcasecmp($unVar1, $unVar2);
$unVar3 = "User";
$unVar4 = "id";
$usernameVariations2 = strcasecmp($unVar3, $unVar4);
$pwVar1 = "password";
$pwVar2 = "pass";
$passwordVariations1 = strcasecmp($pwVar1, $pwVar2);
if ($element->value === $usernameVariations1
|| $element->value === $usernameVariations2
|| $element->value === $passwordVariations1) {
echo "Weee!";
}
else {
echo "boo!";
}
The problem is it outputs "boo" for each element in the foreach() output. What am I doing wrong? Is it possible to put all of these values in an array? Thanks.
You're making this more complicated then it needs to be. If your usernames and passwords not case sensitive, just make them lowercase when you compare them:
if (strtolower($username) === strtolower($element->value))
{
// ok
}
Now if you're allowing spaces to be added to the middle, and abbreviations, then you can try plan B:
$valid_usernames = array('Username', 'username', 'user name', 'UsE Nam');
if (in_array($element->value, $valid_usernames))
{
// ok
}
Keep in mind that you are now responsible for keeping $valid_usernames complete.

Categories