Form values variables and submission problems - php

Can someone help me fix this code? What I want to fix is:
If a person doesn't enter a username or password, I just want the error text (the red messages on the side) without the 'sorry, no access' message on top.
Also, if a person gains access (or doesn't), I want the text fields and submit button go away.
This isn't going to be a real form, so please don't worry about how I'm using a username and password....and if its possible do you think most of my code could stay the same?
Thanks!
<?php
echo '<style type="text/css">
.error
{
color: red;
}
</style>';
$error = false;
if (isset($_POST['submitted']))
{
if (empty($_POST['username']) || empty($_POST['password']))
{
$error = TRUE;
}
if (!$error && $_POST['username']=='test' && $_POST['password']=='abc123') {
echo '<p>Correct. Thank you for entering.<p/>';
}
else
{
echo '<p>Sorry, no access.</p>
';
}
}
?>
<form action="" 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 a password.</span>';
}
?>
<br /><input type="submit" value="Log in" />
<br /><input type="hidden" name="submitted" value="true" />
</form>

Try this:
<style type="text/css">
.error {
color: red;
}
</style>
<?php
$submitted = isset($_POST['submitted']);
$userName = isset($_POST['username']) ? $_POST['username'] : null;
$password = isset($_POST['password']) ? $_POST['password'] : null;
if($submitted) {
if (!$userName || !$password) {
echo '<p class="error">Please go back and fill the inputs.</p>';
} elseif($userName == 'test' && $password == 'abc123') {
echo '<p>Correct. Thank you for entering.<p/>';
} else {
echo '<p class="error">Sorry, no access.</p>';
}
} else {
?>
<form action="" method="post">
Username: <input type="text" name="username" size="20" value="<?php echo $userName; ?>" />
<br />
Password: <input type="password" name="password" size="20" value="" />
<br /><input type="submit" value="Log in" />
<br /><input type="hidden" name="submitted" value="true" />
</form>
<?php } ?>

Consider using the onSubmit event on your form.
You need to combine php and javascript here in order to prevent it from submitting. Make a Jscript function that's called by onSubmit. If a value isn't filled in, return false. It'll kill the submit button and print out directly on the screen.
So just take this:
$submitted = isset($_POST['submitted']);
$userName = isset($_POST['username']) ? $_POST['username'] : null;
$password = isset($_POST['password']) ? $_POST['password'] : null;
if($submitted)
{
if (!$userName || !$password) {
echo '<p class="error">Please go back and fill the inputs.</p>';
}
}
And then on your form:
<form action="" method="post" onSubmit="checkForm()">
Then figure out how you're going to check the form with javascript. You can piece together the rest.

Related

Change empty input border after submission

I want to have it so if the person clicks the submit button and leaves a input / textarea empty. I want it to change the now gray border to red (Whichever input was left empty).
My current code:
if(empty($_POST['email']) ||
empty($_POST['name']) ||
empty($_POST['message']) ||
empty($_POST['pref-job']) ||
empty($_POST['username']))
{
echo "<style type='text/css'>
input {
border: thin solid #e51923;
}
textarea {
border: thin solid #e51923;
}
</style>";
}
You can do this with php, but a much better option is to use HTML5.
The required attribute will stop submission and highlight the field red if it is not populated.
<input type="email" name="email" required="required" />
Note that this will only function correctly with those browsers that implement HTML5, and should not be relied upon for validation. You should still validate server side. In this case, I would suggest adding a class to the input field to show that it is invalid in php - something like:
if (empty($_POST['email'])) {
$emailClass = 'validationFailed';
} else {
$emailClass = '';
}
printf('<input type="email" name="email" class="%s" />', $emailClass);
For this to work, you would also need the validationFailed class to have been defined of course - something like in your question:
.validationFailed {
border: thin solid #e51923;
}
Since Both HTML require and PHP empty() can be bypassed my space
$email = null;
$name = null;
$message = null;
$pref_job = null;
$username = null;
if ($_POST) {
$error = false;
if(trim($_POST['email']) == false) {
$email = 'failed';
$error = true;
}
if (trim($_POST['name']) == false) {
$name = 'failed';
$error = true;
}
if (trim($_POST['message']) == false) {
$message = 'failed';
$error = true;
}
if (trim($_POST['pref_job']) == false) {
$pref_job = 'failed';
$error = true;
}
if (trim($_POST['username']) == false) {
$username = 'failed';
$error = true;
}
if ( ! $error) {
//passed all basic validation
}
}
?>
<style type='text/css'>
.failed {
border: thin solid #e51923;
}
</style>
<form method="post">
<input type="text" name="email" class="<?php echo $email; ?>" /> <br />
<input type="text"name="name" class="<?php echo $name; ?>"/> <br />
<input type="text" name="message" class="<?php echo $message; ?>"/> <br />
<input type="text" name="pref-job" class="<?php echo $pref_job; ?>"/> <br />
<input type="text" name="username" class="<?php echo $username; ?>"/> <br />
<input type="submit" value="Submit"/>
</form>
Unless you want to allow empty space values

Undefined variable on POST

I looked trough your pages and fixed my undefined index on username and password but now I get undefined variable. I had more code but decided to simplify it for the sake of testing and just echo it to see if anything changes and it doesn't.
<?php
if (isset($_POST['submit'])){
$uname = isset($_POST['username']);
$pass = isset($_POST['password']);
}
echo $uname;
echo $password;
?>
I get this:
Notice: Undefined variable: uname in C:\xampp\htdocs\8\login.php on line 7
Notice: Undefined variable: pass in C:\xampp\htdocs\8\login.php on
line 8
I do not really understand what's wrong here. If needed here is my form page html.
<form id="login" method="post" action="login.php">
<div id="loginon">
<label for="username" style="color:#0F0; font-family:Arial, Helvetica, sans-serif;" >Username: </label>
<input type="text" id="username" name="username" />
<br />
<br />
<label for="password" style="color:#0F0; size:auto; font-family:Arial, Helvetica, sans-serif;">Password: </label>
<input type="password" id="password" name="password" />
<br />
<br />
<input type="image" src="http://www.clker.com/cliparts/2/G/4/v/K/E/submit-hi.png" border="0" width="180px" height="80px" alt="Submit" />
</div>
</form>
</body>
EDIT:
The further problem is connected to this so I think I am allowed to post it here.
if($username == "pikachu" || "cloud") {
$ucheck = "dobar";
} else {
$ucheck = "los";
}
if ($password == "123123" || "132132") {
$pcheck = "topar";
} else {
$pcheck = "losh";
}
if($ucheck == "dobar" && $pcheck == "topar") {
echo "Najjaci si!";
}
elseif ($ucheck == "dobar" && $pcheck == "losh") {
echo "Wimp.";
} elseif ($ucheck == "los" && $pcheck == "topar") {
echo "Fish.";
}
The problem is that it always echoes out "Najjaci si" no matter what I type in the previous form. Any ideas?
Since you have the variable decleration inside a logic (If), there is a chance that the variables are not set at all.
Try this
<?php
if (isset($_POST['submit'])){
$uname = isset($_POST['username']);
$pass = isset($_POST['password']);
echo $uname;
echo $pass;
} else {
echo "No submit detected!";
}
?>
It also doesen't look like if you have an actual element named submit.
Try adding this:
<input type="submit" name="submit" value="Send my form" />
Now, your form contains an element named "submit" which will be send as a post parameter when the form is submitted.
I myself, in need of a framework, like doing like this:
$username = ( isset($_POST["username"]) && $_POST["username"] != "" ? $_POST["username"] : false );
$password = ( isset($_POST["password"]) && $_POST["password"] != "" ? $_POST["password"] : false );
if( !$username === false && !$password === false )
{
echo $username . " <br /> " . $password;
} else {
echo "No! :) ";
}
isset will check that variable is set or not and pass value in 0 or 1. So over here you need to do as
$uname = isset($_POST['username']) ? $_POST['username'] : '';
$pass = isset($_POST['password']) ? $_POST['password'] : '';
Notice: Undefined variable: pass in C:\xampp\htdocs\8\login.php on line 8
Its because you were echoing $password instead of $pass
Edited
Do it as
$uname = '';
$pass = '';
if (isset($_POST['submit'])){
$uname = isset($_POST['username']);
$pass = isset($_POST['password']);
}
echo $uname;
echo $pass;
Try this
In form
<form id="login" method="post" action="login.php">
<div id="loginon">
<label for="username" style="color:#0F0; font-family:Arial, Helvetica, sans-serif;" >Username: </label>
<input type="text" id="username" name="username" />
<br />
<br />
<label for="password" style="color:#0F0; size:auto; font-family:Arial, Helvetica, sans-serif;">Password: </label>
<input type="password" id="password" name="password" />
<br />
<br />
<input type="submit" name="submit"/>
</div>
</form>
</body>
In login.php
<?php
if (isset($_POST['submit']))
{
$uname = $_POST['username'];
$pass = $_POST['password'];
}
echo $uname;
echo $pass;
?>

echo Error on for Page Protected PHP page

I have a protected page that requires you to login to access the page content.
Where can I put an else statement that echos "wrong username or wrong password"
if the user does not enter the exact user/password?
The PHP page
<?php
// Define your username and password
$username = "user";
$password = "password";
if ($_POST['txtUsername'] != $username || $_POST['txtPassword'] != $password) {
?>
<h1>Login</h1>
<form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label>User</label>
<input type="text" title="Enter your Username" name="txtUsername" />
<label>Password</label>
<input type="password" title="Enter your password" name="txtPassword" />
<input type="submit" name="Submit" value="Login" />
</form>
<?php
}
else {
?>
<p>This is the protected page. Your private content goes here.</p>
<?php
}
?>
** I have tried entering it after -- else { at the bottom of page
** I have tried entering it after -- if($_POST...$password) {
neither one worked. I attached a image to show you what I mean.
Thanks
It can also be solved by simply setting some validation flags and using those on your views. Using your own code structure template, the following might do the trick:
<?php
// Define your username and password
$username = "user";
$password = "password";
$hasError = true;
$hasSubmitted = false;
if (isset($_POST['Submit'])) {
$hasSubmitted = true;
if ($_POST['txtUsername'] != $username || $_POST['txtPassword'] != $password) {
$hasError = true;
} else {
$hasError = false;
}
}
if ($hasError):
?>
<h1>Login</h1>
<?php if ($hasSubmitted): ?>
<p>*You entered a wrong username or password</p>
<?php endif; ?>
<form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label>User</label><input type="text" title="Enter your Username" name="txtUsername" />
<label>Password</label><input type="password" title="Enter your password" name="txtPassword" />
<input type="submit" name="Submit" value="Login" />
</form>
<?php else: ?>
<p>This is the protected page. Your private content goes here.</p>
<?php endif; ?>
<?php
class ValidateUser
{
public static function Check($user,$pass)
{
$settings[] = ($user == $_POST['txtUsername'])? 1:0;
$settings[] = ($pass == $_POST['txtPassword'])? 1:0;
return (array_sum($settings) == 2)? true:false;
}
}
// if the username and passowrd match up
if(isset($_POST['txtUsername'])) {
$uservalid = ValidateUser::Check('hardcodeuser','hardcodepass');
}
// If user/pass not valid
if($uservalid !== true || !isset($uservalid)) { ?>
<h1>Login</h1>
<?php if(isset($uservalid) && $uservalid !== true) echo 'Invalid Login'; ?>
<form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label>User</label>
<input type="text" title="Enter your Username" name="txtUsername" />
<label>Password</label><input type="password" title="Enter your password" name="txtPassword" />
<input type="submit" name="Submit" value="Login" />
</form>
<?php }
else { ?>
<p>This is the protected page. Your private content goes here.</p>
<?php
} ?>
Try this and read the comment in the code
<?php
if ($_POST['txtUsername'] != $username || $_POST['txtPassword'] != $password) {
?>
<h1>Login</h1>
<form name="form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label>User</label><input type="text" title="Enter your Username" name="txtUsername" />
<label>Password</label><input type="password" title="Enter your password" name="txtPassword" />
<input type="submit" name="Submit" value="Login" />
</form>
<?php
//adde these line to check weather its empty or not
if(!empty($_POST['txtUsername']) && empty($_POST['txtPassword']))
{
//this is complicated part you need check username and password. and they have to
//match.
// i cant help you here, cause i dont know from where you want to check username and password
//but i am giving you if statement.
//simple way you get the username from form, than check wether the username password matches, in the db or not, and if does not matches, we show the error message
//run the query
//check the result
//result return succes then ok
//else show the error
}
else
{
echo 'You need to enter your username and password';
}
}
else {
?>
<p>This is the protected page. Your private content goes here.</p>
<?php
}
?>
<?php
// Define your username and password
$username = "user";
$password = "password";
$loginPageTPL = <<< EOF
<!doctype html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form name="form" method="post" action="{% PHP_SELF %}">
{% ERROR_MESSAGES %}
<label for="username">User</label>
<input id="username" type="text" placeholder="Enter your Username" name="txtUsername" />
<label for="password">Password</label>
<input id="password" type="password" placeholder="Enter your password" name="txtPassword" />
<input type="submit" name="Submit" value="Login" />
</form>
</body>
</html>
EOF;
$loginPageTPL = str_replace('{% PHP_SELF %}', $_SERVER['PHP_SELF'], $loginPageTPL);
if ((isset($_POST['txtUsername'])) && (isset($_POST['txtPassword']))) {
if (($_POST['txtUsername'] == $username) && ($_POST['txtPassword'] == $password)) {
echo "your private content here";
return;
} else {
$loginPageTPL = str_replace('{% ERROR_MESSAGES %}', '<div style="color: red">* you entered a wrong username and password</div>', $loginPageTPL);
echo $loginPageTPL;
}
} else {
$loginPageTPL = str_replace('{% ERROR_MESSAGES %}', '', $loginPageTPL);
echo $loginPageTPL;
}

php login without mysql

i'm having this code at the top of my index.php
<?php
include("security.php");
?>
and here is the security.php
<?php
session_start();
$user["admin"] = "123";
if (!isset($_SESSION['logged_in']))
{
echo '<h1>Login</h1>';
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (empty($_POST['username']) || empty($_POST['password']))
{
echo '<span style="color:red; font-weight: bold">Please fill in all fields!</span>';
}
elseif ($user[$_POST['username']] != $_POST['password'])
{
echo '<span style="color:red; font-weight: bold">Your username/password is wrong!</span>';
}
else
{
header("Refresh: 1");
$_SESSION['ingelogd'] = true;
echo '<span style="color:green; font-weight: bold">You are now logged in!</span>';
}
}
else
{
exit('You need to log-in to view this page.<br /><br />
<form method="POST" action=""><p>
Username:<br />
<input type="text" name="username" /><br /><br />
Password:<br />
<input type="password" name="password" /><br /><br />
<input type="submit" value="Login" /> <input type="reset" value="Empty fields" />
</form>');
}
}
?>
but the fact is when I login using admin and pass it logs in but after some time it redirects me back to the login page..
please tell me how to stay at index.php after login..
chek your following code:
wrong:
if(!isset($_SESSION['logged_in']))
should be:
if(!isset($_SESSION['ingelogd']))
Here you are setting session $_SESSION['ingelogd'] to true
header("Refresh: 1");
$_SESSION['ingelogd'] = true;
echo '<span style="color:green; font-weight: bold">You are now logged in!</span>';
But your are checking $_SESSION['logged_in'] which is not set.
So I think changing either of one will fix your problem

php stop user from viewing logs

<form method = "post" action = "<?php echo $_SERVER['PHP_SELF']; ?>" />
Username:<input type = "text" name ="user"> <br />
Password:<input type = "password" name = "pass"><br />
<input type = "submit" value ="View Logs!"><br />
<?php
$user = $_POST['user'];
$pass = $_POST['pass'];
//Problem here, I need to only allow the user to see logs
// after he or she has entered the correct info.
//Currently code just shows all, when the user hits View Logs
// without any credentials
if (($user == "php") && ($pass == "student"))
echo "Enjoy the Logs!";
else echo "<b>Access Denied!</b>";
?>
The problem is that your form is posting directly to log.txt and not processing any of your PHP after the form submission. You'll need to change the action to post to the PHP file itself and then use http_redirect to redirect the user to log.txt after checking the password.
Having said that it's still not going to be very secure though as anyone could get to log.txt by using a direct URL, so you'll need to do some kind of authorisation there. The best thing to do is probably to store log.txt somewhere that's not accessible by through HTTP and then load and display the file using readfile in place of your echo:
<form action="" method="post">
Username:<input type="text" name="user"/> <br />
Password:<input type="password" name="pass"/><br />
<input type="submit" value="View Logs!"/><br />
</form>
<?php
$user = $_POST['user'];
$pass = $_POST['pass'];
if (($user == "php") && ($pass == "student")) {
echo '<pre>';
readfile('log.txt');
echo '</pre>';
}
else {
echo "<b>Access Denied!</b>";
}
?>
<?
if (
isset( $_POST['user'] )
&& isset( $_POST['pass'] )
) {
$user = $_POST['user'];
$pass = $_POST['pass'];
if (
($user == 'php')
&& ($pass == 'student')
) {
echo "Enjoy the Logs!";
readfile('log.txt');
}
else {
echo '<b>Access Denied!</b>';
}
} else {
?>
<form method="post">
Username:<input type="text" name="user"> <br />
Password:<input type="password" name="pass"><br />
<input type="submit" value="View Logs!"><br />
<?
}

Categories