how to use isset for password - php

I'm giving this simple html form with password and with php I'm giving to do this
The only valid password shall be "testing" (without the quotes). If the user did not type a password, give them a warning to "Please type a password" and do no more processing on the data at all. If the user did not type the valid password "testing" (without the quotes), then tell the user "Invalid password, sorry" and do no more processing on the data at all. (Use an “if” statement to find out if they entered a password, etc…)
but I just can't seem to figure out
can someone give me a hand?
the html coding is
<form action = "lab.php" method = "post" name = "lab_form">
what is your last name: <input type = "text" name = "last"><br />
what is your student number (password): <input type = "password" name = "number">
</form>
what I did with my php is this....but didn't work at all...and all I've learned is $_POST and isset for now. I wonder how I can get this done with $_POST, isset and with if statement...
<?php
echo $_POST["last"] . "<br/>";
if (isset($_POST["number"]))
{
echo "The variable $_POST[number] exists.";
}
else if (!(isset($_POST["number"])))
{
echo "Please enter a password.";
}
else
{
echo "No variable called $_POST[number]";
}
?>
I know what I'm doing wouldn't make must sense....but...ya :(
Thanks in advance though ^_^
P.S. I know in the php code I should add something like
if($_POST["number"] == testing)
and continuing on but the thing is I couldn't even make it show the other parts so i didn't bother try the "testing" as password yet.

Small mistake. Use empty() too.
<?php
echo $_POST["last"] . "<br/>";
if (isset($_POST["number"]))
{
echo "The variable $_POST[number] exists.";
}
elseif (empty($_POST["number"]))
{
echo "Please enter a password.";
}
elseif (!isset($_POST["number"]))
{
echo "No variable called $_POST[number]";
}
?>

Related

Form submission results in a blank page in PHP

I am trying to make a login system and i want to create a conditional statement that checks whether the global variable $_POST['submit-form'] is set.
If the global variable $_POST['submit-form'] is set then i want to echo out the fields of the submitted forms. This works fine..
The problem comes when i want to check whether the global variable $_POST['submit-form'] is empty, i get a blank page when i submit the form with nothing. It is supposed to echo out something like "You have entered nothing, please try again'.
I don't know what is wrong.
This is the code for the form.
<form action="test-form2.php" method="POST">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit" name="submit-form" value="submit">
</form>
..and this is the code for the form handler.
<?php
if(isset($_POST['submit-form'])) {
$name = $_POST['name'];
$email = $_POST['email'];
if(($_POST['name'] != "") && ($_POST['email']!= "")) {
echo "This is your name: ".$name."<br>";
echo "This is your email: ".$email;
// header('refresh=3;url = ../leden/index.php');
}
} else {
echo "You have entered nothing or your username and/or password is incorrect, please try again.";
// header('refresh=3;url = /test-form1.php');
}
?>
Your $_POST always have submit-form (and it's always not empty), so if statement always returns true. Try to check (for example) only that $_POST['name'] and $_POST['email'] are not empty.
The problem with your code is that checking if it's set isn't enough .. Because it may be set and be empty -- Realistically what you want is to check both isset and whether it's empty IE:
if (isset($_POST['submit-form'] && $_POST['submit-form'] != '' && $_POST['submit-form'] != null)
If the above if statement fails your value for $_POST['submit-form'] is most likely not being submitted.
UPDATE
Check for blank fields
if ($_POST['name'] != '' && $_POST['email'] != ''){
// Do stuff
}else{
if ($_POST['name'] == ''){
echo "name is empty";
}
if ($_POST['email'] == ''){
echo "email is empty";
}
}
That's because isset($_POST['submit-form']) returns true even if you don't input anything in Name and E-mail fields, it's value would be submit string when hit submit button to submit the form. This is the reason else part of below block is not getting executed.
if(isset($_POST['submit-form'])) {
} else {
echo "You have entered nothing or your username and/or password is incorrect, please try again.";
}
Use var_dump($_POST); to see the complete array structure. having said these, you can use the following snippet to achieve the desired result,
if(isset($_POST['submit-form'])) {
$name = $_POST['name'];
$email = $_POST['email'];
if(($_POST['name'] != "") && ($_POST['email']!= "")) {
echo "This is your name: ".$name."<br>";
echo "This is your email: ".$email;
// header('refresh=3;url = ../leden/index.php');
}else{
echo "You have entered nothing or your username and/or password is incorrect, please try again.";
}
}
Validation and scrutinization of user inputs should be your next action items in the list.

Is array_key_exists giving a false positive?

Obviously I know that array_key_exists is not giving a false positive. I'm doing something wrong. I just wanted to grab your attention. :)
Seriously though. I am doing this as an exercise.
Here is my code:
<?php
$error = "";
if($_POST)
{
if (!array_key_exists('email',$_POST)) {
$error .= "<p>You did not submit an e-mail address. Please try again.</p>";
}
if (!array_key_exists('password',$_POST)) {
$error .= "<p>You did not submit a password. Please try again.</p>";
}
echo $error;
print_r($_POST);
}
?>
When I don't submit either email or password, echo $error outputs nothing. print_r($_POST) outputs whatever I sent.
What am I missing here?
$_POST['email'] and ['password'] exist but are empty you should see it with your print_r($_POST);
You should check the value instead of the key.
I think that you should use
empty($_POST['email'])
instead of array_key_exists.
Why not just check empty($_POST['email']) instead of !array_key_exists?
Both will check if the key exists and also will check if they are not NULL.
empty will additionally check if it's no empty array, 0(as int and as string), empty string, etc.
EDIT
I was late
I would add a hidden input to your form
<input type="hidden" name="formSubmitted" value="1" />
Then you can check for the form having been submitted, rather than checking for the existence of your $_POST array. Also, in case both of your fields are empty when they are submitted, this provides a separate mechanism for identifying that, rather than assuming both of your fields will be valid.
<?php
$error = "";
if(isset($_POST['formSubmitted']) && $_POST['formSubmitted'] == 1) {
if (!array_key_exists('email',$_POST)) {
$error .= "<p>You did not submit an e-mail address. Please try again.</p>";
}
if (!array_key_exists('password',$_POST)) {
$error .= "<p>You did not submit a password. Please try again.</p>";
}
echo $error;
print_r($_POST);
}
?>
I'm also assuming you (will) have some other forms of validation to ensure that the email address and password meet some basic requirements that are not shown here.

Passing php variables from php1 to php2, then having php2 return a new value assigning to variable from php1

This may sound really broken but essentially my intentions are for in php1, have a name for example validate to match a regex, if it fails to meet the conditions it will then redirect to php2 where there awaits a form where a user can retype it and submit it back to php1 where it will do the checks again. Then finally in the first php, if everything works ok it will echo it back.
Also how would i expand it so multiple things such as credit cards etc. can be validated too?
Thanks
php1
if (isset ($_POST["CardHolder"])) {
cardholder = $_POST["CardHolder"];
cardholder = sanitise_input($cardholder);
if (!preg_match("/^[a-zA-Z\s]{1,40}$/", $cardholder)) {
$errMsg .= "First name can only contain alpha characters, please re-enter";
$newcardholder = $_POST["newcardholder"];
$cardholder = $newcardholder;
}
else {
$cardholder = $_POST["CardHolder"];
}
if ($errMsg != "") {
header("Location: fix_order.php?errMsg=".$errMsg)
}
php2 (fix_order.php)
if (isset ($_GET["errMsg"])){
$cardholder = $_GET["errMsg"];
echo "<form action='process_order.php' method='post'>"
."<p><label>$cardholder:</label>"
."<input type='text' name='newcardholder'/></p>"
."<p><input type='submit' value='Submit'/>";
"</form>";
}
When calling header("Location:...") you need to give the full and absolute URL.
so header("Location: fix_order.php") will not work.

Input does not pass validation test for strlen

I am making a login system and I have a form with some validation.
However my form seems to be failing to pass the validation even though the data input should pass easily.
See:
http://marmiteontoast.co.uk/fyp/login-register/index.php
When you input a username, it should be over 3 characters. But even if you enter one really long you get the error message: The username is less than 3 characters.
EDIT: There was an issue in my copying from formatting that caused a missing }. I've corrected this. It wasn't the issue.
This is the if statement for the username pass. So it seems like it is not getting past the first test:
if (isset($_POST['username'])){
$username = mysql_real_escape_string(trim($_POST['username']));
$_SESSION['status']['register']['username'] = $username;
if(strlen($username) > 3){
if(strlen($username) < 31){
if(user_exists($username) === true){
$_SESSION['status']['register']['error'][] = 'That username is already taken. Sorry, please try again with a different username.';
}else{
// passed
}
} else {
$_SESSION['status']['register']['error'][] = 'The username is greater than 30 characters.';
}
} else {
$_SESSION['status']['register']['error'][] = 'The username is less than 3 characters.';
}
} else {
$_SESSION['status']['register']['error'][] = 'The username is not entered.';
}
And this is the HTML for the username:
<form method="post" action="register.php">
<div class="username">
<label class="control-label" for="inputUser">Username</label>
<input type="text" id="inputUser" name="username" placeholder="Username" value="<?php echo $usern_value; ?>" />
</div>
You can see the site here: http://marmiteontoast.co.uk/fyp/login-register/index.php
Session
The index page does use sessions.
It starts with this:
<?php
session_start();
?>
And kills the session at the end of the file:
<?php
unset($_SESSION['status']);
?>
But in the file it starts new sessions which store the inputs. This is so if you make a mistake, it still holds your info so you can adjust it rather than having the fill in the form again. Here is an example of where it grabs the username and saves it, then outputs it.
<?php
if(isset($_SESSION['status']['register']['username'])){
$usern_value = $_SESSION['status']['register']['username'];
} else {
$usern_value = "";
}
?>
value="<?php echo $usern_value; ?>" />
This is the user-exists function:
function user_exists($username){
$sql = "SELECT `id` FROM `users` WHERE `username` = '".$username."'";
$query = mysql_query($sql);
$result = mysql_num_rows($query);
if($result == 1){
// username does already exist
return true;
}else{
// username doesn't exist in the database
return false;
}
}
Ah, I can see the problem from your website link. When the error pops up ("The username is less than 3 characters."), try refreshing your browser. I expected to receive a browser warning that says the data would be resubmitted to the server — because you are in a post form — but I did not.
So, what does this mean? It means that immediately after validation failure, you are redirecting back to the same screen, and — unless you are using a session to preserve this information — your $_POST data will be lost. Commonly in the case of validation failure with this sort of form, you must prevent that redirect and render inside the post operation, which keeps the user's input available to you. The redirect should only occur if the form input was successful (i.e. it saves to the data and/or sends an email).
Edit: I should have seen the $_SESSION in the original post. OK, so the strategy is to write things to the session, redirect regardless of validation outcome, and to save error messages to the session. I wonder whether you are not resetting the session errors array when you're posting the form? Immediately after your first if, try adding this:
if (isset($_POST['username'])){
$_SESSION['status']['register']['error'] = array(); // New line
Unless you have something to make the session forget your errors, they will be stored until you delete your browser's cookie.
You have missed a closing brace } on this line:
if(user_exists($username) === true){
} else{// **missed the closing brace before the else**
// passed
}
Why is your logic so complex?
if (strlen($username) < 3) {
// too short
} elseif (strlen($username) > 31) {
// too long
} elseif (true === user_exists($username)) {
// already registered
} else {
// passed
}

Check if POST data is set, can't get it working

I want to use PHP to check if $_POST["pass"] is set, and do something if it's not, and do something else if it is.... But I can't get it working, I'm sure my logic is wrong.
I have a php code that looks something like this...
if (!isset($_POST["pass"])) {
...some form with an input type text here...
if (...wrote the wrong thing in input type text...) {
echo "something is wrong....";
}
else {
$pass_var = "Pass";
$pass_var = $_POST["pass"];
}
}
else {
echo "This thing is working...";
}
If I type the right thing in my input type text, I wan't to get to "This thing is working", and if not I wan't to echo "something is wrong....".
It works almost fine, except that if I type the right thing in my form, I never get to "This thing is working...".
The page just does nothing..
I'm sure it's the
$pass_var = "Pass";
$pass_var = $_POST["pass"];
that I'm doing wrong.
I know that I could set this up in another way to make it work, but I have a large script that is set up like this, and I really want it to work...
You test in the form against the $_POST NOT being set (See the !). You want however the post to be set!
if(isset($_POST["pass"]))
{
print_r($_POST); // basic debugging -> Test the post array
echo "The form was submitted";
// ...some form with an input type text here...
if(...wrote the wrong thing in input type text...)
{
echo "something is wrong with the input....";
}
else
{
// Valid user input, process form
echo "Valid input byy the user";
$pass_var = "Pass";
$pass_var = $_POST["pass"];
}
}
else
{
echo "The form was not submitted...";
}
You can use the empty() function of php
if(!empty($_POST['pass'])){
// do something
}else{
// do something else
}
Hope this will work for you .
Make sure you have "method='POST'" in your html form else $_POST isn't accessible in php, and logic was a bit screwy, try this?
e.g.
if (!isset($_POST["pass"])) {
//no POST so echo form
echo "<form action='".$_SERVER['PHP_SELF']."' method='POST'>
<input type='text' name='txtInput' />
<input type='submit' name='pass' />
</form>";
} elseif (isset($_POST["pass"])) {
//have POST check txtInput for "right thing"
if ($_POST["txtInput"] == "wrong thing") {
echo "something is wrong....";
} elseif ($_POST["txtInput"] == "right thing") {
//$pass_var = "Pass";
$pass_var = $_POST["pass"];
echo "This thing is working...";
}
}
Well, if (!isset($_POST["pass"])) means if $_POST["pass"] is not set, so you might want to remove the '!' which stands for not.

Categories