PHP Find password in foreach loop - php

I have a very simple login script, it requires just a password and thats it. The user will attempt to login and when the user enters the wrong password the php script will append the password to a text file but first the script checks whether the password is already in the file and if it is, the script will then add 1 to the number of attempts in the file. My problem is i am trying to find a way to check every password and then add the password but not check each individual password and add the password right away. I am using a class file found at this website My code is below.
<!DOCTYPE html>
<html>
<head>
<title>Website</title>
</head>
<body>
<form method="post" action="Assets/Scripts/PHP/Login.php">
<table>
<tr>
<td>
<label for="Password">Password:</label>
</td>
<td>
<input type="password" name="password" placeholder="Password" id="Password" />
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="submit" name="submit" value="Log In" />
</td>
</tr>
</table>
</form>
</body>
</html>
Login.php
<?php
$Password = $_POST['password'];
$Submit = $_POST['submit'];
if(isset($Submit))
{
if($Password != '' && $Password == 'Password')
{
session_start();
$_SESSION['Login'] = 'True';
$Login = $_SESSION['Login'];
if(isset($Login))
{
header("location:../../../main.php");
}
else
{
header("location:../../../index.html");
}
}
else
{
include("../../../MyTXT.php");
$File = new MyTXT("../../Texts/Passwords.txt");
foreach($File->rows as $Row)
{
if($Row != $Password)
{
$File->add_row(array($Password, "1"));
$File->save();
}
else
{
}
}
echo 'The Password Is Incorrect';
echo '<br />';
echo 'Go Back';
}
}
else
{
header("location:../../../index.html");
}
Txt File
Password:|:Attempts
Test:|:26
Test123:|:2
Test456:|:5

Is there a specific reason you're using the code from the link? It looks like a LOT of code for what is a simple task.
Try these:
Read contents of the file into a string:
http://php.net/manual/en/function.file-get-contents.php
Read contents of file into an array:
http://php.net/manual/en/function.file.php
I'm still not exactly sure how you're checking if their password is correct, as your file contains incorrect passwords, however, a quick example (v quick..) of how to check for a string in a file:
$strPassword = '123test';
$strFilename = 'pass.txt';
$strFileContents = file_get_contents($strFilename);
if(strpos($strFileContents, $strPassword))
{
//$strPassword is there, log them in/whatever
}
else
{
//password not there
}
However if you want/need to use that script from that site, then in the downloads there are examples of how to use it. You should study those and write code with them, and if you are stuck, ask specific questions.

Related

I want users to update account information only after they log in... But I have no Idea How to do it

I have made simple php files by using which I can validate username and PASSWORD and then only user can log in. I want users to update account only if they log in to account. Without validating ID and password, they can't update their Name and Surname and all... It's very simple program. Here is the table Structure.
It is just a Demo data. I want users to update their accounts only after logging in. Here is the file by which they can see their information by logging in.
<html>
<head>
<title>
Login
</title>
</head>
<body>
<?php
if(isset($_POST["uname"]) && isset($_POST["pass"]))
{
$uname=$_POST["uname"];
$pass=$_POST["pass"];
mysql_connect("localhost","adarsh","Yeah!");
mysql_select_db("aadarsh");
$select = mysql_query("select * from users where username='$uname' AND pass='$pass'");
$data = mysql_fetch_array($select);
if($uname==$data['username'] && $pass==$data['pass'])
{
echo "<center>";
echo "Name: ".$data['username']."<br>";
echo "Last namme: ".$data['lastname']."<br>";
echo "<img src=".$data['image']."><br>";
echo "</center>";
}
else
{
echo "<script>alert('Nope!!!');</script>";
}
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="text" name="uname">
<input type="pass" name="pass">
<input type="submit" name="submit" value="Login!">
</form>
</html>
The code is working fine and They can see their data by entering username and password. If they will enter wrong Username and password, they will just see alert box.
I just want users to update their data after logging in. Without login, they can't update their data.
But i have no idea how to do it. Once I tried by validating username and password and then redirecting to new page where they can update their account using header location but that doesn't work. I didn't get any variables on the other page.
Help me solving this....
Try this
<html>
<head>
<title>
Login
</title>
</head>
<body>
<?php
session_start();
if(isset($_POST["submit"]))
{
$uname=$_POST["uname"];
$pass=$_POST["pass"];
if(empty($uname) && empty($pass))
{
echo "<script>alert('Empty');</script>";
}
else
{
mysql_connect("localhost","adarsh","Yeah!","aadarsh");
$select = mysql_query("select * from users where username='$uname' AND pass='$pass'");
$data = mysql_fetch_array($select);
$count = count($data);
if(empty($count) || $count > 1)
{
echo "<script>alert('Invalid Login');</script>";
}
else
{
$image = $data['image'];
$lname = $data['lastname'];
$username = $data['username'];
$_SESSION["lastname"] = $lname;
$_SESSION["username"] = $username;
echo "Name: ".'$username'."<br>";
echo "Last namme:".'$lname'."<br>";
echo "<img src='$image'><br>";
if(isset($_SESSION))
{
redirect('new_page.php');
}
else
{
echo "<script>alert('Something Went Wrong');</script>";
}
}
}
}
?>
<form method="post" action="#">
<input type="text" name="uname">
<input type="pass" name="pass">
<input type="submit" name="submit" value="Login!">
</form>
</body>
</html>
and in new_page.php
<?php
session_start();
if(isset($_SESSION["username"]))
{
//show update form
}
else
{
//redirect to login page
redirect('login.php');
}
Includes
Using Session
Optimize Query
Validate all fields
and take a look at this too
How can I prevent SQL-injection in PHP?
MySQL extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.
So, after logging in, instead of simply displaying the users details, display a form allowing the user to update their details, something like this (incomplete code just to give you an outline):
if($uname==$data['username'] && $pass==$data['pass'])
{
echo '<form method="" action ="">';
echo '<input value="'.$data['username'].'" />';
echo '<input value="'.$data['lastname'].'" />';
echo '<input type="submit" />';
echo "</form>";
}
If you want to pass variables from one page to another, once the user is logged in, you should use Session variables.
Thanks to all to answer on my question. Finally with the help of you guys, I solved every errors and Program is working fine!
I did this with the help of 2 files... Here are they,
updatedata.php (This file contains only html stuff... .html will also work)
<html>
<head>
<title>
Login
</title>
</head>
<body>
<form method="post" action="updateaccount.php">
Username : <input type="text" name="uname"><br>
Password :<input type="password" name="pass"><br>
New Information:<br><br>
New Name : <input type="text" name="newname"></input>
<input type="submit" name="submit" value="Update!">
</form>
</html>
updateaccount.php (hehe, Don't get confused in file names...)
<?php
$con=mysql_connect("localhost","adarsh","Password");
mysql_select_db("aadarsh",$con);
if(isset($_POST["uname"]) && isset($_POST["pass"]))
{
$uname=$_POST["uname"];
$pass=$_POST["pass"];
}
$sql="select * from users where username='$uname' AND pass='$pass'";
$select = mysql_query($sql);
$data = mysql_fetch_array($select);
$username=$_POST["newname"];
if(isset($_POST['submit']))
{
if($uname==$data['username'] && $pass==$data['pass'])
{
$user_id= $data['id'];
if(isset($_POST['newname']))
{
$update = mysql_query("UPDATE users SET username = '$username' WHERE id = $user_id");
if($update)
{
echo "<script>alert('updated!');</script>";
header("location:http://www.example.com");
}
else
{
echo mysql_error();
}
}
}
else
{
echo "<script>alert('Nope!!!');</script>";
}
}
?>
Thanks to all of you again.... :)
Some considerations about your code:
mysql_connect is deprecated, you should use mysqli_connect.
http://php.net/manual/en/book.mysqli.php
You can use empty() instead of isset(). empty() will return true if the variable is an empty string, false, array(), NULL, “0?, 0, and an unset variable. With !empty you can:
if (!empty($_POST["uname"]) && !empty($_POST["pass"])){
$uname = .........
}
Can't use echo and header("location:http....") in the same loop. If you send to another page, the message will not be displayed.
After a header("location:http....") you must exit(); otherwise, the code will follow the normal flow.
You check if ($update). If you click the submit button, $update always be true, so this check is not necessary.
Hope that helps.

PHP basic form validation

I'm building a website that is password-protected but I can't seem get it to work properly. I have it set to go to the homepage if the password is correct & to a different page if the password is incorrect. I have written the code but every time I run it, it goes right to the page that displays if the password is wrong. I know something is missing from the code but I'm not sure what it is.
HTML
<table>
<form action="index.php" method="post">
<tr>
<td><input type="password" name="password" /></td>
<td><input type="submit" name="submit" value="Request Permission" /></td>
</tr>
</form>
</table>
PHP
$pass = $_POST['password'];
if ($pass == "Password") {
header('Location:home.php');
} else {
header('Location:wrong.php');
exit;
}
Can you please help me?
You're not checking to see if the form is submitted. You're just going straight into your logic.
And easy way to check to see if the page has received a form submission is to check the request method.
if('POST' === $_SERVER['REQUEST_METHOD']) {
$pass = $_POST['password'];
if ($pass == "Password") {
header('Location:home.php');
} else {
header('Location:wrong.php');
exit;
}
}
You can also check to see if $_POST['submit'] is set and has a value.
FYI, might want to put an exit after the first call to header(). Also, this isn't a great way to go about checking passwords. Might want to consider using a database and hashed passwords. You should also add some data validation (i.e. make sure the password field isn't blank).
add this around your PHP:
if(isset($_POST['submit'])) {
}
It'll work fine then, upon page load the code is being read, and as $_POST['password'] has no value at this stage you're being redirected to wrong.php.
Try this
if('POST' === $_SERVER['REQUEST_METHOD']) {
$pass = $_POST['password'];
if ($pass == "Password") {
header('Location:home.php');
} else {
header('Location:wrong.php');
exit;
}
}
else{
echo'<table>
<form action="index.php" method="post">
<tr>
<td><input type="password" name="password" /></td>
<td><input type="submit" name="submit" value="Request Permission" /></td>
</tr>
</form>
</table>';
}
Consider the following system with the following pages:
index.php - here we will have our login form
<?php
session_start();
if ((isset($_POST['password']) && $_POST['password'] == "Password") || $_SESSION['auth'] == 1)
{
header('Location:home.php');
}
else
{
header('Location:wrong.php');
}
?>
<table>
<form action="index.php" method="post">
<tr>
<td><input type="password" name="password" /></td>
<td><input type="submit" name="submit" value="Request Permission" /></td>
</tr>
</form>
</table>
Your home.php file
<?php
session_start();
if ($_GET['logout'] == 1)
{
session_destroy();
}
if ($_SESSION['auth'] == 1)
{
//show stuff to the logged in user
//display log-out option
echo 'Logout';
}
else
{
//redirect the user to the login page
header('Location:index.php');
}
?>
if ( $_POST['password'] AND $_POST['password'] == "Password")
{
header('Location:home.php');
} else
{
header('Location:wrong.php');
exit;
}

correct username and password doesn't have any effect PHP

I have some problem in php. Here is my code:
if (isset($_POST['submit'])) { // Form has been submitte
echo "Submitted";
$username = trim($_POST['username']);
$password = trim($_POST['password']);
// Check database to see if username/password exist.
$found_user = User::authenticate($username, $password);
if ($found_user) {
$session->login($found_user);
redirect_to("index.php");
}
} else { // Form has not been submitted.
$username = "";
$password = "";
}
?>
<html>
<head>
<title>Photo Gallery</title>
<link href="../stylesheets/main.css" media="all" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header">
<h1>Photo Gallery</h1>
</div>
<div id="main">
<h2>Staff Login</h2>
<form action="login.php" method="post">
<table style="float: left;">
<tr>
<td>Username:</td>
<td>
<input type="text" name="username" maxlength="30" value="
<?php echo htmlentities($username); ?>" />
</td>
</tr>
<tr>
<td>Password:</td>
<td>
<input type="password" name="password" maxlength="30" value="
<?php echo htmlentities($password); ?>" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="submit" value="Login" />
</td>
</tr>
</table>
</form>
</div>
<div id="footer">Copyright <?php echo date("Y", time()); ?>, Gio baramidze</div>
</body>
</html>
My problem is that when i try to log in with incorrect user everything works fine and message "submitted" comes on the screen. But when i write correct username and password and click "Log in" it doesn't even show me the message ("submitted"). It means that "if (isset($_POST['submit']))" this condition isn't true. Despite the fact that I've clicked Submit. Thanks.
My guess is above code is index.php. When a user is found it redirects to the same page (quickly) and thus no $_POST is set since it is reloaded.
if ($found_user) {
$session->login($found_user);
redirect_to("index.php"); //If user found redirect without $_POST information.
}
You should make use of the $_SESSION array. This is a server side array, you can fill it with a user ID once a user logs in. On every page where you need to check a login you should include a script that checks for the this ID. You can also use this to store a users name or other stuff you need frequent access to:
$_SESSION['USER_ID'] = //Some ID
$_SESSION['USERNAME'] = $username
To make $_SESSION work you need something like this:
<?php
session_start();
//other code...
if ($found_user) {
$session->login($found_user);
//give the user an ID
$_SESSION['USER_ID'] = //some id, usually fetched from a database
//Let's give a name too
$_SESSION['USERNAME'] = $username;
//Now redirect
redirect_to("index.php"); //If user found redirect without $_POST information.
}
//Other code...
?>
Now from index.php we start again with session_start(); and we can use php to retrieve his ID and name. Put this on top and you see that $_SESSION gets carried over to other pages on the server.
<?php
session_start();
echo $_SESSION['USER_ID'];
echo $_SESSION['USERNAME'];
//or something nicer
if (isset($_SESSION['USER_ID']))
{
echo "User ".$_SESSION['USERNAME']." has logged in and has user id [".$_SESSION['USER_ID']."].";
}
else
{
echo "Not logged on."
}
?>
For testing purpose you can store the above code in whatever.php and redirect to whatever.php inside your login.php. It should pass the if statement if a user is found on login.php and thus show the username and ID.
You might change isset($_POST['submit']) by
if(isset($_POST['username']) && isset($_POST['password'])){
//do your stuff here
}

How to check that a string WAS reversed using strrev() in PHP

Now I understand how to reverse a string in PHP:
<?php
echo strrev("Hello world!"); // outputs "!dlrow olleH"
?>
However, I have searched high and low and cannot figure out how to do what I want to do. (This is for a class project fyi)
I need to check that the password is the exact reverse of the username. So the user may choose whatever they want, but their password must be the exact reverse in order for them to proceed and log into the page.
EX:
username: me
Password: em
I do not need to store this in a file, just hard code it into the PHP script and have it check to make sure the one text field is the reverse of the other.
In theory (and I'm really new to this), I was thinking I should do something like this:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
echo ($_POST['password'] === strrev($_POST['username'])) ? 'true' : 'false'; // check that password is reverse of username
?>
However, this is obviously not right (or I wouldn't be here). No matter what I put it, it is allowing the user to go on to the next page.
Full code:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
echo ($_POST['password'] === strrev($_POST['username'])) ? 'true' : 'false'; // check that password is reverse of username
?>
<html>
<head></head>
<body>
<form action="amanot.php" method="post">
<table>
<tr>
<td><label>Username: </label></td>
<td><input type="text" name="username" id="username"/></td>
</tr>
<tr>
<td><label>Password: </label></td>
<td><input type="password" name="password" id="password"/></td>
</tr>
<tr>
<td><label>Submit</label></td>
<td><input type="submit" name="submit" id="submit"/></td>
</tr>
</table>
</form>
</body>
</html>
Edit
I noticed you used my (original) answer in its entirety, but named it as an .html extension. That will not work.
Use two seperate files. One as .html for the form and the other as amanot.php for the action file.
My original answer had action="" instead of what you were using, plus there was a \ at the end of .../amanot.php\ in your file --- Try this now:
HTML form (form.html)
<html>
<head></head>
<body>
<form action="amanot.php" method="post">
<table>
<tr>
<td><label>Username: </label></td>
<td><input type="text" name="username" id="username"/></td>
</tr>
<tr>
<td><label>Password: </label></td>
<td><input type="password" name="password" id="password"/></td>
</tr>
<tr>
<td><label>Submit</label></td>
<td><input type="submit" name="submit" id="submit"/></td>
</tr>
</table>
</form>
</body>
</html>
PHP (amanot.php) as a seperate file, not inside the form itself, it will not work.
<?php
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
if($password == strrev($username)){
echo "match"; // replace with header("Location: valid.php"); exit;
}
else{
echo "sorry"; // replace with header("Location: invalid.php"); exit;
}
} // brace for if(isset($_POST['submit']))
?>
Original answer
This works:
<?php
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
if($password == strrev($username)){
echo "match"; // replace with header("Location: valid.php"); exit;
}
else{
echo "sorry"; // replace with header("Location: invalid.php"); exit;
}
} // brace for if(isset($_POST['submit']))
?>
<html>
<head></head>
<body>
<form action="" method="post">
<table>
<tr>
<td><label>Username: </label></td>
<td><input type="text" name="username" id="username"/></td>
</tr>
<tr>
<td><label>Password: </label></td>
<td><input type="password" name="password" id="password"/></td>
</tr>
<tr>
<td><label>Submit</label></td>
<td><input type="submit" name="submit" id="submit"/></td>
</tr>
</table>
</form>
</body>
</html>
That logic should be correct. If by 'next page' you mean the page that your PHP script is executing on, then that is the correct behavior.
If you would like to stop the current page from loading, try this instead.
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($_POST['password'] !== strrev($_POST['username'])) {
header('Location: ' . $_SERVER['HTTP_REFERER']);
}
else {
echo 'Successful';
}
?>

Changing a password PHP MySQL

I am working on a section of code that changes a password in a database upon completion of the following form:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Password Change</title>
</head>
<body>
<h1>Change Password</h1>
<form method="POST" action="password_change.php">
<table>
<tr>
<td>Enter your UserName</td>
<td><input type="username" size="10" name="username"></td>
</tr>
<tr>
<td>Enter your existing password:</td>
<td><input type="password" size="10" name="password"></td>
</tr>
<tr>
<td>Enter your new password:</td>
<td><input type="password" size="10" name="newpassword"></td>
</tr>
<tr>
<td>Re-enter your new password:</td>
<td><input type="password" size="10" name="confirmnewpassword"></td>
</tr>
</table>
<p><input type="submit" value="Update Password">
</form>
<p>Home
<p>Logout
</body>
</html>
And the the PHP:
<?php
session_start();
include 'dbconfig.php';
$username = $_POST['username'];
$password = $_POST['password'];
$newpassword = $_POST['newpassword'];
$confirmnewpassword = $_POST['confirmnewpassword'];
$result = mysql_query("SELECT password FROM user_info WHERE
user_id='$username'");
if(!$result)
{
echo "The username you entered does not exist";
}
else if($password!= mysql_result($result, 0))
{
echo "You entered an incorrect password";
}
if($newpassword=$confirmnewpassword)
$sql=mysql_query("UPDATE user_info SET password='$newpassword' where
user_id='$username'");
if($sql)
{
echo "Congratulations You have successfully changed your password";
}
else
{
echo "Passwords do not match";
}
?>
The problem I have at the moment is when I submit the submit button takes me to a read only page of this code.
Any suggestions?
On first looks I can figure out few major mistakes you made:
if you are comparing you should use
$newpassword == $confirmnewpassword
and not
$newpassword=$confirmnewpassword
secondly when you use if..elseif... loop format shold be
if (condition)
{
//code to be executed if condition is true;
}
else if (condition)
{
// code to be executed if condition is true;
}
else
{
//code to be executed if condition is false;
}
You apparently miss the else part in one of your such loops.
Please correct your syntax and try again...
u can 1st select a table and check a password is correct and if correct a update a password .else display a error message.hey this just update a password if old is password is match to update a password....,
Cracker World
$old_password=$_POST['old_password'];
$new_password=$_POST['new_password'];
$con_password=$_POST['con_password'];
$chg_pwd=mysql_query("select * from users where id='1'");
$chg_pwd1=mysql_fetch_array($chg_pwd);
$data_pwd=$chg_pwd1['password'];
if($data_pwd==$old_password){
if($new_password==$con_password){
$update_pwd=mysql_query("update users set password='$new_password' where id='1'");
$change_pwd_error="Update Sucessfully !!!";
}
else{
$change_pwd_error="Your new and Retype Password is not match !!!";
}
}
else
{
$change_pwd_error="Your old password is wrong !!!";
}}
You made a mistake here
This include 'dbconfig.php';
Should be like this include ('dbconfig.php');
After seen your script, i found that you have not use '==' in your password comparison condition.
if($newpassword=$confirmnewpassword)
Which is wrong. You accepted the birju shah's answer above which is pointing out what i want to say.
Apart from this, i found that you did't use any encryption method, which is extremely wrong. Anyone can hack your password from the database.
You should use Password_verify() and Password_hash() functions to encrypt and decrypt your password. These encryption and decryption are considered most safe now days. You should not use md5 encryption because now days anyone can decrypt md5 algorithm.
Here i have made one tutorial Change password code in PHP. I have covered all the above topics. I Hope that this tutorial will help you.
Cheers,

Categories