php log in form with messages and date and time - php

I am trying to create a php log in form. I want to just make a few adjustments but when i've tinkered with it, it stops working...
If you can't see from the code, I'm trying to create a (mock) log in form that asks for a username and password.
I want any blank textbox to show a red message to the right of the textbox. (i have the red error message, but I can't get it to the left of the box)
I want a sticky form that keeps either field if its filled in (again, I think I have this set up but don't think its working all the way)
I would like a person who enters the username: user and the password: abc123 to see a welcome message. If you don't use that username/password combo I want a message that says that they are not authorized. (This is what i really don't know how to do)
I want this all in a redux (also think i have that working but not 100% sure)
Any help would be greatly apprecaited!!
And here is my code:
<?php
define('TITLE', 'LOG IN');
// CSS
print '<style type="text/css" media="screen">
.error { color: red; }
</style>';
// Checking
if ( isset($_POST['submitted']) ) {
$problem = FALSE;
// Each value
if (empty($_POST['email'])) {
$problem = TRUE;
print '<p class="error">Please enter the username!</p>';
}
if (empty($_POST['password1'])) {
$problem = TRUE;
print '<p class="error">Please enter the password!</p>';
}
if (!$problem) { //No problem
// Printing the log in message
print '<p>Thank you for logging in!</p>';
$_POST = array();
} else {
print '<p class="error">No entry!</p>';
}
}
?>
<form action="login.php" method="post">
<p>"Username": <input type="text" name="username" size="20" value="<?php if (isset($_POST['username'])) { print htmlspecialchars($_POST['username']); } ?>" /></p>
<p>Password: <input type="password" name="password1" size="20" /></p>
<p><input type="submit" name="submit" value="Log in" /></p>
<input type="hidden" name="submitted" value="true" />
</form>

Ok, here is a simple login that is not meant for real world usage. Please read the comments included in the code to see what I have to say about each. Doing logins is quite tricky for a number of reasons, so this example is not meant to demonstrate a real world working codebase, but a very simple username/password check.
The security issues associated with a more sophisticated use are perhaps beyond this answer, but the below code is the way I would interpret what you have posted above, without getting to detailed (to the point of possibly making it hard to understand the simplest steps occurring).
Let me know if you have any questions. To see the form in action, check:
http://jfcoder.com/test/simplelogin.php
Also, I use PHP's HEREDOC syntax instead of quoted strings for simplicity. To read more about this sometimes handy form, see
http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc.
<html>
<head>
<style type="text/css">
.error {
color: red;
}
</style>
</head>
<body>
<?php
// Note, in most cases you will set a SESSION variable
// of $_SESSION['loggedin'], which would require you to
// use session_start() before you access any session
// variables.
// Note, this defaults to false.
$loggedin = false;
// If I get an error, I will put it in this variable.
$error = '';
// If the username is provided, run the code. Otherwise,
// act as if the login form was not submitted. This makes
// a hidden `submitted` value superfluous, and guarantees
// your users at least provide a username.
if ($_POST['username']) {
// NOTE!!! In mose cases, you're querying a database
// for a username/password match. In PHP, this often
// means a MySQL query. DO NOT USE THE BELOW IF YOU
// ARE DOING SO!!! This will allow what's called a
// SQL injection. You MUST wash your data with something
// like mysql_real_escape_string() for the $_POST
// values (NEVER trust submitted data, always validate
// and escape as necessary), or use the PHP PDO library.
// In this example, though, I use a switch to check the
// values for exact matches, which means I do not need
// to escape (and mysql_real_escape_string() requires
// a database connection to use).
$username = $_POST['username'];
$password = $_POST['password'];
// Here, I check if the username and password match.
// This is, of course, hardcoded, but to match your
// attempt, I chose to keep the form, although you
// rarely see this in use in the real world.
switch ($username) {
// My one case. For each additional user, you
// would need to add a new entry with password
// check. And I set my error text according to
// the result of the code.
case 'user':
if ($password === 'abc123') {
$loggedin = true;
} else {
$error = 'Username/Password did not match.';
}
break;
default:
// Note, I don't give a descriptive error
// here. If someone reports this error, I
// know what may have gone wrong, but the
// user is not told the username does not
// exist.
$error = 'Unknown error. Try again.';
}
}
// I will only show the welcome message if the user has
// successfully logged in.
if ($loggedin === true) {
echo <<<HTML
<h1>Welcome!</h1>
<p>Thank you for logging in $username</p>
HTML;
} else {
// If an error text is set, display that error.
if ($error != '') {
$error = "<h4>Login error</h4><p class='error'>$error</p>";
}
// Here's my form, only shown if the user has not
// successfully logged in (note, this is only a one-
// time check when the POST data is submitted; I
// would need to use sessions to "remember" the requestor
// had logged in across page accesses.
echo <<<FORM
<h1>Login Form</h1>
<form action="simplelogin.php" method="POST">
$error
<p><label>Username: <input type="text" name="username"/></label></p>
<p><label>Password: <input type="password" name="password"/></label></p>
<p><input type="submit" value="Login"/> <input type="reset"/></p>
</form>
FORM;
}
?>
</body>
</html>

Here's my full code. I pretty much rewrote the whole thing, so I appologize if the coding style differs too much:
<?php
// Output our CSS code
echo '<style type="text/css" media="screen">
.error
{
color: red;
}
</style>';
// Define our variable
$problem = false;
// Check if the form has been submitted
if (isset($_POST['submitted']))
{
// If either user or password are empty, we have a problem
if (empty($_POST['username']) || empty($_POST['password']))
{
$problem = TRUE;
}
// If there is no problem, username is user, and password is abc123, we're good
if (!$problem && $_POST['username']=='user' && $_POST['password']=='abc123') {
// Print our login message
echo 'Thank you for logging in!<br />';
}
// Ok, there's either a problem or the username or password is wrong, so no entry for them
else
{
echo '<p class="error">No entry!</p>';
}
}
?>
<form action="login.php" method="post">
Username: <input type="text" name="username" size="20" value="<?php
if (isset($_POST['submitted']) && !empty($_POST['username']))
{
echo $_POST['username'];
} ?>" />
<?php
if (isset($_POST['submitted']) && empty($_POST['username']))
{
echo '<span class="error">Please enter a username!</span>';
}
?>
<br />Password: <input type="password" name="password" size="20" value="<?php
if (isset($_POST['submitted']) && !empty($_POST['password']))
{
echo $_POST['password'];
} ?>" />
<?php
if (isset($_POST['submitted']) && empty($_POST['password']))
{
echo '<span class="error">Please enter the password!</span>';
}
?>
<br /><input type="submit" value="Log in" />
<br /><input type="hidden" name="submitted" value="true" />
</form>

Related

echo an error without redirecting to another page and keep all form data?

If for example a username isn't filled in the user is given an error stating so, but after pressing submit they're thrown to another page with the error.
How would I go around keeping the error on the same page as the registration form and keeping all the text entered by the user after submit?
Registration PHP:
<?php
require 'db_connect.php';
$count = 0;
if (isset($_POST['username']))
{
$username = $_POST['username'];
if (!empty($username))
{
$count++;
}
else
{
echo 'Please enter a username';
echo "<br>";
}
}
if (isset($_POST['email']))
{
$email = $_POST['email'];
if (!empty($email))
{
$count++;
}
else
{
echo 'Please enter an email';
echo "<br>";
}
}
if (isset($_POST['password']))
{
$password = $_POST['password'];
if (!empty($password))
{
$count++;
}
else
{
echo 'Please enter a password';
echo "<br>";
}
}
if(strlen($username) > 25)
header('Location: registration.php');
$hashword = password_hash($password,PASSWORD_DEFAULT);
if($count == 3 )
{
$query = "INSERT INTO member ( username, password, email)
VALUES ( '$username', '$hashword', '$email');";
header('Location: login.html');
}
else {
echo '<b>You will be redirected shortly</b>';
echo "<br>";
echo '<b>Please enter ALL details correctly</b>';
header( "refresh:5;url=registration.php" );
}
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
?>
Registration Form:
<!doctype html>
<html lang="en">
<head>
<title>Gumby template file</title>
<meta charset="utf-8" />
<script data-touch="gumby/js/libs" src="gumby/js/libs/gumby.min.js"></script>
<script src="gumby/js/libs/jquery-2.0.2.min.js"></script>
<link rel="stylesheet" href="gumby/css/gumby.css">
<script src="gumby/js/libs/modernizr-2.6.2.min.js"></script>
<link rel="stylesheet" href="forumhomepage_style.css">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
</head>
<body>
<form name="register" action="register.php" method="post">
<tr>
<td>Username: </td>
<td><input type="text" name="username" maxlength="25" /></td>
</tr>
<tr>
<td>Email: </td>
<td><input type="text" name="email" id="email" /></td>
</tr>
<tr>
<td>Password: </td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Register" /></td>
</tr>
</table>
</form>
</body>
</html>
It depends on at what level do you want to do this.
Validating that the different data is not empty and has information that makes sense (like the password is at least 7 chars long) can be done via javascript before sending the form data, this way you can stop the form to be sent. You can use jQuery Plugin Validator to help you do this.
But other validations like the insert has failed only can be done at server side, if you need also not to redirect in this case then you have to use ajax to load the data and then refresh the website info without reloading it.
I prefer to only do an initial check with javascript and send the user to the results page. But I also keep the validations as this one of the password length in the php because, even though now a days it's really strange, a user can disable javascript and I don't wana have surprises when checking the database values. But, another example, if you have lots of users you could check that the user does not exist to warn the user at the very first moment before the form is sent and this can only be done performing an ajax call.
You should know how to do both things and decide depending on what you want to do on your projects.
In your case, I would leave the php validations as they are now and check the same (non empty values) in javascript on the form submit event calling event.preventDefault() if an error has been detected.
$('form[name="register"]').submit(function( event ) {
if ($('input[name="username"]').is(":empty")) {
// append a "Username can not be empty message somewhere on your page
event.preventDefault();
}
// I let you finish the jquery code...
});
This example uses jQuery lib. but you can do it without it with just javascript if you want.
There are several ways to do this. The first step is using the required attribute in your input elements:
<input type="text" name="username" required>
This will force the user to at least put something inside the input element. Then there's Javascript or jQuery for client side validation. You can create a custom event handler to catch the form submit and validate the input like so:
document.getElementById("your_form_id_here").addEventListener("submit", function(e){
// Your Javascript validation code here, for example:
var x = document.forms["your_form_id_here"]["username"].value;
if (x == "") {
alert("Username must be filled out");
e.preventDefault();
}
});
You can also put the form handler on the same file as the form and display the errors / values in case something goes wrong. For example:
<?php
if(!empty($_POST['submit'])){
$error = false;
if($_POST['username'] === ''){
$usernameEmpty = 'The username was empty. Please enter a username!';
$error = true;
}
if(!$error){
// No errors found so proceed with the registration
}
}
?>
<form id="myForm" method="post" action="" accept-charset="utf-8">
<?php if(!empty($usernameEmpty)){ echo $usernameEmpty . '<br/>'; } ?>
Username: <input type="text" name="username" value="<?php if(!empty($_POST['username'])){ echo $_POST['username']; } ?>"/>
<input type="submit" name="submit" value="Register"/>
</form>
Lastly there's of course Ajax which will allow you to send the form towards PHP without reloading your page. You could have PHP send the errors back and use Javascript to show the errors inside the DOM.
without ajax you will need ro lead your page with some conditional logic. This will look and see if any fields are filled in and fill them in again, along with setting any error messages to return to the user.
something like:
<?php
//example fields
$username = '';
$field2 = '';
$field3 = '';
if(isset($errorToShow)){
// echo your error message here
}
if($_POST["submit"]){
foreach($_POST as $k=>$v){
$$k = $v;
}
}
// your form can be here.
of course there are other considerations and ajax is a better solution, but this type of thing can work just fine.
You may use ajax
Or if you don't know ajax
You can put all your code in one page and call $_POST indexes into the value of every input.
for ex.
<input type="text" name="username" maxlength="25" value="<?=$_POST['usename'];?>"/>
Or you may use "PHP $_SESSION"
Just store $_POST into $_SESSION
then call it from the html page
for ex.
<input type="text" name="username" maxlength="25" value="<?=$_SESSION['usename'];?>"/>
And the same idea for errors.

Hash a password in PHP before it goes to database, getting error

I had been researching a while and even got a hold of my hosting company for help but I have run into a problem with my PHP code and my database through my website. While the code that I have does hash the password that I enter, when I attempt to use the regular word password it comes up as incorrect. But if I copy and paste the hashed password, it works.
<?php
/* NEW.PHP
Allows user to create a new entry in the database
*/
// creates the new record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($email, $pass, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>New User</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<?php
// if there are any errors, display them
if ($error != '') {
echo '<div style="padding:4px; border:1px soluser_id red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<div>
<strong>Update User Info <br><br><br><br><br>Email: *</strong>
<input type="text" name="email" value="<?php echo $email; ?>" /><br/>
<strong>Password: *</strong> <input type="password" name="pass" value="<?php echo $pass; ?>" /><br/>
<p>* required</p>
<input type="submit" name="submit" value="Submit"> <br><br>Back to home?</div>
</form>
</body>
</html>
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit'])) {
// get form data, making sure it is valuser_id
$email = mysql_real_escape_string(htmlspecialchars($_POST['email']));
$pass = mysql_real_escape_string(htmlspecialchars($_POST['pass']));
// check to make sure both fields are entered
if ($email == '' || $pass == '') {
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($email, $pass, $error);
} else {
// save the data to the database
mysql_query("INSERT users SET email='$email', pass=MD5('$pass')")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
} else {
// if the form hasn't been submitted, display the form
renderForm('','','');
}
?>
As you can see it does hash it when I enter it into the database, but when I try to use the password the way it was originally spelled, it tells me it's the wrong one.
I would do the MD5 hashing on the PHP side. Print it before it goes into the database and try to compare it with the input given on the login form.
Also the htmlspecialchars is not needed in this case. Since your escaping is fine. If it would contain weird chars, it would match them against the database.
Also make sure your encoding type is set on both pages and make sure they're the same.
Without seeing your SELECT query in the login form I'd ask if you're MD5 hashing it when you select it as well?
mysql_query("SELECT * FROM users WHERE email='$email' AND pass=MD5('$pass')")
or die(mysql_error());
However, I agree that you shouldn't be using MD5 for password hashing. Check out http://php.net/manual/en/function.password-hash.php

PHP Server Side Form Validation.Empty Form fields are inserted into database

I am new to PHP and am trying to do Server Side Form Validation. There are two PHP files Login.php and Form.php. Registration is done in Login.php and Validation in Form.php. The idea is that Form.php will process the form data sent by Login.php
My problem: even if form fields are empty, the variables are still being inserted into the database.
I don't want to insert if its empty. Rather, it has to route back to Login.php with error messages stored as a session variable.
I have checked the Form fields using !isset() and empty in Form.php using an if..else clause. In the if..else clause you can find out if the form fields are empty, and if so, they must go the session variable clause (inside the if condition). Instead, it is going to the else condition and inserting the empty values in variables ('$username','$password','$phone','$mailid','$city') in to the database.
I have read previous questions for similar problem here and even checked Youtube for Server Side Validation. What did I do wrong? Is there a problem with the use of session variables. Kindly assist
Login.php:
<!Doctype HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href= "Form.css" />
<script src="Form.js" type="text/javascript"></script>
</head>
<body>
<?php
session_start();
$passworderr='';
if(isset($_SESSION["passworderr"])) {
$passworderr=$_SESSION["passworderr"];
}
?>
<div id="Outer">
<div id="left" >
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" name="form">
<p><label>Username</label> <input type="text" name="regusername" placeholder="Your name"/> </p>
<p><label>Password</label> <input type="text" name="regpassword" placeholder="Password"/> </p>
<input type="Submit" value="Login" />
</form>
</div>
<div id="right">
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" id="formm">
<p>*Username <input required name="username" type="text" /><?php //echo $usernameerr;?></p>
<p>*Password <input name="password" type="password" /> <?php echo $passworderr;?></p>
<p> *Phone <input name="phone" type="tel" /><?php //echo $phoneerr;?></p>
<p> *MailId <input name="mailid" type="email" /><?php //echo $mailiderr;?></p>
<p> *City <input name="city" type="text" /><?php //echo $cityerr;?></p>
<input type="Submit" value="Signup" />
</form></div></div></body></html>
Form.php:
<?php
session_start();
$dbservername='localhost';$dbname='mani';$dbusername='root';$dbpassword='';
$dbconn=mysqli_connect($dbservername,$dbusername,$dbpassword);
if(!$dbconn){
die("Connection failed:". mysqli_connect_error());
}
if(!isset($_POST["username"])) {
$_SESSION["usernameerr"]="UserName is required";
}
else{
$username=mysqli_real_escape_string($dbconn,$_POST["username"]);
}
if(!isset($_POST["password"])) {
$_SESSION["passworderr"]="Enter a password";
}
else{
$password=mysqli_real_escape_string($dbconn,$_POST["password"]);
}
if(!isset($_POST["phone"])) {
$_SESSION["phoneerr"]="Phone number is required";
}
else{
$phone=mysqli_real_escape_string($dbconn,$_POST["phone"]);
}
if(!isset($_POST["mailid"])) {
$_SESSION["mailiderr"]="Enter a valid mail id";
}
else{
$mailid=mysqli_real_escape_string($dbconn,$_POST["mailid"]);
}
if(!isset($_POST["city"])) {
$_SESSION["cityerr"]="Enter your resident city";
}
else{
$city=mysqli_real_escape_string($dbconn,$_POST["city"]);
}
$selected = mysqli_select_db($dbconn,"$dbname")
or die("Could not select examples".mysqli_error($dbconn));
if(isset($_POST["username"]) and isset($_POST["password"]) and isset($_POST["phone"]) and isset($_POST["mailid"]) and isset($_POST["city"]) )
{
$res=mysqli_query($dbconn,"Insert into user(username,password,phone,mailid,city) values('$username','$password','$phone','$mailid','$city')");
if($res)
{
header("location:Login.php");
}
}
else
{
print "Problem in inserting";
header("location:Login.php");
}
mysqli_close($dbconn);
?>
There are a bunch of ways to do this. A blank form field is present on the server side with an empty value. So in addition to checking if the variable is set, in your case you want to check if the value is non-empty.
One way to do that is to use the strlen function.
So an example for you is:
if(!isset($_POST["username"]) || strlen($_POST["username"]) == 0) {
NOTE: Do not use the empty function since the string "0" is considered 'empty'. Read the manual for other such cases.
You may want to consider using a helper function to do the determination. Basically something like this:
function DoesPostFormFieldHaveValue($formFieldName) {
return(
isset($_POST[$formFieldName])
&& strlen($_POST[$formFieldName]) > 0
);
}
First of all, session_start should always be the first line of the php page you need to use sessions on.
Also, I'm not sure why you are using so many session variables for storing errors. Instead of this, use a single session variable, declare it as array and store all the errors in it.
Here's your updated form :-
<?php
session_start();
if((isset($_SESSION['errors']))) //check if we have errors set by the form.php page
{
echo "Please fix the following errors";
foreach($_SESSION['errors'] as $error) //loop through the array
{
echo $error;
}
}
?>
<!Doctype HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href= "Form.css" />
<script src="Form.js" type="text/javascript"></script>
</head>
<body>
<div id="Outer">
<div id="left" >
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" name="form">
<p><label>Username</label> <input type="text" name="regusername" placeholder="Your name"/> </p>
<p><label>Password</label> <input type="text" name="regpassword" placeholder="Password"/> </p>
<input type="Submit" value="Login" />
</form>
</div>
<div id="right">
<form action="/DatabaseDrivenWebpage/Form.php" method="POST" id="formm">
<p>*Username <input required name="username" type="text" /><?php //echo $usernameerr;?></p>
<p>*Password <input name="password" type="password" /> <?php echo $passworderr;?></p>
<p> *Phone <input name="phone" type="tel" /><?php //echo $phoneerr;?></p>
<p> *MailId <input name="mailid" type="email" /><?php //echo $mailiderr;?></p>
<p> *City <input name="city" type="text" /><?php //echo $cityerr;?></p>
<input type="Submit" value="Signup" />
</form></div></div></body></html>
Backend processing file :-
<?php
session_start();
$_SESSION['errors'] = array(); //declare an array
$dbservername='localhost';$dbname='mani';$dbusername='root';$dbpassword='';
$dbconn=mysqli_connect($dbservername,$dbusername,$dbpassword);
if(!$dbconn){
die("Connection failed:". mysqli_connect_error());
}
if((!isset($_POST["username"])) || (empty($_POST['username']))) {
$_SESSION["errors"][]="UserName is required"; //push error message to array if $_POST['username'] is empty or is not set
}
else{
$username=mysqli_real_escape_string($dbconn,$_POST["username"]);
}
if((!isset($_POST["password"])) || (empty($_POST['password']))) {
$_SESSION["errors"][]="Enter a password";
}
else{
$password=mysqli_real_escape_string($dbconn,$_POST["password"]);
}
if((!isset($_POST["phone"])) || (empty($_POST['phone']))) {
$_SESSION["errors"][]="Phone number is required";
}
else{
$phone=mysqli_real_escape_string($dbconn,$_POST["phone"]);
}
if((!isset($_POST["mailid"])) || (empty($_POST['mailid']))) {
$_SESSION["errors"][]="Enter a valid mail id";
}
else{
$mailid=mysqli_real_escape_string($dbconn,$_POST["mailid"]);
}
if((!isset($_POST["city"])) || (empty($_POST['city']))) {
$_SESSION["errors"][]="Enter your resident city";
}
else{
$city=mysqli_real_escape_string($dbconn,$_POST["city"]);
}
$selected = mysqli_select_db($dbconn,"$dbname")
or die("Could not select examples".mysqli_error($dbconn));
if(count($_SESSION['errors']) < 1) //check if the the $_SESSION['errors'] count is less than 1 (0), this means there are no errors.
{
$res=mysqli_query($dbconn,"Insert into user(username,password,phone,mailid,city) values('$username','$password','$phone','$mailid','$city')");
if($res)
{
header("location:Login.php");
}
}
else
{
print "Problem in inserting";
header("location:Login.php");
}
mysqli_close($dbconn);
?>
The thing about isset is that it checks if the variable exists, and therefore allows variables that contain an empty string, like you have. When the current form is submitted without any user input, it is submitting a whole bunch of variables containing empty strings.
Now the solution is to change all your isset() to empty() and that should solve your problem!
[Note] There is no need to use both isset() and empty() like this:
if(!isset($_POST['fieldname']) && !empty($_POST['fieldname']))
because empty() is doing everything that isset() does.
check like this:
if(!isset($_POST["username"]) && $_POST["username"]!="")
Your PHP code is checking for isset only, I don't see any empty check. isset will be always true in your case to either of the forms, as the form fields are submitting - just the values are blank.
To prevent empty insertions, add a !empty check to your conditions. Your conditional statements should look like this -
if(!isset($_POST['fieldname']) && !empty($_POST['fieldname']))
first of all a little advice. If you want to start a new project, I would advice you learn how to use PDO connection to MySQL Databases, and not MySQLi. As PDO is much better method, and secured (especially when using prepared statements).
Anyway, as I can see you are storing the errors in a multiple $_SESISON variables, but after you are finishing the validation checks, you are not doing a correct if statement.
Instead of doing that:
if(isset($_POST["username"]) and isset($_POST["password"]) and isset($_POST["phone"]) and isset($_POST["mailid"]) and isset($_POST["city"]) )
Do something like this:
if(!isset($_SESSION['usernameerr']) && !isset($_SESSION['passworderr']) && !isset($_SESSION['phoneerr'] && !isset($_SESSION['mailiderr'] && !isset($_SESSION['cityerr'])))
Should work.
Another think I'm advising is to unset the sessions of the errors, in your case I would do that in the end of the Login.php page. Just in case, so there won't be any problems if you fix the form inputs and submit it again.
Another thing, based on the unset idea. If you will do this, it would be much more cleaner way to change the setting of the error sessions instead of:
$_SESSION['cityerr']
to:
$_SESSION['errors']['cityerr']
So afterwards, you can clean the specific form error session in one command, like that:
unset($_SESSION['errors']);
Hope it helped ;)
if(isset($_POST['field_name']))
{
$field_name=$_POST['field_name']
}else
{
unset($_POST['field_name'])
}

Injecting HTML produced by PHP

This may be a simple question for some of you but i've been investigating it for the last hour and couldn't find the answer. I have a simple login form/script that has the following structure;
<?php
PHP code here to check for token (if true) and then check the db for username and password
if the token is false display error message
?>
<HTML>
HTML logon form here that sets the token
</HTML>
Now if there is an issue with the logon, i.e the password is incorrect the php will output the error message, trouble is that it will echo the output at the top of the form. I'd like to be able to insert it at another point of the form. i have a vague idea that i could inject it into the html with something like {logon_error} but i don't know what method thats called or how to use it.
You can store the error message in a php variable , for e.g. $error_msg = "Error! ... ";
And display that wherever you want in the html page like this:
<html>
...
<body>
...
<span><?= $error_msg; ?>
</body>
</html>
Store the error message in a variable, and use it afterwards.
Here's a working example to help you understand:
<?php
if (isset($_POST['FormSubmit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if ($username === 'admin' && $password === 'hunter2') {
# success
} else {
$error = 'Invalid credentials';
}
}
?>
<html>
<div id="errorContainer">
<?php echo (isset($error)) ? $error : ''; ?>
</div>
<form action="" method="post">
Username: <input type="text" name="username" /> <br />
Password: <input type="text" name="password" /> <br />
<input type="submit" name="FormSubmit" value="Submit!" />
</form>
</html>
If you have multiple checks, and want different error messages to be output, then you could store the error messages in an array instead. Your validation code should look like:
if (condition) {
$error[] = '...'
}
elseif (condition) {
$error[] = '...'
}
else (condition) {
$error[] = '...'
}
And then, to output it in your HTML, you can use a foreach construct with the alternate syntax:
<div id="errorContainer">
<?php foreach($errors as $error): ?>
<p class="error-content">
<?php echo $error; ?>
</p>
<?php endforeach; ?>
</div>
Note that this is a very basic example and is just for demonstration purposes. You should never trust user input. Your original form should contain all the necessary validation and should not be just a couple of if statements.
You would have to store the message in the session or take a look at https://github.com/plasticbrain/PHP-Flash-Messages
the main idea is $error_mesage = 'your error mesage here';
loadView('your-view')->with($error_message);
It's really simple, if you give more information about what kind of framework you are working with we may be able to assist you further.
You can do like this:
PHP:
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["username"]))
{$userErr = "Username is required";}
}
HTML:
<span class="error">* <?php echo $userErr;?></span>
You can do whatever you like using <?php echo ""; ?> in php to call it on your html.

Easy way to password-protect php page

I have a page I want to password-protect. I've tried doing HTTP authentication, but for some reason it doesn't work on my hosting. Any other quick (and easy) way to do this? Thanks!
Not exactly the most robust password protection here, so please don't use this to protect credit card numbers or something very important.
Simply drop all of the following code into a file called (secure.php), change the user and pass from "admin" to whatever you want. Then right under those lines where it says include("secure.html"), simply replace that with the filename you want them to be able to see.
They will access this page at [YouDomain.com/secure.php] and then the PHP script will internally include the file you want password protected so they won't know the name of that file, and can't later just access it directly bypassing the password prompt.
If you would like to add a further level of protection, I would recommend you take your (secure.html) file outside of your site's root folder [/public_html], and place it on the same level as that directory, so that it is not inside the directory. Then in the PHP script where you are including the file simply use ("../secure.html"). That (../) means go back a directory to find the file. Doing it this way, the only way someone can access the content that's on the (secure.html) page is through the (secure.php) script.
<?php
$user = $_POST['user'];
$pass = $_POST['pass'];
if($user == "admin"
&& $pass == "admin")
{
include("secure.html");
}
else
{
if(isset($_POST))
{?>
<form method="POST" action="secure.php">
User <input type="text" name="user"></input><br/>
Pass <input type="password" name="pass"></input><br/>
<input type="submit" name="submit" value="Go"></input>
</form>
<?}
}
?>
This is a bit late but I wanted to reply in case anyone else came upon this page and found that the highest reply was a bit off. I have improved upon the system just a tad bit. Note, it is still not amazingly secure but it is an improvement.
First prepare your password salts file:
hash_generate.php:
<?php
$user = "Username"; // please replace with your user
$pass = "Password"; // please replace with your passwd
// two ; was missing
$useroptions = ['cost' => 8,];
$userhash = password_hash($user, PASSWORD_BCRYPT, $useroptions);
$pwoptions = ['cost' => 8,];
$passhash = password_hash($pass, PASSWORD_BCRYPT, $pwoptions);
echo $userhash;
echo "<br />";
echo $passhash;
?>
Take your output $userhash and $passhash and put them in two text files: user.txt and pass.txt, respectively. Others have suggested putting these text files away above public_html, this is a good idea but I just used .htaccess and stored them in a folder called "stuff"
.htaccess
deny from all
Now no one can peek into the hash. Next up is your index.php:
index.php:
<?php
$user = ""; //prevent the "no index" error from $_POST
$pass = "";
if (isset($_POST['user'])) { // check for them and set them so
$user = $_POST['user'];
}
if (isset($_POST['pass'])) { // so that they don't return errors
$pass = $_POST['pass'];
}
$useroptions = ['cost' => 8,]; // all up to you
$pwoptions = ['cost' => 8,]; // all up to you
$userhash = password_hash($user, PASSWORD_BCRYPT, $useroptions); // hash entered user
$passhash = password_hash($pass, PASSWORD_BCRYPT, $pwoptions); // hash entered pw
$hasheduser = file_get_contents("stuff/user.txt"); // this is our stored user
$hashedpass = file_get_contents("stuff/pass.txt"); // and our stored password
if ((password_verify($user, $hasheduser)) && (password_verify($pass,$hashedpass))) {
// the password verify is how we actually login here
// the $userhash and $passhash are the hashed user-entered credentials
// password verify now compares our stored user and pw with entered user and pw
include "pass-protected.php";
} else {
// if it was invalid it'll just display the form, if there was never a $_POST
// then it'll also display the form. that's why I set $user to "" instead of a $_POST
// this is the right place for comments, not inside html
?>
<form method="POST" action="index.php">
User <input type="text" name="user"></input><br/>
Pass <input type="password" name="pass"></input><br/>
<input type="submit" name="submit" value="Go"></input>
</form>
<?php
}
<?php
$username = "the_username_here";
$password = "the_password_here";
$nonsense = "supercalifragilisticexpialidocious";
if (isset($_COOKIE['PrivatePageLogin'])) {
if ($_COOKIE['PrivatePageLogin'] == md5($password.$nonsense)) {
?>
<!-- LOGGED IN CONTENT HERE -->
<?php
exit;
} else {
echo "Bad Cookie.";
exit;
}
}
if (isset($_GET['p']) && $_GET['p'] == "login") {
if ($_POST['user'] != $username) {
echo "Sorry, that username does not match.";
exit;
} else if ($_POST['keypass'] != $password) {
echo "Sorry, that password does not match.";
exit;
} else if ($_POST['user'] == $username && $_POST['keypass'] == $password) {
setcookie('PrivatePageLogin', md5($_POST['keypass'].$nonsense));
header("Location: $_SERVER[PHP_SELF]");
} else {
echo "Sorry, you could not be logged in at this time.";
}
}
?>
And the login form on the page...
(On the same page, right below the above^ posted code)
<form action="<?php echo $_SERVER['PHP_SELF']; ?>?p=login" method="post">
<label><input type="text" name="user" id="user" /> Name</label><br />
<label><input type="password" name="keypass" id="keypass" /> Password</label><br />
<input type="submit" id="submit" value="Login" />
</form>
Here's a very simple way. Create two files:
protect-this.php
<?php
/* Your password */
$password = 'MYPASS';
if (empty($_COOKIE['password']) || $_COOKIE['password'] !== $password) {
// Password not set or incorrect. Send to login.php.
header('Location: login.php');
exit;
}
?>
login.php:
<?php
/* Your password */
$password = 'MYPASS';
/* Redirects here after login */
$redirect_after_login = 'index.php';
/* Will not ask password again for */
$remember_password = strtotime('+30 days'); // 30 days
if (isset($_POST['password']) && $_POST['password'] == $password) {
setcookie("password", $password, $remember_password);
header('Location: ' . $redirect_after_login);
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Password protected</title>
</head>
<body>
<div style="text-align:center;margin-top:50px;">
You must enter the password to view this content.
<form method="POST">
<input type="text" name="password">
</form>
</div>
</body>
</html>
Then require protect-this.php on the TOP of the files you want to protect:
// Password protect this content
require_once('protect-this.php');
Example result:
After filling the correct password, user is taken to index.php. The password is stored for 30 days.
PS: It's not focused to be secure, but to be pratical. A hacker can brute-force this. Use it to keep normal users away. Don't use it to protect sensitive information.
Some easy ways:
Use Apache's digest authorization.
Use lighttpd's digest authorization.
Use php's header digest authorization.
If you want you can also make it so only certain ip addresses can login.. :) really easy with lighttpd
Update: I will post some examples soon, so don't vote down for no examples, i just need to get some down for this answer.
If you want to use sessions the following is the best way to go:
# admin.php
session_start();
if(!$_SESSION["AUTH"])
require_once "login.php";
# Do stuff, we are logged in..
# login.php
session_start();
if($_REQUEST["username"] == "user" && $_REQUEST["password"] == "pass")
$_SESSION["AUTH"] = true;
else $_SESSION["AUTH"] = false; # This logs you out if you visit this login script page without login details.
if($_SESSION["AUTH"])
require_once "admin.php";
This method does not contain the examples for above but you seamed interested in this method. The other method examples are still to come, I have not got enough time to get it for apache or lighttpd settings and the php header auth: http://php.net/manual/en/features.http-auth.php Will do.
I would simply look for a $_GET variable and redirect the user if it's not correct.
<?php
$pass = $_GET['pass'];
if($pass != 'my-secret-password') {
header('Location: http://www.staggeringbeauty.com/');
}
?>
Now, if this page is located at say: http://example.com/secrets/files.php
You can now access it with: http://example.com/secrets/files.php?pass=my-secret-password Keep in mind that this isn't the most efficient or secure way, but nonetheless it is a easy and fast way. (Also, I know my answer is outdated but someone else looking at this question may find it valuable)
A simple way to protect a file with no requirement for a separate login page - just add this to the top of the page:
Change secretuser and secretpassword to your user/password.
$user = $_POST['user'];
$pass = $_POST['pass'];
if(!($user == "secretuser" && $pass == "secretpassword"))
{
echo '<html><body><form method="POST" action="'.$_SERVER['REQUEST_URI'].'">
Username: <input type="text" name="user"></input><br/>
Password: <input type="password" name="pass"></input><br/>
<input type="submit" name="submit" value="Login"></input>
</form></body></html>';
exit();
}
This helped me a lot and save me much time, its easy to use, and work well, i've even take the risque of change it and it still works.
Fairly good if you dont want to lost to much time on doing it :)
http://www.zubrag.com/scripts/password-protect.php
</html>
<head>
<title>Nick Benvenuti</title>
<link rel="icon" href="img/xicon.jpg" type="image/x-icon/">
<link rel="stylesheet" href="CSS/main.css">
<link rel="stylesheet" href="CSS/normalize.css">
<script src="JS/jquery-1.12.0.min.js" type="text/javascript"></script>
</head>
<body>
<div id="phplogger">
<script type="text/javascript">
function tester() {
window.location.href="admin.php";
}
function phpshower() {
document.getElementById("phplogger").classList.toggle('shower');
document.getElementById("phplogger").classList.remove('hider');
}
function phphider() {
document.getElementById("phplogger").classList.toggle('hider');
document.getElementById("phplogger").classList.remove('shower');
}
</script>
<?php
//if "login" variable is filled out, send email
if (isset($_REQUEST['login'])) {
//Login info
$passbox = $_REQUEST['login'];
$password = 'blahblahyoudontneedtoknowmypassword';
//Login
if($passbox == $password) {
//Login response
echo "<script text/javascript> phphider(); </script>";
}
}
?>
<div align="center" margin-top="50px">
<h1>Administrative Access Only</h1>
<h2>Log In:</h2>
<form method="post">
Password: <input name="login" type="text" /><br />
<input type="submit" value="Login" id="submit-button" />
</form>
</div>
</div>
<div align="center">
<p>Welcome to the developers and admins page!</p>
</div>
</body>
</html>
Basically what I did here is make a page all in one php file where when you enter the password if its right it will hide the password screen and bring the stuff that protected forward. and then heres the css which is a crucial part because it makes the classes that hide and show the different parts of the page.
/*PHP CONTENT STARTS HERE*/
.hider {
visibility:hidden;
display:none;
}
.shower {
visibility:visible;
}
#phplogger {
background-color:#333;
color:blue;
position:absolute;
height:100%;
width:100%;
margin:0;
top:0;
bottom:0;
}
/*PHP CONTENT ENDS HERE*/
This stores the password in history after login!
You can specify a password in your php code so only users that have the secret url can access:
mywebsite.com/private.php?pass=secret
in your login-protected file:
<?php
if(isset($_GET["pass"]) && $_GET["pass"]=="secret"){
//put your code here
}
else{
echo "you're not allowed to access this page";
}
?>

Categories