I have a password protected webpage with one password. But, I want to use multiple passwords on that webpage... I'm very new to PHP...
So, can anyone give me some advice on how to do this!
Thanks in Advance!
here is the code I'm using:
<?php
$password = "anything";
?>
on that code, I want to use "anything" & also use "mypass" as password same time!
I just use this code for multiplying the pass. but, won't work!
<?php
$password = "anything" + "mypass";
?>
& the full code is:
<?php
if (isset($_POST["password"]) && ($_POST["password"]=="$password")) {
?>
### anything to hide before password given!
<?php
}
else
{
if (isset($_POST['password']) || $password == "") {
print "<p align=\"center\"><font color=\"red\"><b>Wrong Password !!!</b><br>Please enter the correct Password</font></p>";}
print "<form method=\"post\"><p align=\"center\"><b>Please enter the Password</b><br/><br/>";
print "<b>Password </b><input class=\"box\" name=\"password\" type=\"password\" maxlength=\"10\"><input class=\"button\" value=\"Download\" type=\"submit\"></p></form>";
}
?>
use an array of passwords. btw
== and === is vulnerable to timing attacks, use hash_equals instead, but even hash_equals is vulnerable to timing attacks if the length of the 2 inputs is not equal, so hash the passwords before comparing them, to pad the length. something like
$authed=false;
if (isset($_POST["password"])){
$passwords=array('pass1','pass2','pass3');
$u=hash('md5',(string)$_POST["password"],true); // using a weak (and fast) CS hash is not a problem, because we're only using it to pad the length so we're not vulnerable to a timing attack.
foreach($passwords as $pass){
if(hash_equals($u,hash('md5',$pass,true))){
$authed=true;
break;
}
}
}
// here $authed is true if a correct password was supplied
once try:
$password = "anything";
$password = $password . "mypass";
//anythingmypass
if (isset($_POST["password"]) && $_POST["password"] != $password) {
print '<p align="center"><font color="red"><b>Wrong Password !!!</b><br>Please enter the correct Password</font></p>';
} else if (isset($_POST['password']) && $_POST['password']==$password) {
echo "password correct";
}
print '<form method="post"><p align="center"><b>Please enter the Password</b><br/><br/>';
print '<b>Password </b><input class="box" name="password" type="password" maxlength="' . strlen($password).'"><input class="button" value="Download" type="submit"></p></form>';
I think you want to do this
$passwordList = ['password','secretPassword','anything'];
if (isset($_POST["password"]) && in_array($_POST["password"], $passwordList)) {
// do protected stuff here
}
BUT. THERE IS A BIG BUT
NEVER EVER STORE PASSOWRDS IN CODE. Use a database for this.
I recommend you to follow there tutorials from Laracasts to get more familiar with PHP
Related
I know this has to be a common question, but I can't find the answer.
I'm using PHP's password_verify. If the password contains "&" it won't verify. Without the "&" it does. What do I need to do to escape the character?
<?php
$password_entered = "Password&";
$stored_secret = '$2y$12$oG8A4pbZSfQFxBQ0cHcJTuJ1h7wzzhlMnqjhnurN4.0/AfS/Wp9W2';
if (password_verify($newstr, $stored_secret))
{
echo "Right\n";
}
else
{
echo "Wrong\n";
}
?>
Firstly ignoring that $newstr is not set and you meant $password_entered instead.
It looks like your running htmlentities/htmlspecialchars on the user input, (which you are not showing), so it's breaking it.
The following matches your hash: Password&.
<?php
$password_entered = "Password&";
$stored_secret = '$2y$12$oG8A4pbZSfQFxBQ0cHcJTuJ1h7wzzhlMnqjhnurN4.0/AfS/Wp9W2';
if (password_verify($password_entered, $stored_secret)) {
echo "Right\n";
} else {
echo "Wrong\n";
}
?>
https://3v4l.org/SjfRG
I have literally done extensive research on the above topic and it's since been futile. The only available results i have been able to get is specifying arrays of password in cases where you have variety of users, so that if they enter any of the password in the arrays, they are granted access to the protected content. I have also come across using a single password to protect a file.
But what I need to complete the project am working on is PROTECTING A PHP PAGE from a single user using four different passwords, i.e when the user inputs the first password, it requests for the second which inturns request for the third and the third requests for the fourth before access is granted to the required content.
Thanks in anticipation.
Am new to php.
To be more specific, i have this below line of code which protects the page or content with a single password
<?php
$password = "ABACLB102"; // Modify Password to suit for access, Max 10 Char. ?>
<?php
// If password is valid let the user get access
if (isset($_POST["password"]) && ($_POST["password"]=="$password")) {
?>
Hidden Content
Hidden Content goes here
<?php
}
else
{
// Wrong password or no password entered display this message
if (isset($_POST['password']) || $password == "") {
print "<p align=\"center\"><font color=\"red\"><b>Incorrect Code entered</b><br>Please enter the correct code or contact Administrator</font></p>";}
print "<form method=\"post\"><p align=\"center\"><h2>Please enter code to intiate transfer</h2><br>";
print "<input name=\"password\" type=\"password\" size=\"25\" maxlength=\"10\"><input value=\"Authenticate\" type=\"submit\"></p></form>";
}
?>
But i need to protect the page with Four different password, so if the user enters the first one, it requests for another till all four are enter before hidden content is displayed.
If I understand correctly, user has to enter 4 different passwords, so you can use session to remember each stage like followings:
<?php
session_start();
$error = false;
if (!isset($_SESSION['login'])) {
$stage = (isset($_SESSION['stage']))? $_SESSION['stage'] : 0;
$stage_labels = array(
'First',
'Second',
'Third',
'Final'
);
$passwords = array(
'111',
'222',
'333',
'444'
);
if (isset($_POST['password']) && $_POST['password'] == $passwords[$stage]) {
if ($stage == 3) {
// if the final password matches, create a session variable for login
$_SESSION['login'] = 'loggedin';
header('location: ' . $_SERVER['PHP_SELF']);
exit();
} else {
// if password matches the respective stage, increase the value of stage by 1 to move on to next stage
$_SESSION['stage'] = $stage + 1;
header('location: ' . $_SERVER['PHP_SELF']);
exit();
}
} elseif (isset($_POST['password'])) {
$error = true;
// if form submitted with mismatch password, stage will restart from 0 again
print '<p align="center"><font color="red"><b>Incorrect Code entered</b><br>Please enter the correct code or contact Administrator</font></p>';
$_SESSION['stage'] = 0;
}
if (!$error) {
print '<p>Please enter your '. $stage_labels[$stage].' password</p>';
}
print '<form method="post"><p align="center"><h2>Please enter code to intiate transfer</h2><br>';
print '<input name="password" type="password" maxlength="10"><input value="Authenticate" type="submit"></p></form>';
} else {
echo 'You have logged in';
}
?>
I'm trying to understand what's went wrong with my code. it's a login proccess to cp. you do get the right outcome when writing the correct username (only username yet, just for that test). but you get nothing at all when you don't - nothing I've programmed it to do.
I'm REALLY desperate, tried to solve this the whole night. please help me.
here's the code.
calculations:
if (isset($_POST['connection_made'])) { // is a connection been made? using a hidden input
$form_user = forms_filter($_POST['form_user']); // filter any tags or any unwanted actions first
$form_pass = forms_filter($_POST['form_pass']); // filter any tags or any unwanted actions first
if (strlen($form_user) > 5 AND strlen($form_user) < 16 AND strlen($form_pass) > 5 AND strlen($form_pass) < 16) {
if (login_blank_filter($form_user, $form_pass) == true) { // are those values length shorter than the minimal value or longer?
$user_name = $form_user;
$raw_password = $form_pass;
$user_pass = password_hash($raw_password, PASSWORD_DEFAULT); // generating a hashed and salted password
$cp_validate_login = mysqli_query($data_connection, "SELECT * FROM `admins` WHERE `username` = '$user_name' ");
if (!$cp_validate_login) { die('error: ' . mysql_error()); }
while ($admin_row = mysqli_fetch_array($cp_validate_login)) {
if (mysqli_num_rows($cp_validate_login) == 1) {
echo "you made it.";
echo mysqli_num_rows($cp_validate_login);
}
else {
echo "not yet there.";
echo mysqli_num_rows($cp_validate_login);
}
}
}
else {
header('Location: index.php?login_status=2');
}
}
}
Form:
<?php
if (isset($_GET['login_status'])) {
switch ($_GET['login_status']) {
case 1:
echo "wrong username or password";
break;
case 2:
echo "the inputs has to be filled";
break;
case 3:
echo "username\passwords are too short or too long";
break;
default:
echo "unknown error";
}
}
else {
echo "welcome. log in to the control panel please";
}
?>
</div>
<form name="loginform" method="post" action="index.php" onSubmit="return validateBlank()">
<input type="hidden" name="connection_made" value="">
<div class="login_layout">
<div class="login_right_layout">
user:
</div>
<div class="login_left_layout">
<input class="login_input" name="form_user" type="text">
</div>
<div class="login_right_layout">
password:
</div>
<div class="login_left_layout">
<input class="login_input" name="form_pass" type="password">
</div>
</div>
<input type="submit" value="כניסה" class="login_submit">
</form>
</center>
PLEASE help me. thank you.
First, you are wide open to SQL injection. You need to use prepared statements, rather than concatenating variables into your query. See How can I prevent SQL injection in PHP?.
Second, your code fails because you never make it into the while loop if the username is invalid. That is, if you type a bogus username, this condition is never satisfied:
while ($admin_row = mysqli_fetch_array($cp_validate_login))
So, your if/else logic is never executed.
The solution here is not to try to improve your existing code. It's to stop what you're doing and use an existing authentication (login) library. Security is hard, and proper authentication and authorization is no exception. You should not roll your own security code.
I hope you are doing great. I have within my project a login functionality. when I try to login. It gives me this strange error that I did not write within my login.php script. I wrote it somewhere else and did not make an import to it. I hope you guys can help me identify the problem.
Thanks in Advance. Cheers,
Some useful pieces of my code:
Login.php Script:
<?php
include_once 'Header.php';
?>
<style>
#container {
height: 92vh;
}
</style>
<div id="container">
<br>
<?php
$_SESSION['logged'] = null;
//in this page we do things slightly differently - the code for validation and displaying messages is done
//before we display the form
echo '<div id = "div_1"><h1>Login</h1>';
//display the form
echo '<div id="div_2"><div id="div_2">
<form action="Login.php" method="post">
<label>Email<br>
<span class="small">enter your Email</span>
</label>
<input type="text" name="Email" value=""/>
<label><br>Password<br>
<span class="small">enter your password</span>
</label>
<input type="password" name="Password" />
<button type="submit" name="submit" value="Login" />Log in</button>
<input type ="hidden" name="submitted" value="1">
</form>
</div>
</div>';
if (isset($_POST['submitted'])) {
//require_once is similar to 'include' but ensures the code is not copied multiple times
require_once('LoginFunctions.php');
$name3 = $_POST['Email'];
$pwd3 = $_POST['Password'];
echo $name3;
echo $pwd3;
//list() is a way of assigning multiple values at the same time
//checkLogin() function returns an array so list here assigns the values in the array to $check and $data
list($check, $data) = checkLogin($_POST['Email'], $_POST['Password']);
if ($check) {
setcookie('FName', $data['FName'], time() + 900); //cookie expires after 15 mins
setcookie('LName', $data['LName'], time() + 900);
//
//use session variables instead of cookies
//these variables should now be available to all pages in the application as long as the users session exists
$_SESSION['FName'] = $data['FName'];
$_SESSION['LName'] = $data['LName'];
$_SESSION['Email'] = $data['Email'];
//to enable $_SESSION array to be populated we always need to call start_session() - this is done in header.php
//print_r is will print out the contents of an array
print_r($_SESSION);
//
//Redirect to another page
$url = absolute_url('Index.php'); //function defined in Loginfunctions.php to give absolute path for required page
$_SESSION['logged'] = TRUE;
echo $_SESSION['logged'];
//this version of the header function is used to redirect to another page
echo "<script>setTimeout(\"location.href = '" . $url . "';\",10000);</script>"; //since we have entered correct login details we are now being directed to the home page
exit();
} else {
$errors = $data;
}
}
//create a sopace between the button and the error messages
//echo'<div class="spacer"></div>';
if (!empty($errors)) {
echo '<br/> <p class="error">The following errors occurred: <br />';
//foreach is a simplified version of the 'for' loop
foreach ($errors as $err) {
echo "$err <br />";
}
echo '</p>';
}
//this is the end of the <div> that contains the form
echo '</div>';
/* */
?>
</div>
<?php
include 'Footer.php';
?>
My loginFunctions.php class:
<?php
function absolute_url($page = 'Index.php')
{
//header('Location: http:\\localhost');
//exit(); //terminates the script
$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
$url = rtrim($url, '/\\');
$url .= '/' . $page;
return $url;
}
function checkLogin($Email = '', $password = '')
{
$errors = array();
if(empty($Email))
$errors[] = 'You must enter a Email';
if(empty($password))
$errors[] = 'You must enter a password';
if(empty($errors))
{
////set up database econnection
include 'DBConn.php';
$db = new DBConn();
$dbc = $db->getDBConnection();
$q = "select Email, FName, LName from Users_1 where Email = '$Email' and Password = '$password'";
$r = mysqli_query($dbc, $q);
if($r)
{
if(mysqli_affected_rows($dbc) != 0)
{
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
return array(true, $row);
}
else
{
$errors[] = 'Passwords do not match';
}
}
else{
echo '<p class="error"> Oh dear. There was a database error</p>';
echo '<p class = "error">' . mysqli_error($dbc) .'</p>';
}
}
return array(false, $errors);
}
?>
mysqli_affected_rows is used for returning rows affected by insert, update and delete operation. For select statement you must use mysqli_num_rows
if($r) {
if(mysqli_num_rows($r) != 0){
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
return array(true, $row);
}else {
$errors[] = 'Passwords do not match';
}
}
For better security: you can use password_hash() function to make your password stronger and later match the hash you saved in the field (Password- datatype would be varchar with a length of 255). You match this hash using password_verify() function which has two parameters: the string that user typed and the hash saved in the database.
For example:
echo password_hash("rasmuslerdorf", PASSWORD_DEFAULT)."\n";
will print:
$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a
When a user login using rasmuslerdorf as password, you query the database and match the stored hash password $2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a with rasmuslerdorf using password_verify :
$q= mysqli_query($dbc, "SELECT Password FROM `Users_1`
WHERE `Email` = '$Email' and `Password` = '$password'");
$res = mysqli_fetch_assoc($q);
$hash = $res['Password'];
if (password_verify('rasmuslerdorf', $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
This is a fairly non-technical answer but it contains my advice based on my own experience.
When I was just learning html and had no real idea about php or javascript, I would spend hours trying to figure out how logins worked.
After a while I found out about php and javascript, and I had a friends php login script to go on.
I managed to get a database working, however the signup did not which is why I posted this question.
Eventually I got the login working, however my limited knowledge meant that I could have been storing peoples (and friends) private information such as passwords that they use elsewhere, on a website that could have had a major flaw.
Now don't get me wrong, I am not saying don't do this I am simply saying DO YOUR RESEARCH. Take time watching videos like this:
https://www.youtube.com/watch?v=8ZtInClXe1Q
How NOT to Store Passwords! - Computerphile
and then spend some more time doing database queries that don't involve passwords.
Once you have a good understanding of how to use queries and feel confident doing them, begin researching hashing methods in php.
Please take a look into:
Salting your passwords where you essentially add random
characters to the password that is being hashed so that you cant use
a hashing table to reverse a hashed password.
SQL Injection where people use the input (name field or any other field) on your form to change the syntax of your question, and essentially add code to your website. This is dangerous because then they can (depending on what permissions the user has) drop tables, drop databases, select *, and many other harmful things. This topic is also mentioned in the video mentioned before about "How NOT to Store Passwords!".
Do more research (don't only use that link it does not contain everything)...when you are storing peoples information you can never be too safe. Don't think of these tips as overkill, think of them as a responsibility to your users, that they can TRUST that nothing will happen to their password!
Good luck!
I am making a login system and I have a form with some validation.
However my form seems to be failing to pass the validation even though the data input should pass easily.
See:
http://marmiteontoast.co.uk/fyp/login-register/index.php
When you input a username, it should be over 3 characters. But even if you enter one really long you get the error message: The username is less than 3 characters.
EDIT: There was an issue in my copying from formatting that caused a missing }. I've corrected this. It wasn't the issue.
This is the if statement for the username pass. So it seems like it is not getting past the first test:
if (isset($_POST['username'])){
$username = mysql_real_escape_string(trim($_POST['username']));
$_SESSION['status']['register']['username'] = $username;
if(strlen($username) > 3){
if(strlen($username) < 31){
if(user_exists($username) === true){
$_SESSION['status']['register']['error'][] = 'That username is already taken. Sorry, please try again with a different username.';
}else{
// passed
}
} else {
$_SESSION['status']['register']['error'][] = 'The username is greater than 30 characters.';
}
} else {
$_SESSION['status']['register']['error'][] = 'The username is less than 3 characters.';
}
} else {
$_SESSION['status']['register']['error'][] = 'The username is not entered.';
}
And this is the HTML for the username:
<form method="post" action="register.php">
<div class="username">
<label class="control-label" for="inputUser">Username</label>
<input type="text" id="inputUser" name="username" placeholder="Username" value="<?php echo $usern_value; ?>" />
</div>
You can see the site here: http://marmiteontoast.co.uk/fyp/login-register/index.php
Session
The index page does use sessions.
It starts with this:
<?php
session_start();
?>
And kills the session at the end of the file:
<?php
unset($_SESSION['status']);
?>
But in the file it starts new sessions which store the inputs. This is so if you make a mistake, it still holds your info so you can adjust it rather than having the fill in the form again. Here is an example of where it grabs the username and saves it, then outputs it.
<?php
if(isset($_SESSION['status']['register']['username'])){
$usern_value = $_SESSION['status']['register']['username'];
} else {
$usern_value = "";
}
?>
value="<?php echo $usern_value; ?>" />
This is the user-exists function:
function user_exists($username){
$sql = "SELECT `id` FROM `users` WHERE `username` = '".$username."'";
$query = mysql_query($sql);
$result = mysql_num_rows($query);
if($result == 1){
// username does already exist
return true;
}else{
// username doesn't exist in the database
return false;
}
}
Ah, I can see the problem from your website link. When the error pops up ("The username is less than 3 characters."), try refreshing your browser. I expected to receive a browser warning that says the data would be resubmitted to the server — because you are in a post form — but I did not.
So, what does this mean? It means that immediately after validation failure, you are redirecting back to the same screen, and — unless you are using a session to preserve this information — your $_POST data will be lost. Commonly in the case of validation failure with this sort of form, you must prevent that redirect and render inside the post operation, which keeps the user's input available to you. The redirect should only occur if the form input was successful (i.e. it saves to the data and/or sends an email).
Edit: I should have seen the $_SESSION in the original post. OK, so the strategy is to write things to the session, redirect regardless of validation outcome, and to save error messages to the session. I wonder whether you are not resetting the session errors array when you're posting the form? Immediately after your first if, try adding this:
if (isset($_POST['username'])){
$_SESSION['status']['register']['error'] = array(); // New line
Unless you have something to make the session forget your errors, they will be stored until you delete your browser's cookie.
You have missed a closing brace } on this line:
if(user_exists($username) === true){
} else{// **missed the closing brace before the else**
// passed
}
Why is your logic so complex?
if (strlen($username) < 3) {
// too short
} elseif (strlen($username) > 31) {
// too long
} elseif (true === user_exists($username)) {
// already registered
} else {
// passed
}