PHP basic form validation - php

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;
}

Related

Php code executing the error line while fetching data for a login page

<?php
session_start();
include_once 'dbconnect.php';
if (isset($_SESSION['user']) != "") {
header("Location: home.php");
}
if (isset($_POST['btn-login'])) {
$email = mysql_real_escape_string($_POST['email']);
$upass = mysql_real_escape_string($_POST['pass']);
$res = mysql_query("SELECT * FROM telecomt_user WHERE email='$email'");
$row = mysql_fetch_array($res);
if ($row['password'] == md5($upass)) {
$_SESSION['user'] = $row['user_id'];
header("Location: home.php");
} else {
?>
<script>alert('wrong details');</script>
<?php
}
}
?>
This is my code for fetching data from database to let the user to log in by email and password. My table name is "telecomt_user".
<form method="post">
<table align="center" width="30%" border="0">
<tr>
<td><input type="text" name="email" placeholder="Your Email" required /> </td>
</tr>
<tr>
<td><input type="password" name="pass" placeholder="Your Password" required /></td>
</tr>
<tr>
<td><button type="submit" name="btn-login">Sign In</button></td>
</tr>
<tr>
<td>Sign Up Here</td>
</tr>
</table>
</form>
And this my html form code. The code works fine in localhost but when I uploaded it to my server it does not work. It always executes this line:
<script>alert('wrong details');</script>
Is it problem in my database? But I am using the same name and pattern what I used in my localhost and also my sign up form works with the same database. My "dbconnect.php" file is also okay. What is the problem?
instead of $row['password'] , can you try to type the column of the password in the string, for example $row[0] (if password column is the first column).
I think you have to put break point in each condition like
if(your condition){
echo "something";exit;
}else{
echo "nothing";exit;
}
Better to do checking on query only email and password
$res=mysql_query("SELECT * FROM telecomt_user WHERE email='$email' AND password='md5($upass)'");
$row=mysql_fetch_array($res);
Now condition login or not
if(count($row)>=1){
//login
}else{
// credentials wrong message
}

Form validation unable to redirect page in PHP

i got some problem regarding form validation using PHP. I have done some research on google, the problem is I seem can't to redirect user after login using <?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> in form action, it keep staying on index.php page instead going to other page.
Form
<?php
$usernameErr = $passwordErr = "";
$username = $password = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["username"]))
{$usernameErr = "Username is required.";}
else
{$username =($_POST["username"]);}
if (empty($_POST["password"]))
{$passwordErr = "Password is required.";}
else
{$password =($_POST["password"]);}
}
?>
<body>
<form id="login" name="login" method="post" action="checklogin.php">
<table>
<tr>
<td>Username</td>
<td></td>
<td><input name="username" type="text" id="username"><span class="error"><?php echo $usernameErr;?></span></td>
</tr>
<tr>
<td>Password</td>
<td></td>
<td><input name="password" type="password" id="password"><span class="error"><?php echo $passwordErr;?></span></td>
</tr>
<tr>
<td colspan="3" align="center"><input type="submit" name="submit" value="Login"></td>
</tr>
</table>
</form>
Or do I put it on wrong page? Should I put it on checklogin.php?
Your not redirecting by echo statement.Use header() for redirection.like header("Location:index.php");
For details about header visit the link.
The form validation logic does belong to checklogin.php. You pointed your <form> to send its data to checklogin.php, but you are doing the actual validations in index.php.
ye. you need to put it in checklogin.php page.
and also make change like
if (isset($_REQUEST['submit']))
{
if (empty($_POST["username"]))
{
echo $usernameErr = "Username is required.";}
elseif (empty($_POST["password"]))
{
echo $passwordErr = "Password is required.";}
else
{
echo $password =$_POST["password"];
echo $username =$_POST["username"];}
}
?>

PHP Find password in foreach loop

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.

Login page that gives error messages and submits to self

im currently stuck trying to create a log in form that submits to its self so that if theres any errors they'll be displayed above the login form rather than being sent to another page. Also if the login is successful then they're sent to the desired page. Here's my code below, I appreciate any help, Thanks!
<?php
if ((isset($_REQUEST['username'])) && (isset($_REQUEST['password']))) {
$adminusername = $_POST["username"];
$adminpassword = $_POST["password"];
if ($adminusername == '' || $adminpassword == '') {
echo "<b>You must complete all sections</b><br/>";
}
$query = mysql_query("SELECT * FROM admin WHERE username = '$adminusername' AND password = '$adminpassword'");
$numrows = mysql_num_rows($query);
if ($numrows != 0) {
while ($row = mysql_fetch_assoc($query)) {
$dbusername = $row['username'];
$dbpassword = $row['password'];
}
if ($adminusername == $dbusername && ($adminpassword == $dbpassword)) {
$_SESSION['username'] = $adminusername;
header("Location: admin.php");
}
} else {
echo " ($error) Username and password do not match";
}
}
?>
<h3>Admin Login</h3>
<form name="login" action="<?= $SERVER['PHP_SELF'] ?>" method="POST">
Username: <input type="text" name="username"><br/>
Password: <input type="password" name="password"><br/><br/>
<button type="submit">Log In</button>
</form>
I've indented your code so you can see the structure more clearly.
If the username and password are blank then an error will be output, but the database will still be queried.
You're not checking whether the database query actually works. You should check $query is not false, and if it is report an error.
You're checking the username and passwords match twice (once in the SQL and once again later), this is overkill, and besides you're not reporting if the second check fails.
header() will only work if you've not sent any output yet... if there's anything output before the code you've shown, even a blank line outside of PHP, then the header won't work.
On its own, this works for me (sql injection potential aside):
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$adminusername = $_POST["username"];
$adminpassword = $_POST["password"];
if ($adminusername == '' || $adminpassword == '') {
echo "<b>You must complete all sections</b><br/>";
} else {
$sql = "SELECT * FROM admin WHERE username = '$adminusername' AND password = '$adminpassword'";
$query = mysql_query($sql);
if ($query === false) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($query) > 0) {
$_SESSION['username'] = $adminusername;
header('Location: /admin.php');
exit;
}
echo "<b>Username and password do not match</b><br/>";
}
}
?>
<h3>Admin Login</h3>
<form name="login" action="<?= $_SERVER['PHP_SELF'] ?>" method="POST">
Username: <input type="text" name="username"><br/>
Password: <input type="password" name="password"><br/><br/>
<button type="submit">Log In</button>
</form>
To submit a <form>, you need a submit button; you've got:
<button type="submit">Log In</button>
try:
<input type="submit" value="Log In" />
I don't think you're currently submitting the form, so nothing will happen when you click submit.
instead of
header("Location: admin.php");
try java script
echo "<script>window.location = 'admin.php';</script>
if you have already outpu to the page header wont work
My solution echos the form with the error below it within a div. I'm still learning but I hope it helps someone.
<div>
<?php
//make sure the form action='' is set to itseslf
echo "
<form action='self_page_name' method='post'>
<table>
<tr>
<td>UserName:</td>
</tr>
<tr>
<td><input type='text' name='username' required='required' /></td>
</tr>
<tr>
<td>Password: </td>
</tr>
<tr>
<td><input type='password' name='password' required='required' /></td>
</tr>
<tr>
<td><input type='submit' name='submit' value='Login' /></td>
</tr>
</table>
</form>
";
//////////your php validation script here////////////
?>
</div>

PHP - Login form not working in IE8

I've just uncovered a rather annoying IE8 problem affecting a login page I'm working with. The login form is working correctly in FF (3.6 - MAC & PC), Chrome, Safari but does the equivalent of a refresh when you submit the UN/PW in IE8. No error, just a blank form looking me in the face.
PHP code on the login page:
<?php
define('INCLUDE_CHECK',true);
include 'includes/connect.php';
session_name('tzLogin');
session_set_cookie_params(2*7*24*60*60);
session_start();
if($_SESSION['id'] && !isset($_COOKIE['tzRemember']) && !$_SESSION['rememberMe'])
{
$_SESSION = array();
session_destroy();
}
if(isset($_GET['logoff']))
{
$_SESSION = array();
session_destroy();
header("Location: login.php");
exit;
}
if($_POST['submit']=='Login')
{
$err = array();
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'Sorry, all the fields must be completed.';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
$row = mysql_fetch_assoc(mysql_query("SELECT id,usr,permission,fullName FROM adidas_members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if($row['usr'])
{
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$_SESSION['fullName'] = $row['fullName'];
$_SESSION['permission'] = $row['permission'];
$_SESSION['rememberMe'] = $_POST['rememberMe'];
setcookie('tzRemember',$_POST['rememberMe']);
}
else $err[]='Opps, wrong username and/or password.';
}
if($err)
$_SESSION['msg']['login-err'] = implode('<br />',$err);
header("Location: dashboard.php");
exit;
}
else {
}
$script = '';
?>
Login related code on the 'dashboard' (landing) page:
<?php
session_name('tzLogin');
session_set_cookie_params(2*7*24*60*60);
session_start();
error_reporting(E_ALL^E_NOTICE);
define('INCLUDE_CHECK',true);
include 'includes/connect.php';
if(isset($_GET['logoff']))
{
$_SESSION = array();
session_destroy();
header("Location: login.php");
exit;
}
?>
Finally, the form code:
<form action="" method="post" class="contactForm" id="loginForm">
<?php
if($_SESSION['msg']['login-err'])
{
echo '<div class="error">'.$_SESSION['msg']['login-err'].'</div>';
unset($_SESSION['msg']['login-err']);
}
?>
<table class="loginTable" cellspacing="0">
<tr>
<th width="50"><label for="username">Username:</label></th>
<td><input type="text" name="username" id="username" class="validate[required] textBox" /></td>
</tr>
<tr>
<th><label for="password">Password:</label></th>
<td><input type="password" name="password" id="password" class="validate[required] textBox" /></td>
</tr>
<tr>
<th></th>
<td style="padding-top:5px;"><input type="image" src="images/button_login.gif" alt="Login" name="submit" value="Login" /><span class="remember"><input name="rememberMe" id="rememberMe" type="checkbox" checked="checked" value="1" />Remember me</span></td>
</tr>
</table>
</form>
The only thing I can think of/find is that IE8 doesn't handle cookies very well. That said, I checked to see what cookies are being set and I'm told that tzLogin is (with an expiry date which is ages away).
Note: My login page is based off this > http://tutorialzine.com/2009/10/cool-login-system-php-jquery/
Hoping someone can help with this frustration!
rrfive
IE is not passing submit=Login only passing the coordinates for your image button (submit.x and submit.y values).
Store a hidden input instead:
<input type="hidden" name="submitaction" value="Login" />
And in your PHP code:
if($_POST['submitaction']=='Login')

Categories