I have the following code for submitting a form - it doesn't do much at the moment but what I am looking to achieve is this:
The textbox docTitle is a required field.
If the yourName textbox has text in it and the docTitle textbox is left blank, when submitted the required field message appears and the yourName textbox retains it's value.
I'm struggling with the part where the form retains the previous values after submitting.
Here's the code:
<?php
if(isset($_POST['submit'])) {
if(empty($docTitle)) {
} else {
if ((($_FILES["file"]["type"] == "application/pdf")) && ($_FILES["file"]["size"] < 2000000) && ($_POST["docTitle"] > "")) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"];
if (file_exists("upload/pdf/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES['file']['tmp_name'],
"upload/pdf/" . $_FILES["file"]["name"]);
}
}
}
else
{
echo "Invalid file";
}
}
}
?>
<form name="uploadAPdf" id="uploadAPdf" action="<?php $_SERVER['PHP_SELF'] ?>" method="post" enctype="multipart/form-data">
<label for="text">Name: </label> <input type="text" name="yourName" id="yourName" /><br />
<label for="text">Document: </label> <input type="text" name="docTitle" id="docTitle" />
<?php if(isset($_POST['submit']) && empty($docTitle)) {
echo " Document title must be filled in...";
echo "<script type='text/javascript'>document.uploadAPdf.docTitle.focus();</script>";
} ?>
<br />
<label for="file">Select PDF to upload: </label> <input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
Isn't this what you want:
<?php
function postValue($name, $alt = '') {
return isset($_POST[$name]) ? $_POST[$name] : $alt;
}
?>
<label for="text">Name: </label> <input type="text" name="yourName" id="yourName" value="<?=htmlspecialchars(postValue('yourName'))?>" /><br />
<label for="text">Document: </label> <input type="text" name="docTitle" id="docTitle" value="<?=htmlspecialchars(postValue('yourName'))?>" />
That's (sort of) how most Forms work...
Maybe I'm missing something =)
edit
This is a function I used to use when I didn't use a PHP framework:
<?php
function ifsetor($var, $alt = '') {
return isset($var) ? $var : $alt;
}
?>
which would be used like this:
<?php
$selectedOptions = ifsetor($_POST['options'], array());
?>
edit
Unrelated: you might want to put your form elements in a wrapper (instead of separating them with a <br>) like this:
<div class="form-element"><label>...</label><input .... /></div>
change your html input(s) code to:
<input type="text" name="docTitle" id="docTitle" value="<?php echo htmlspecialchars($_POST['docTitle']; ?>" />
Related
I want to validate if the textbox has a value or not. Right now what I have is a textbox that has a value but the output says it is empty here is it it is like nothing is being conditioned on the code please see me code, thank you
Full Code
-Here is the full code of my form please take a look thank you very much
<form>
<div class="row">
<form method="POST">
<div class="col-md-8">
<?php
$code = 'Code';
$code2 = 'PIN';
if(isset($_POST['btnSubcode'])) {
$lblCode = isset($_POST['lblQrTxt']) ? $_POST['lblQrTxt'] : '';
$code = $lblCode;
$code = explode(":",$code); // code = array("QR Code","444444444|123")
$code = explode("|",$code[1]); // code[1] = "444444444|123"
$code = trim($code[0]); // 444444444
$code2 = $lblCode;
$code2 = explode(":",$code2); // code = array("QR Code","444444444|123")
$code2 = explode("|",$code2[1]); // code[1] = "444444444|123"
$code2 = trim($code2[1]); // 123
}
?>
<div class="form-group">
<label class="form-control-label">code</label>
<input type="text" name="input" id="card-code" value='<?php echo $code ?>' class="form-control">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-control-label">pin</label>
<input type="text" id="card-pin" value='<?php echo $code2 ?>' class="form-control" maxlength="3">
</div>
<?php
if(isset($_POST['txtQrtxt']) && $_POST['txtQrtxt'] != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
<div class="caption">
<div class="jumbotron">
<input type="text" name='txtQrtxt' value='Hello World' class="form-control" >
<textarea class="form-control text-center" id="scanned-QR" name="lblQrTxt"></textarea><br><br><br>
</div>
</div>
</form>
<div class="form-group float-right">
<input value="Topup" class="btn btn-primary topup-button">
</div>
</div>
</div>
</form>
<?php
$txtCodeqr = isset($_POST['txtQrtxt']) ? $_POST['txtQrtxt'] : '';
if (!empty($txtCodeqr)) {
echo "Text";
} else {
echo "Empty Textbox";
}
?>
my textbox
<input type="text" name='txtQrtxt' value='Hello World' class="form-control" >
You might be over complicating it. It is pretty simple.
<?php
if(isset($_POST['txt']) && $_POST['txt'] != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
Additionally I would recommend you filter all input on post or get. Basically anything that gets information from a user.
Check here - http://php.net/manual/en/function.filter-input.php
<?php
$my_txt = filter_input(INPUT_POST, 'txt');
if(isset($my_txt) && $my_txt != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
Also you need to add a submit button between your form tags. Like this.
<input type="submit" value="Submit">
Also you should have only one closing tag for every opening tag. This is called valid HTML.
For example a valid form is like
<form method="post">
First name:<br>
<input type="text" name="firstname" value="Mickey"><br>
Last name:<br>
<input type="text" name="lastname" value="Mouse"><br><br>
<input type="submit" value="Submit">
</form>
Ok I have made a simple php test file and tested it works. Your problem is:
You don't have a submit button. The $_POST will not be there if you do not submit a form first.
It would be easier to validate your textarea using javascript instead.
Here is my test file and it works:
<html>
<body>
<form method="POST">
<textarea name="txtQrtxt">
</textarea>
<input type="submit">
</form>
<?php
$var = $_POST['txtQrtxt'];
if (strlen($var)<=0) {
echo "Textarea empty";
} else {
echo "Textarea Okay";
}
?>
</body></html>
Here is my code:
<h2> Simple Form </h2>
<form action="" method="post">
First Name: <input type="text" name="firstName">
Last Name: <input type="text" name="lastName"><br /><br />
<input type="submit">
</form>
<br />
Welcome,
<?php
echo $_POST['firstName'];
echo " ";
echo $_POST['lastName'];
?>
!
<hr>
<h2>POST Form</h2>
<h3>Would you like to volunteer for our program?</h3>
<form action="" method="post">
Name: <input type="text" name="postName">
Age: <input type="text" name="age"><br /><br />
<input type="submit">
</form>
<br />
Hello,
<?php
echo $_POST['postName'];
?>
!
<br>
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$age = $_POST['age'];
if ($age >= 16) {
echo "You are old enough to volunteer for our program!";
} else {
echo "Sorry, try again when you're 16 or older.";
}
}
?>
<hr>
<h2>GET Form</h2>
<h3>Would you like to volunteer for our program?</h3>
<form method="get" action="<?php echo htmlspecialchars($_SERVER["REQUEST_URI"]); ?>">
<input type="hidden" name="p" value="includes/forms.php">
Name: <input type="text" name="getName">
Age: <input type="text" name="age"><br /><br />
<input type="submit">
</form>
<br />
Hello,
<?php
echo $_GET['getName'];
?>
!
<br>
<?php
if ($_SERVER['REQUEST_METHOD'] == "GET") {
$age = $_GET['age'];
if ($age >= 16) {
echo "You are old enough to volunteer for our program!";
} else {
echo "Sorry, try again when you're 16 or older.";
}
}
?>
I have two forms. Both displaying the exact same thing, but one form using POST and one using GET.
I have gotten so close to finishing this off but now I have another small/weird issue.
The code technically works correctly, but here's the output explanation:
when I first open up the page the GET form already has the result "Sorry, try again when you're 16 or older." When I fill out the first 'simple' form, it displays the result correctly but then the POST form shows the "Sorry, try again..." result. Then, when I fill in the information and click submit, it displays the correct result and the other two forms are blank as they're supposed to be, and then the same result when I fill out the GET form.
Any help on this is much appreciated.
Try this code :
<h2> Simple Form </h2>
<form action="" method="post">
First Name: <input type="text" name="firstName">
Last Name: <input type="text" name="lastName"><br /><br />
<input type="submit">
</form>
<br />
Welcome,
<?php
if (isset($_POST['firstName']) && $_POST['lastName'])
{
echo $_POST['firstName'];
echo " ";
echo $_POST['lastName'];
}
?>
!
<hr>
<h2>POST Form</h2>
<h3>Would you like to volunteer for our program?</h3>
<form action="" method="post">
Name: <input type="text" name="postName">
Age: <input type="text" name="age"><br /><br />
<input type="submit">
</form>
<br />
Hello,
<?php
if (isset($_POST['postName']))
{
echo $_POST['postName'];
}
?>
!
<br>
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if (isset($_POST['age']))
{
$age = $_POST['age'];
if ($age >= 16)
{
echo "You are old enough to volunteer for our program!";
}
else
{
echo "Sorry, try again when you're 16 or older.";
}
}
}
?>
<hr>
<h2>GET Form</h2>
<h3>Would you like to volunteer for our program?</h3>
<form method="get" action="<?php echo htmlspecialchars($_SERVER["REQUEST_URI"]); ?>">
<input type="hidden" name="p" value="includes/forms.php">
Name: <input type="text" name="getName">
Age: <input type="text" name="age"><br /><br />
<input type="submit">
</form>
<br />
Hello,
<?php
if (isset($_GET['getName']))
{
echo $_GET['getName'];
}
?>
!
<br>
<?php
if ($_SERVER['REQUEST_METHOD'] == "GET")
{
if (isset($_GET['age']))
{
$age = $_GET ['age'];
if ($age >= 16)
{
echo "You are old enough to volunteer for our program!";
}
else
{
echo "Sorry, try again when you're 16 or older.";
}
}
}
?>
Please try this. I hope it will help.
Replace
if ($_SERVER['REQUEST_METHOD'] == "POST") {
with
if (isset($_POST['age'])) {
Similarly,Replace
if ($_SERVER['REQUEST_METHOD'] == "GET") {
with
if (isset($_GET['age'])) {
When you first enter on page, default REQUEST_METHOD is GET so you should check if isset($_GET['age']) {
and here check if it is more than 16
}
also you should check this one
echo $_GET['getName']; and change on this
echo isset($_GET['getName']) ? $_GET['name'] : "";
You should also check $_POST request like this and your program will work correctly.
I am new to php and web development. I am trying to do a simple validation of text field. I want to display a red remark beside the text field after submit button was clicked.
However my problem here is: The php codes validates all input field the moment the page was loaded. How to validate it only after user clicked the submit button?
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name <input type='text' name='name' /><br>
Email <input type='text' name='email' /><br>
Age<input type='text' name='age' /><br>
<input type='submit' name='Done' /><br><br>
</form>
<?php
if(empty($POST['name']))
echo '<font color="red">Please enter your name.</font>';
if(empty($POST['email']))
echo '<font color="red">Please enter your email.</font>';
if(empty($POST['age']))
echo '<font color="red">Please enter your age.</font>';
?>
I have several questions here:
1) If I want to display the error message right beside each text field, shall I write a separate php code beside each input field?
2) How to echo the error message only after user clicked the submit button?
I know this is extremely simply to many people here, but this is my first time doing something related to the web.
Just check if post is send
<?php
if($_POST)
{
if(empty($POST['name']))
echo '<font color="red">Please enter your name.</font>';
if(empty($POST['email']))
echo '<font color="red">Please enter your email.</font>';
if(empty($POST['age']))
echo '<font color="red">Please enter your age.</font>';
}
?>
Please note:
<input type='submit' name='Done' /><br><br>
should be outside the PHP markup.
To display the errors beside each element, just move your if statements to the place where it should be displayed in the HTML.
Most developers use javascript for form validation. A quick Google will give you a lot information about this.
Use $_SERVER['REQUEST_METHOD'] to detect whether the page is being displayed in response to posting the form.
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (empty($_POST['name'])) {
echo '<span style="color: red;">Please enter your name.</span>';
}
if(empty($_POST['email'])) {
echo '<span style="color: red;">Please enter your email.</span>';
}
if(empty($_POST['age'])) {
echo '<span style="color: red;">Please enter your age.</span>';
}
}
If you want to show them separately next to each input, you can write:
Name <input type='text' name='name' /> <?php
if ($_SERVER['REQUEST_METHOD'] == "POST" && empty($_POST['name'])) {
echo '<span style="color: red;">Please enter your name.</span>';
} ?><br>
Note that the variable containing POST parameters is $_POST, not $POST.
Just add a hidden input to your form.
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name <input type='text' name='name' /><br>
Email <input type='text' name='email' /><br>
Age<input type='text' name='age' /><br>
<input type='submit' name='Done' /><br><br>
<input type="hidden" name='form' value='wasSubmited' />
</form>
Then in the PHP script check $_POST:
if ($_POST['form'] == 'wasSubmited') {
// here you can start to validate your form
}
To follow the DRY system you can simplify your code a little and make it easy to adjust in case you add more fields to your form in the future. You only have to add your new fieldname(s) to the $fields array. It is also much easier to adjust the HTML in case you want another class or something.
if(whatever condition you need)
{
$fields = array('name', 'email', 'age');
foreach ( $fields as $field ) {
if(empty($POST[$field]))
echo '<font color="red">Please enter your ' . $field . '.</font>';
}
}
}
try this i used your form working 100% =)
<script>
function ValidateForm() {
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var age = document.getElementById('age').value;
if (name == "" && email == "" && age == "")
{
document.getElementById("error_name").innerHTML = "Please enter your name<br/>";
document.getElementById("error_email").innerHTML = "Please enter your email<br/>";
document.getElementById("error_age").innerHTML = "Please enter your age";
return false;
}
else if (name == "")
{
document.getElementById("error_name").innerHTML = "Please enter your name<br/>";
return false;
}
else if (email == "")
{
document.getElementById("error_email").innerHTML = "Please enter your email<br/>";
return false;
}
else if (age == "")
{
document.getElementById("error_age").innerHTML = "Please enter your age";
return false;
}
}
</script>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" onSubmit="return ValidateForm()">
Name <input type='text' id="name" name='name' /> <span id="error_name" style="color:red;"></span> <br>
Email <input type='text' id="email" name='email' /> <span id="error_email" style="color:red;"></span><br>
Age<input type='text' id="age" name='age' /> <span id="error_age" style="color:red;"></span><br>
<input type='submit' name='Done' /><br><br>
</form>
Here is a pure php printing the error right beside the form fields
<?php
$fieldErrors = array();
if(isset($_POST['Done']))
{
$fields = array('name', 'email', 'age');
foreach ($fields as $field)
{
if($_POST[$field] == "")
{
$fieldErrors[] = $field;
}
}
}
if(count($fieldErrors) > 0)
print_r($fieldErrors);
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name <input type='text' id="name" name='name' /> <span id="error_name" style="color:red;"><?php echo (count($fieldErrors) > 0 && in_array("name", $fieldErrors)) ? 'Please Enter your name' :''; ?></span> <br>
Email <input type='text' id="email" name='email' /> <span id="error_email" style="color:red;"><?php echo (count($fieldErrors) > 0 && in_array("email", $fieldErrors)) ? 'Please Enter your email' :''; ?></span><br>
Age<input type='text' id="age" name='age' /> <span id="error_age" style="color:red;"><?php echo (count($fieldErrors) > 0 && in_array("age", $fieldErrors)) ? 'Please Enter your age' :''; ?></span><br>
<input type='submit' name='Done' /><br><br>
</form>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
<!DOCTYPE = "HTML">
<html>
<head>
<meta charset = "UTF-8">
</head>
<body>
<p1><h1>Guitar Wars - High Scores</h1></p1>
<hr />
<p2> The screenshot must be an image file no greater than 2MB in size.</p2>
<form enctype="multipart/form-data" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="MAX_FILE_SIZE" value="2100000" />
<label for="name">Name: </label>
<input type="text" id="name" name="name" /><br />
<label for="score">Score: </label>
<input type="text" id="score" name="score" /><br />
<label for "screenshot">Screen shot: </label>
<input type="file" id="screenshot" name="screenshot" />
<hr />
<input type="submit" name="submit" value="Add" /><br />
</form>
<?php
$name = $_POST['name'];
$score = $_POST['score'];
$screenshot = $_FILES['screenshot']['name'];
$screenshot_type = $_FILES['screenshot']['type'];
$screenshot_size = $_FILES['screenshot']['size'];
require_once('appvars.php');
if (isset($_POST['submit'])){
// Level 1
if ((!empty($name) && !empty($score)) {
// Level 2
$db = mysqli_connect('localhost','****','****','guitarwars') or die('cannot connect to server');
$query = "INSERT INTO scoreboard (date, name, score, screenshot) VALUES (NOW(),'$name', '$score', '$screenshot')";
$result = mysqli_query($db,$query) or die (mysqli_error($db));
echo $name.', your score has been added successfully!<br><br>';
if (($_FILES['screenshot']['error'] == 0) && ((($screenshot_type == 'image/gif') || ($screenshot_type == 'image/jpeg') || ($screenshot_type == 'image/png')) && (($screenshot_size > 0) && ($screenshot_size <= GW_MAXSIZE)))){
// Level 3
echo "File name: ".$screenshot."<br>";
echo "Type: " . $screenshot_type . "<br>";
echo "Type: " . $screenshot_size . " bytes<br>";
$target = GW_UPLOADPATH.$screenshot;
$move = move_uploaded_file($_FILES['screenshot']['tmp_name'], $target);
}
else {
// Level 3
echo '<p class = "error">Adding score failed, you can upload only image file under 2MB in size.'.$_FILES['screenshot']['error'].'</p>';
}
}
else {
// Level 2
echo '<p class = "error">Adding score failed, you must fill all the fields.</p>';
}
mysqli_close($db);
}<--- this is the last bracket
?>
<p>Go to the scoreboard!</p>
</body>
</html>
My text-editor(coda) sounds beep(alert) when I move cursor over the last bracket'}'. However I can't figure out what's wrong with that bracket.
And I added codes for displaying errors which neither works.
Thank you in advance.
Your problem is in this line:
if ((!empty($name) && !empty($score)) {
You have a ( to many.
It should be:
if (!empty($name) && !empty($score)) {
if ((!empty($name) && !empty($score)) {
You have too few ) here, which is causing the {...} around it (your "Level 1" braces) to overlap the () parentheses.
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?>