PHP->MySQL Form - Validation - php

I've got a dilema, I've got my database created, my input form works, however I'm looking to add validation to the POST so that certain things cant be entered, I can release snippets of code if needed however I can't find what I'm looking for.
My form basically
<input type="text" name="id1" placeholder="Pick a number">
<input type="text" name="id2" placeholder="Pick another number">
However, I would like to display an error if they pick the same number
EG: IF ID1 == ID2 then ECHO error.
However I'm unsure of the code, I have a simple PHP Mysql form.

You can use this code:
if($_POST['id1'] == $_POST['id2']) {
echo 'error';
}

on the action of your form i.e you define in your action attribute of form action='somepage.php write below code.
if(isset($_REQUEST['id1']) && isset($_REQUEST['id2'])){
if($_REQUEST['id1'] >= $_REQUEST['id2']){
echo "error";
}
}

To be sure, use typecasting plus check if posts are set.. e.g.
<?php
$id1 = isset($_POST['id1']) ? (int) $_POST['id1'] : 0;
$id2 = isset($_POST['id2']) ? (int) $_POST['id2'] : 0;
if(!empty($id1) && !empty($id2) && $id1 !== $id){
// success
} else {
// fail
}

Related

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

PHP Form validation server side, Display error on page, Display outputs on other page

I'm trying to validate a form using server-side, but the problem is, I can't display the error message and inputs. To explain it in details:
Have a form that can post inputs
Validate the data eg,. if empty, display error on the page, else proceed to the target page
form page, this is where I validate and display
<?php
?>
<?=$firstErr?>
<form method="POST" action="">
<input type="text" name="firstname" />
<input type="text" name="secondname" >
<input type="submit" name="submit" >
</form>
target page
if(isset($_POST['submit']))
{
$first = $_POST['firstname'];
$second = $_POST['secondname'];
if($first == "" && $second== "")
{
echo "<script language='javascript'>window.location = 'main.php';</script>";
$firstErr .= '<p class="error">Username should be alpha numeric characters only.</p>';
}
else
{
echo $first;
echo $second;
}
}
That is because you have already been redirected to the page before the line execution.
Instead add an alert like this.
if($first == "" && $second== "")
{
echo "<script>alert('Username should be alpha numeric characters only.');</script>"; //<-- Added here
echo "<script language='javascript'>window.location = 'main.php';</script>";
}
It's because the redirect occurs and the PHP isn't executed. What you can do is set a GET param in your redirect.
echo "<script language='javascript'>window.location = 'main.php?error=1';</script>";
And on main.php
if(isset($_GET['error']) && $_GET['error'] == 1) { do code ... }
When you need to go back to main.php the javascript simply loads that page.
As far as I know, you will have to implmenent some sort of a checking method that will store your error codes on sessions or cookies and then write a check to display the messages if there are errors. You will have to clear the errors saved once main.php is loaded by the way.
Or you can pass on the error messages through $_GET by modifying your javascript.
Your javascript could look like
window.location = "main.php?err=1";
You can set your main.php to
if(isset($_GET['err'])) {
//Your logic to check the error message number and display text goes here
}
Ideal would be to verify on the client side using javascript/jquery but since you mentioned this to be a server side verification you will have to either use a framework that has all the foundation laid for such kind form validation (using a framework has many pros and cons so I am not sure if this feasible to you. Just putting it out there), or write your own small logic to check and revert back to the main page with the error codes.

give a user X number of chances to input a value in PHP

Hi I am a newbie learning PHP ( & on stackoverflow too)- I am trying to solve a simple problem but unable to do. I hae already searched on google and stackoverflow before posting a question as I didnt want to waste other time but for a week now am unable to solve this issue.
I am writing a simple program in php that lets user input a number and checks if the value entered is 5. If true it echo's "you win" else "try again". I am able to do this
The tricky part for me is I want to give him only 10 chances and try as I might using basic PHP am unable to do this. Have tried using if, for, do while but am unable to "loop the html"..I dont know jquery etc and am trying to accomplish this with PHP only. I havent yet progessed to learning sessions etc. Thanks in advance
<html>
<body>
TRY AND GUESS THE NUMBER
<br/>
<br/>
<form method="POST" action="gullible.php">
Please enter any number :<input type="text" name="num">
<input type="hidden" name="cnt" value=<?php $cnt=0 ?>>
<input type="submit" name="go">
</body>
</html>
<?php
$i=0;
if ($_POST['num']!=5)
{
$i++;
echo $i;
echo " Please try again";
}
else
echo "You win the game";
?>'
You need to store the variable in some manner such that it persists. in your script, you are setting $i to 0 each time it runs. Plus you are setting the value incorrectly in your hidden input.
One way of doing this is using a Session variable, such as $_SESSION['cnt']
My PHP is a bit rusty, but here's an example using Session variables:
$max_guesses = 10;
if( !isset($_SESSION['cnt']) ){
$_SESSION['cnt'] = 0;
}
if( $_SESSION['cnt']++ > $_max_guesses ){
echo "Maximum tries exceeded";
} else {
echo "Try again";
}
If you don't want to, or can't use a session variable, you could use the hidden input field, like you tried to:
<?php
if( !isset($_POST['cnt']) ){
$cnt = 0;
} else {
$cnt = $_POST['cnt'];
}
if( $cnt++ > $_max_guesses ){
echo "Maximum tries exceeded";
} else {
echo "Try again";
}
?>
<input type='hidden' name='cnt' value='<?php echo $cnt ?>' />
(Note if your form uses GET instead, just replace $_POST with $_GET or you can use $_REQUEST if you're not sure, but probably better not to.
After successful login of the user set the chances variable to 10 like this.
$_SESSION['nofchances']=10;
After setting this flag on the successful authentication page. Redirect to your PLAIN html code.
EDITED :
question.html
<html>
<body>
TRY AND GUESS THE NUMBER
<br/>
<br/>
<form method="POST" action="gullible.php">
Please enter any number :<input type="text" name="num">
<input type="submit" name="go">
</body>
</html>
gullible.php
<?php
if($_SESSION['nofchances']!=0)
{
if ($_POST['num']!=5)
{
$_SESSION['nofchances'] = $_SESSION['nofchances'] - 1;
echo "You have ".$_SESSION['nofchances']." no of chances to try";
echo "<br>Please try again";
header("location:question.html");
}
else
{
echo "You won the game";
$_SESSION['nofchances']=10; // resetting back
}
}
else
{
echo "Your chances expired";
}
?>
You can call a function in onBlur/onChange
<script>
function test()
{
var count=<?php echo $count;?>;
var guess=parseInt($('#hid_num').val())+1;
if(guess>count)
{
alert('Your chances over!');
}
else
{
$('#hid_num').val(guess);
}
}
</script>
<input type="text" onblur="test();" id="chk_estimate" />
<input type="hidden" value="0" id="hid_num" /></body>
If you dont want to use sessions yet you could define a hidden input field which stores the current try then incriment "+1" it whenever the submit is pressed / the site is reloaded. Something like:
if( isset($_POST['try']) ) {
$try = $_POST['try'];
$try += 1;
} else {
$try = 0;
}
add the hidden field in your form like:
$hiddenTry = '<input type="hidden" value="'. $try .'" name="try"/>';
and add a if clause to when to show the form like:
if ( $try <= 10 ) {
//your form
}
i made this for you i hope it can help you learn something new (i edited it a couple of times to make variable names easier to understand make sure you check it again - i added a cheat also :) )
<?php
session_start(); // with this we can use the array $_SESSION to store values across page views of a user.
mt_srand(time()); // this is to ensure mt_rand function will produce random values. just ignore it for now. it's another story :)
$max_tries = 10; // limit of guesses
$_SESSION['the_magic_number']=!isset($_SESSION['the_magic_number'])?mt_rand(0,100):$_SESSION['the_magic_number'];
// the previous line is a one-liner if then else statement. one-liners works like this:
// $my_name_will_be=($isBoy==true)?"George":"Mary";
if(isset($_POST['num'])) // if this pageview is from a valid POST then...
{
$_SESSION['current_try']=isset($_SESSION['current_try'])?$_SESSION['current_try']+1:1;
// one-line if then else again. This increases the try user is now, or resets it to one
}
?>
<html>
<body>
TRY AND GUESS THE NUMBER
<br/>
<br/>
<?php
if ($_SESSION['current_try']<=$max_tries) // if user has more tries available
{
if(intval($_POST['num'])==$_SESSION['the_magic_number']) // did he found it?
{
echo "You found it! Gongratulations! Click <a href=''>here</a> to try again!";
// oh and do not forget to reset the variables (you found this bug, well done!)
$_SESSION['current_try']=1;
$_SESSION['the_magic_number']=NULL;
}
else
{
// if he didn't found it, display the status of tries left, and the form to try again
echo "This is your try ".($_SESSION['current_try'])." of ".$max_tries." Good Luck!";
?>
<form method="POST" action="mygame.php">
Please enter any number :
<input type="text" name="num"/>
<input type="hidden" name="tries" value="<?php echo (isset($_POST['tries']))?$_POST['tries']-1:$max_tries; ?>"/>
<input type="submit" name="go"/>
</form>
<span style="color:white;background-color:white;"><?php echo "You bloody cheater! The magic number is ".$_SESSION['the_magic_number'];?></span>
<?php
}
}
else
{
// here we are if no tries left! An empty href to reload the page, and we resetting our variables.
// the_magic_number gets NULL so at the start of script it will be "not set" and will get a mt_rand(0,100) value again
echo "You lost! Sorry! Click <a href=''>here</a> to try again!";
$_SESSION['current_try']=1;
$_SESSION['the_magic_number']=NULL;
}
?>
</body>
</html>
the span at the end is a cheat ;) press ctrl+a to use it !!!

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