Trying To Post Via Button - php

I Have tried many solutions posted on stack overflow and non of them have worked.
It could just be me but i tried it on a separate file and it worked but if i use my current site with nice css it won't work
I Have tried the exact code on LAEPHP and it worked but when i added my code as you can see below it does not display anything when the button is clicked and it does not even refresh the page on click
<form action="" method="post">
<div class="form-group">
<label>Username</label>
<input class="au-input au-input--full" type="email" name="target" placeholder="Example">
</div>
<div class="form-group">
<label>API key</label>
<input class="au-input au-input--full" type="text" name="key" placeholder="X7UI-9H2D-IZAS">
</div>
<?php
$key= $_POST['key'];
$send= $_POST['send'];
if ($send) {
if (!empty($key)) {
echo 'The key you entered is ' . $key;
}
else {
echo 'You did not enter a key. Please enter a key into this form field.';
}
}
?>
<button class="subscribe btn btn-primary btn-block" name="send" type="submit">Check Key</button>
</form>

The problem I see is that you're checking if the button was sent and isn't "falsy". Since you don't have a value-attribute on the button, it will be an empty string, which is a "falsy" value, meaning that the first if-statement will never evaluate as true.
Try changing your code to:
<?php
// isset() is better since it check if the key exists and isn't null.
if (isset($_POST['send'])) {
// If you rather put the values in separate variables,
// you should do it here, inside the if-statement (where we know we
// got a POST request)
if (!empty($_POST['key'])) {
echo 'The key you entered is ' . $_POST['key'];
}
else {
echo 'You did not enter a key. Please enter a key into this form field.';
}
}
?>

The variable $send is null when the form is being sent to the browser and an empty string (""") when the browser is posting the form. In PHP, when converted to a boolean (as in your if ($send) statement), both of these evaluate to false and the code inside the if statement doesn't run.
The quick fix would be to change it to:
if ($send !== null) // the `!==` is for preventing the type juggling that `!=` does
However, a better method is to use the isset() function which checks if a variable or key in an array exists like so:
if (isset($_POST['send']))
If you were to enable full error reporting, you may get some notices that the $_POST['key'] and $_POST['send'] variables don't exist. With my recommendation that uses isset(), you won't need the $send variable anymore, and the other notice will go away if assign the value to the $key variable after you check that the $_POST['send'] variable is set.

Related

How to display divs after checking password with an HTML form

I'm programming a simple password checker with a html form, where you input the code and this code is compared as hash to another hashed code in the database. If the password matches, the index.php file shows a few divs, which otherwise are completely hidden from the user.
I've tried things like:
$input = "";
<center>
<form action="" method="GET">
CODE:<br>
<input type="text" name="code" value="">
<br><br>
<input type="submit" value="Submit">
</form>
</center>
<?php
$checker = new Checker();
$input = $_GET['code'];
//echo "<style>.Main_Content{ visibility:hidden;}</style>";
if ($checker->compareWords($input, 'Beginners')) {
echo "success Beginners<br>";
include 'Beginners_Video.php';
echo "<style>.Main_Content{ visibility:show;}</style>";
}
else {
echo "false Beginners<br>";
}
?>
Fatal error: Uncaught TypeError: Argument 1 passed to
Checker::compareWords() must be of the type string, null given, called
in D:\www\www91\members\members.php on line 64 and defined in
D:\www\www91\members\checker.php:23 Stack trace: #0
D:\www\www91\members\members.php(64): Checker->compareWords(NULL,
'Beginners') #1 {main} thrown in D:\www\www91\members\checker.php on
line 23
The result should be no error and just the whole thing hidden, or the output "False Beginners. Nothing else"
I know that i'm just stupid and that the answer is probably really simple. I've tried and I can't figure it out.
Thanks for your help.
Your code should work once you filled in and submitted the form, but there is no check handling the case where $_GET['code'] is unset or empty. Change your if statement to
if (!empty($input) && $checker->compareWords($input, 'Beginners')) {
in order to check for this first. If !empty($input) is false, the next condition won't be checked at all, so there won't be an error message and it will jump to the else clause directly.
On a side note: You should think about whether GET is the right method for what you're trying to achieve or whether POST would be better. With GET, The codes users enter might get saved in the browser's history and be visible to others using the same computer. Also, for passwords use type="password" for the input instead of displaying it in cleartext.
And one more thing: the <center> tag is deprecated and you should use CSS instead for layout.
At the very beginning you should check if something is passed in code parameter, using the isset() method. If $_GET['code'] is empty it will return null and this is why you get must be of the type string, null given.
<?php
if(isset($_GET['code']) {
$input = $_GET['code'];
} else {
// 'code' parameter is empty
$input = '';
}
$checker = new Checker();
// ...

Button Value Not Changing when Text Field Isn't Empty

Having a small issue getting my submit button to change the value when the php variable isn't empty. So the way I have it set up is that when the button "GO" is pressed it will set the value of the text field to "1234567890" meaning it is no longer empty. Now when the page first loads the text field will be empty and the button should say "GO" once pressed the text field value will change and the button should now say "REFRESH" however it stays saying "GO" can anyone see where I'm going wrong here?
Thanks.
PHP
<?
if (!$HostKey){
$HostBtn = 'GO';
}
else{
$HostBtn = 'REFRESH';
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['Go'])) {
$HostKey = "123567890";
}
}
}
?>
HTML
<form action="Home.php" method="post">
<p><strong>HOST:</strong>
<input name="Host" id="Host" type="text" value="<? echo $HostKey; ?>" maxlength="10" disabled>
<input name="Go" id="Go" type="submit" value="<? echo $HostBtn; ?>"></p>
</form>
Your issue is a logical one, as $HostKey isn't defined prior to you doing your check - so $HostKey is null. You define it after that. Then, because the variable is effectively null, when you apply the not-operator !, that condition is always true.
You should refactor your code to check if the form was submitted, and define the value of the variable based on that instead. All you need in PHP would be
$HostBtn = isset($_POST['Go']) ? 'REFRESH' : 'GO';
$HostKey = isset($_POST['Go']) ? 123567890 : '';
This would also fix the "Undefined variable..." notices you should have been getting if you enabled error-reporting,
error_reporting(E_ALL);
ini_set("display_errors", 1);
Which should be enabled while in development. In a live environment, you shouldn't display the actual errors though - but its fine to do that under development.
You should try something like :
<?
if (isset($_POST['Go'])) {
$HostKey = "123567890";
$HostBtn= "REFRESH";
}else{
$HostKey="";
$HostBtn="GO";
}
?>

isset function doesn't work on my form and form is nod getting submitted

I am submitting form to page and checking if submit button value InsertMe isset but non of the code inside is executed
<?php
if (isset($_POST['InsertMe'])){
//code to execute
echo "Test";
}
?>
and insert buttons looks like that
<input style="float:right;" name="InsertMe" id="InsertMe" type="submit" class="rectangular-button" value="Add User" />
if (!isset($_POST['InsertMe']) || empty($_POST['InsertMe'])) {
// error message here
} else {
// What you want to do if not empty and is set.
}
This code will check if the variables is set and if if it's empty.
"||" is the PHP operator to check or. So in this case it's checking if it's set OR empty.
Make sure you have the form tag set to post.
<form method="post">
you are selecting Id I think we should be use name tag parameters in isset()

Need type="text" input fields to display previously-POST'd entries if errors occur

I've probably not explained what I"m trying to do in the title very well, so here goes:
I've got a HTML entry form, in a .php file. That entry form when submitted files a POST operation. That POST operation has code to check field input, similar to this:
<?php
...
if ($_POST["submitted"] == 1) {
//"submitted" is a hidden field with value '1' in the form
$isvalid = 1; // Inits to 1, changes to 0 if something fails checks.
$field1 = $_POST["field1"];
$field2 = $_POST["field2"];
...
/*
Checks for validation on each field go here,
but are not relevant to this question here.
*/
}
if ($isvalid == 1) {
// Send email
} else { ?>
<!-- Print form, and error msg. -->
...
<input name="field1" type="text" id="field1" size="32" class="stylingclass">
...
So the above is example code, but here's the real question: How can I get any of the text input fields in my form, when submitted and an error occurred, to automatically contain the previous values that were entered, so that the user can correct the entries accordingly, based on whatever constraints I've set?
You can set the value parameter using a basic ternary operator:
<input name="field1" type="text" id="field1" value="<?php echo isset($_POST["field1"]) ? $_POST["field1"] : ''; ?>" size="32" class="stylingclass">
Note that the ternary operator is used here to prevent an error if there is no index of the specified field in the $_POST array
Just add value="<?=$_POST['field1']?>" (assuming PHP 5.4, use <?php echo $_POST['field1'] ?> otherwise)

Retaining values in forms fields when validation of data fails

I am having problems figuring out how to retain users data when the validation fails. I am somewhat new to PHP so I might be making some huge mistakes in my logic.
Currently if the validation fails all the fields are wiped clean and $_Post data is also gone.
Here is some code assuming the user enters an invalid email I want the Name field to be retained. This code is not working.
<?php
if($_POST['doSubmit'] == 'Submit') {
$usr_name = $data['Name'];
$usr_email = $data['Email'];
if (isEmail($usr_email)==FALSE){
$err = "Email is invalid.");
header("Location: index.php?msg=$err");
exit();
}
//do whatever with data
}
if (isset($_GET['msg'])) {
$msg = mysql_real_escape_string($_GET['msg']);
echo "<div class=\"msg\">$msg</div><hr />";
}
if (isset ($_POST['Name'])){
$reusername = $_POST['Name'];}
else{$reusername = "NOTHING";}//to test
?>
<form action="index.php" method="post" >
<input name="UserName" type="text" size="30" value="<?echo $reusername;?>">
<input name="Email" type="text" size="30">
<input name="doSubmit" type="submit" value="submit">
</form>
}
You can use AJAX to submit your form data to your PHP script and have it return JSON data that specifies whether the validation was successful or not. That way, your fields won't be wiped clean.
Another way is to send back the recorded parameters to the posting page, and in the posting page, populate the fields using PHP.
However, I think the first solution is better.
UPDATE
The edit makes your code clearer and so I noticed something. Your input field is called UserName in the HTML, but you are referring to Name in PHP. That's probably why it's not working. Is your field always being filled with the value NOTHING? Make sure the name of the input field and the subscript you are using in $_POST are the same.
Also, there's no need to redirect to another page (using header) if you have an error. Maintain an $errors array or variable to print error messages in the same page. But like I mentioned before, it's probably better to use the JSON approach since then you can separate your view layer (the html) from the PHP (controller layer). So you'd put your HTML in one file, and your PHP in another file.
EDIT:
Vivin had commented that my assumption regarding the header was incorrect and he was right in that. Further more it looks like what the OP is doing is essentially what i layed out below albeit in a less structured fashion. Further Vivin - caught what is likely the actual problem here - the html name and the array key $_POST do not match.
Its wiped clean because you are using header to redirect to another page. Typicaly you would have a single page that validates the data and if ok does something with it and returns a success view of some sort, or that returns an error view directly showing the form again. By using header youre actually redirecting the browser to another page (ie. starting up an entirely new request).
For example:
// myform.php
if(strtolower($_SERVER['REQUEST_METHOD']) == 'get')
{
ob_start();
include('form.inc.php'); // we load the actual view - the html/php file
$content = ob_get_clean();
print $content; // we print the contents of the view to the browser
exit;
}
elseif(strtolower($_SERVER['REQUEST_METHOD']) == 'post')
{
$form = santize($_POST); // clean up the input... htmlentities, date format filters, etc..
if($data = is_valid($form))
{
process_data($data); // this would insert it in the db, or email it, etc..
}
else
{
$errors = get_errors(); // this would get our error messages associated with each form field indexed by the same key as $form
ob_start();
include('form.inc.php'); // we load the actual view - the html/php file
$content = ob_get_clean();
print $content; // we print the contents of the view to the browser
exit;
}
}
so this assumes that your form.inc.php always has the output of error messages coded into it - it just doesnt display them. So in this file you might see something like:
<fieldset>
<label for="item_1">
<?php echo isset($error['item_1']) ? $error['item_1'] : null; ?>
Item 1: <input id="item_1" value="<?php echo $form['item_1'] ?>" />
</label>
</fieldset>
Could do something similar to if failed then value=$_POST['value']
But vivin's answer is best. I don't know much about AJAX and wouldn't be able to manage that.
Ok, firstly header("Location: index.php?msg=$err"); is not really required. It's best practice not to redirect like this on error, but display errors on the same page. Also, redirecting like this means you lose all of the post data in the form so you can never print it back into the inputs.
What you need to do is this:
<input name="Email" type="text" size="30" value="<?php print (!$err && $usr_email ? htmlentities($usr_email, ENT_QUOTES) : '') ?>">
Here I'm checking whether any errors exist, then whether the $usr_email variable is set. If both these conditions are matched the post data is printed in the value attribute of the field.
The reason I'm using the function htmlentities() is because otherwise a user can inject malicious code into the page.
You appear to be processing the post on the same page as your form. This is an OK way to do things and it means you're nearly there. All you have to do is redirect if your validation is successful but not if it fails. Like this
<?php
if( isset( $_POST['number'] ) ) {
$number = $_POST['number'];
// validate
if( $number < 10 ) {
// process it and then;
header('Location: success_page.php');
} else {
$err = 'Your number is too big';
}
} else {
$number = '';
$err = '';
}
?>
<form method="POST">
Enter a number less than 10<br/>
<?php echo $err ?><br/>
<input name="number" value="<?php echo $number ?>"><br/>
<input type="submit">
</form>

Categories