php stop user from viewing logs - php

<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 />
<?
}

Related

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

PHP - Redisplay forms with valid values in fields and error messages where validation fails

I have created a PHP form to take 4 text fields name, email, username and password and have set validation for these. I have my code currently validating correctly and displaying messages if the code validates or not.
However, I would like for it to keep the correctly validated fields filled when submitted and those that failed validation to be empty with an error message detailing why.
So far I have the following code, the main form.php:
<?php
$self = htmlentities($_SERVER['PHP_SELF']);
?>
<form action="<?php echo $self; ?>" method="post">
<fieldset>
<p>You must fill in every field</p>
<legend>Personal details</legend>
<?php
include 'personaldetails.php';
include 'logindetails.php';
?>
<div>
<input type="submit" name="" value="Register" />
</div>
</fieldset>
</form>
<?php
$firstname = validate_fname();
$emailad = validate_email();
$username = validate_username();
$pword = validate_pw();
?>
My functions.php code is as follows:
<?php
function validate_fname() {
if (!empty($_POST['fname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['fname']);
if (strlen($trimmed)<=150 && preg_match('/\\s/', $trimmed)) {
$fname = htmlentities($_POST['fname']);
echo "<p>You entered full name: $fname</p>";
} else {
echo "<p>Full name must be no more than 150 characters and must contain one space.</p>";
} }
}
function validate_email() {
if (!empty($_POST['email'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['email']);
if (filter_var($trimmed, FILTER_VALIDATE_EMAIL)) {
$clean['email'] = $_POST['email'];
$email = htmlentities($_POST['email']);
echo "<p>You entered email: $email</p>";
} else {
echo "<p>Incorrect email entered!</p>";
} }
}
function validate_username() {
if (!empty($_POST['uname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['uname']);
if (strlen($trimmed)>=5 && strlen($trimmed) <=10) {
$uname = htmlentities($_POST['uname']);
echo "<p>You entered username: $uname</p>";
} else {
echo "<p>Username must be of length 5-10 characters!</p>";
} }
}
function validate_pw() {
if (!empty($_POST['pw'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['pw']);
if (strlen($trimmed)>=8 && strlen($trimmed) <=10) {
$pword = htmlentities($_POST['pw']);
echo "<p>You entered password: $pword</p>";
} else {
echo "<p>Password must be of length 8-10 characters!</p>";
} }
}
?>
How can I ensure that when submit is pressed that it will retain valid inputs and empty invalid ones returning error messages.
Preferably I would also like there to be an alternate else condition for initial if(!empty). I had this initially but found it would start the form with an error message.
Lastly, how could I record the valid information into an external file to use for checking login details after signing up via this form?
Any help is greatly appreciated.
Try using a separate variable for errors, and not output error messages to the input field.
You could use global variables for this, but I'm not fond of them.
login.php
<?php
$firstname = '';
$password = '';
$username = '';
$emailadd = '';
$response = '';
include_once('loginprocess.php');
include_once('includes/header.php);
//Header stuff
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, "utf-8");?>" method="post">
<fieldset>
<p>Please enter your username and password</p>
<legend>Login</legend>
<div>
<label for="fullname">Full Name</label>
<input type="text" name="fname" id="fullname" value="<?php echo $firstname ?>" />
</div>
<div>
<label for="emailad">Email address</label>
<input type="text" name="email" id="emailad" value="<?php echo $emailadd; ?>"/>
</div>
<div>
<label for="username">Username (between 5-10 characters)</label>
<input type="text" name="uname" id="username" value='<?php echo $username; ?>' />
</div>
<div>
<label for="password">Password (between 8-10 characters)</label>
<input type="text" name="pw" id="password" value="<?php echo $password; ?>" />
</div>
<div>
<input type="submit" name="" value="Submit" />
</div>
</fieldset>
</form>
<?php
//Output the $reponse variable, if your validation functions run, then it
// will contain a string, if not, then it will be empty.
if($response != ''){
print $response;
}
?>
//Footer stuff
loginprocess.php
//No need for header stuff, because it's loaded with login.php
if($_SERVER['REQUEST_METHOD'] == 'POST'){//Will only run if a post request was made.
//Here we concatenate the return values of your validation functions.
$response .= validate_fname();
$response .= validate_email();
$response .= validate_username();
$response .= validate_pw();
}
//...or footer stuff.
functions.php
function validate_fname() {
//Note the use of global...
global $firstname;
if (!empty($_POST['fname'])) {
$form_is_submitted = true;
$trimmed = trim($_POST['fname']);
if(strlen($trimmed)<=150 && preg_match('/\\s/', $trimmed)){
$fname = htmlentities($_POST['fname']);
//..and the setting of the global.
$firstname = $fname;
//Change all your 'echo' to 'return' in other functions.
return"<p>You entered full name: $fname</p>";
} else {
return "<p>Full name must be no more than 150 characters and must contain one space.</p>";
}
}
}
I wouldn't suggest using includes for small things like forms, I find it tends to make a mess of things quite quickly. Keep all your 'display' code in one file, and use includes for functions (like you have) and split files only when the scope has changed. i.e your functions.php file deals with validation at the moment, but you might want to make a new include later that deals with the actual login or registration process.
Look at http://www.php.net/manual/en/language.operators.string.php to find out about concatenating.

Make errors show on top of a form

How do I make error show on top of form so that if $user->success == true, it wont show my form then. Removing that last else would help, but then form shows after success. One way is to redirect that. Maybe tehre
if (isset($_POST["submit"]))
{
if ($_POST["formid"] == $_SESSION["formid"])
{
$_SESSION["formid"] = '';
$User->signin($_POST['username'], $_POST['password']);
}
else
$User->CheckUser();
if ($User->success == true) {
include ('in.php');
}
if ($User->error)
echo "<p>" . $User->error . "</p>";
else
echo 'Don\'t process form';
$_SESSION["formid"] = md5(rand(0,10000000));
} else {
?>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
Username:
<input id="username" name="username" type="text" /><br />
Password:
<input id="password" name="password" type="password" /><br />
<input type="hidden" name="formid" value="<?php echo $_SESSION["formid"]; ?>" />
<input type="submit" name="submit" />
<br />
Register
</form>
<?php }?>
Perhaps the simplest approach is to just create a variable $show_form to use to determine whether form is to be shown,
$show_form = true;
if(isset($_POST['submit'])) {
// do your form processing here.
// If you decide everything is good and you don't want to show the form,
// just add this line:
$show_form = false;
} // don't use else here
if (true === $show_form) {
?>
<form>...</form>
<?
}
?>
add this code before your form tag
<?php if (isset($User->error) AND $User->error)?>
<p><?php echo $User->error?></p>
<?php?>

Form values variables and submission problems

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.

Variable wont echo

I have the following code, where the var $username doesn't echo, when you type in a value.
//TODO: SET AUTH TOKEN as random hash, save in session
$auth_token = rand();
if (isset($_POST['action']) && $_POST['action'] == 'Login')
{
$errors = array(); //USED TO BUILD UP ARRAY OF ERRORS WHICH ARE THEN ECHOED
$username = $_POST['username'];
if ($username = '')
{
$errors['username'] = 'Username is required';
}
echo $username; // var_dump($username) returns string 0
}
require_once 'login_form.html.php';
?>
login_form is this:
<form method="POST" action="">
<input type="hidden" name="auth_token" value="<?php echo $auth_token ?>">
Username: <input type="text" name="username">
Password: <input type="password" name="password1">
<input type="submit" name="action" value="Login">
</form>
The auth token part isn't important, it just when I type in a value in username textbox and press the login button, the username wont echo, var_dump returns string (0) and print_r is just blank.
silly mistake
if ($username = '') <-- this is an assignment
Should be this
if ($username == '') <-- this is comparison
if ($username = '')
You're missing a =, so you're assigning an empty string to $username. Change it to
if ($username == '')
^-- note the 2 equal signs.
This line is an assignment, not a comparison:
if ($username = '')
You want:
if ($username == '')
//TODO: SET AUTH TOKEN as random hash
$auth_token = rand();
if (isset($_POST['action']) && $_POST['action'] == 'Login')
{
$errors = array(); //USED TO BUILD UP ARRAY OF ERRORS WHICH ARE THEN ECHOED
$username = $_POST['username'];
if ($username == '') // **You are assiging not comparing**
{
$errors['username'] = 'Username is required';
}
echo $username; // var_dump($username) returns string 0
}
require_once 'login_form.html.php';
?>
In your login form: (the action attribute..)
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="auth_token" value="<?php echo $auth_token ?>">
Username: <input type="text" name="username">
Password: <input type="password" name="password1">
<input type="submit" name="action" value="Login">
</form>

Categories