Nothing happens when you click the submit button at the bottom of the page. I simply want it to validate user input and I am only focused on the name field at the moment and I cannot get it to validate any input in the name field. No error messages pop up or anything. Please review this and offer any suggestions, I cannot find my error.
PHP portion, where variables are initialized and set to empty. As well as the post methods and isset functions
<?php
//define variables and set them to empty values
$fname_error= $phone_error= $address1_error= $address2_error= $city_error= $state_error= $zipcode_error= "";
$fname= $phone= $address1= $address2= $city= $state= $zipcode= "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
$fname_error = "Missing";
}
else {
$fname = test_input($_POST["fname"]);
//now we check to see that the name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
$fname_error = "Please use letters and white space only";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
The Html portion:
<div class="userinput">
<label for="fname"><b>First Name</b></label>
<input type="text" name="fname" value="<?php
echo $fname ?>">
<span class="error">
<?php echo $fname_error;?></span>
</div>
Good day. This is just a hypothesis, I may be wrong as I couldn't check the entire code, but you cannot have more than 1 form on the same page. Because, you need a single opening and closing form tag that wraps ALL form elements on your page. Form fields are only counted as part of a form if they are contained within the form elements. And you do have more than 1 form on the same page.
Also, you should consider minimizing your code to only what's needed.
Hope this helps!!!
Related
I am trying to save the input from a PHP form onto the action page.
So for example, the form is on /world/play/create/create.php, and onsubmit leads to /world/play/create/index.php?id=(6DIGIT#) the input of the username from the first URL would be echoed onto the action and saved to the page, so that any user can go back and see it.
However, when I run this code (below), it displays the username on the tab that submitted the form, but other users that go to the link can't see that username when they join; each person can only see their own username.
I'm trying to make it so that each person can see theirs input AND everyone else's, but right now it only shows their own.
Currently this is what I have so far:
The URL:
/world/play/create/index.php?id=M12345
The form (on first link):
<form id="access" method="post" action="/world/play/create/index.php?id=" onsubmit="this.action=this.action.split('#')[0]+'M'+(Math.floor(Math.random()*(75800-39408))+30938);phpValue();">
<input autocomplete="off" type="text" name="nameP1" id="unm" placeholder="Username" value="<?php echo $nameP1;?>">
<br>
<div style="line-height:10px"> </div>
<input type="submit" value="CONTINUE" onclick="return checkInput()">
</form>
The PHP (on second link):
<?php
$nameErr = "";
$nameP1 = "";$nameP2 = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["nameP1"])) {
$nameErr = "Name is required";
} else {
$nameP1 = test_input($_POST["nameP1"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$nameP1)) {
$nameErr = "Only letters and white space allowed";
}
}
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["nameP2"])) {
$nameErr = "Name is required";
} else {
$nameP2 = test_input($_POST["nameP2"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$nameP2)) {
$nameErr = "Only letters and white space allowed";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
And finally, the PHP echo (on second link):
<span id="playerName"><?php echo $nameP1; ?></span>
If you want to save the variables in the URL you should change the form method to GET instead of POST.
Change the $_POST variable in your code on your second php file to $_GET.
More info :
http://php.net/manual/en/tutorial.forms.php#37899
I have a form inside the footer, I'm running the php file at the localhost 127.0.0.1/form.php, apparently if one uses php code inside HTML it will just be commented out. From what I understood at the PHP Documentation I need to run the php file directly.
The code is based on the W3Schools PHP Form Required tutorial:
<!DOCTYPE html>
<html>
<body>
<footer>
<form method="post" action="form.php">
<input type="text" name="name" placeholder="Name"><span class="form-error">*<?php echo $nameError;?></span><br>
<input type="submit" value="Send">
</form>
<?php
// define variables and set to empty values
$name = ""; // The variable is defined at the global scope
$nameError = ""; // The error variable is defined at the global scope
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($POST['name'])) {
$nameError = 'Name required'; }
else {
$name = test_input($_POST["name"]); }
}
// The function that will validate the form
function test_input($data) {
$data = trim($data); // The data is stripped of unnecesary characters
$data = stripslashes($data); // Backslashes '\' are removed
$data = htmlspecialchars($data); // Converts special characters into HTML entities
return $data
}
?>
If I left the text blank it wouldn't echo the error at the span, so I tried debugging it
<?php
// Debugging test_input($data)
echo $name;
echo "<br>";
echo $nameError;
echo "<br>";
?>
No matter what I submit at the input, the $name is always blank whereas the $nameError is always echoed.
So I thought that maybe the function isn't returning anything, and I did a little more debugging
// Debugging without the function
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
echo $name;
echo "<br>";
}
// Debugging after each iteration of whats inside the function (without return)
$data = trim($data); // The data is stripped of unnecesary characters
echo $name;
echo "<br>";
$data = stripslashes($data); // Backslashes '\' are removed
echo $name;
echo "<br>";
$data = htmlspecialchars($data); // Converts special characters into HTML entities
echo $name;
echo "<br>";
?>
If I introduce, for instance, & \ a my output is:
*a blank line*
Name required
& \ a
& \ a
& \ a
& \ a
Apparently the php built in functions aren't doing what they are supposed to do. stripslashes($data) did not remove the backslash and the & should look as & after going through htmlspecialchars($data).
I even commented everything inside test_input($data) so that it looked like this
function test_input($data) {
return $data }
And still would get nothing. Any ideas why? Also, why is the function test_input($data) defined later in the script instead of being defined before (tried to put it before defining my variables and still would not work). Thanks in advance.
"You have a typo: empty($POST['name']) should be empty($_POST['name'])" #Magnus Eriksson
"Because you define and set the variable $nameError after you're trying to echo it." #Magnus Eriksson
I have a page which takes input data from users trying to create a new account on my website. Although I want to check the values of the data before the page is redirected to send the input data to the database. I have created a verification form which redirects back to the same page when the user clicks submit, so as to check the values, but if all the values are okay, then I want to send the parameters inputted to another page which will input them in the database. Is there a way to do this conditionally in PHP? I've tried to implement it with a simple boolean checking if any of the parameters inputted are incorrect, but don't know how to send the params along with the redirection.
Here is a shortened version of the code with just some of the forms:
<?php
// Connection to database
include_once("createConnection.php");
$hasErrors = false;
$errorFName = $errorLName = $errorEmail = "";
$fName = $lName = $email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fName"])) {
$errorFName = "This field is required.";
$hasErrors = true;
}
else {
$name = validation($_POST["fName"]);
//name cannot contain any symbols or numbers
if (!preg_match("/^[a-zA-Z ]*$/",$fName)) {
$errorFName = "Only letters and white space allowed";
$hasErrors = true;
}
}
if($hasErrors==false){
**???**
}
function validation($input) {
$input = trim($input);
$input = stripslashes($input);
$input = htmlspecialchars($input);
return $input;
}
?>
<form class="loginForm" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table class="loginTable">
<tr>
<td><label for="newDetail">First Name: </label>
<input type="text" class="formBox" value="" id="newDetail" name="fName">
<?php echo $errorFName;?>
</td>
</tr>
<tr>
<td><label for="newDetail">Password: </label>
<input type="text" class="formBox" value="" id="newDetail" name="pword">
</td>
</tr>
<tr>
<td><button type="submit" class="loginButton" name="submitNew">Submit</button></td>
</tr>
</table>
</form>
Thanks!
You could store the $_POST variables in sessions.
$_SESSION["firstname"] = $_POST["fname"];
Then redirect to the required page
header("location: welcomepage.php");
Then grab the variables from the session and process, maybe insert to database for future use.
$firstname = $_SESSION["firstname"];
You could redirect manually with a <meta http-equiv="refresh">:
echo '<meta http-equiv="refresh" content="0, welcomepage.php?params=params">';
I'm not quite sure why you would like to pass parameters to other page - it qould be much easier to process them right here. If it is a general messines of the code you dislike - you can pass data to a function or a method from an included file.
However, if it is really necessary to save data from a separate page I would recommend sending them via cURL:
$post = array(/*put all your variables here*/);
$params = http_build_query($post);
$url = 'http://your.domain.com/receiver.php';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
$result = curl_exec($curl);
This way anything you would output on the receiving page will end up in $result, so you can confirm to a user that his/her data was saved.
NB: whatever you would end up doing - do NOT pass the data to the receiving page as GET. It is insecure and every time someone does this a puppy dies!
More info on curl: http://php.net/manual/en/book.curl.php
Recently I built a form using HTML, CSS, and JavaScript. I then entered the PHP required to send the data that is inputted in the form, to my database. After I finished, what I thought was necessary for it to work, I ended up with a blank page when I executed the code. The form and everything disappeared. This is my PHP code:
<?php
require("$_SERVER[DOCUMENT_ROOT]/connect.php");
$email = $username = $type = $question = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if(!empty($_POST))
{
if(isset($_POST["email"], $_POST["username"], $_POST["type"], $_POST["question"])
{
$email = test_input($_POST["email"]);
$username = test_input($_POST["username"]);
$type = test_input($_POST["type"]);
$question = test_input($_POST["question"]);
$premium = ($_POST["premium"]);
$member = $_POST["member"];
$terms = $_POST["terms"];
if ($member != "NO")
{
$member = "YES";
}
}
if(!empty($email) && !empty($username) && !empty($type) && !empty($question) && !empty($terms))
{
$insert = $db->prepare("INSERT INTO QuestionSubmission (Email, Username, Type, Question, Member, Premium, Date) VALUES (?, ?, ?, ?, ?, ?, NOW())");
$insert->bind_param("ssssss", $email, $username, $type, $question, $member, $premium);
if($insert->execute())
{
header("Location: landing.php");
die();
}
}
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
The "member" part is a check box where the user can optionally select to become a member. It is unchecked initially, and i've set a value of "NO" for that. Also, there is a hidden check box that is already checked with a value of NO...this is the "premium" check box. Lastly, there is a check box for agreeing to the terms. This is initially unchecked, but the user has to check it so it won't be empty and for the form to process.
Could you please explain what I have to do in order for my form to work properly?
Also, the " require("$_SERVER[DOCUMENT_ROOT]/connect.php"); " part is where my connection to the database code is located. This code and the form code is located in the same page.
Replace require("$_SERVER[DOCUMENT_ROOT]/connect.php"); with require_once $_SERVER[DOCUMENT_ROOT]."/connect.php");, you're not using a variable - the $_SERVER can't be used like you're using it. This is why you're getting a "blank page of death", if you check your error_log you'd see that it has a syntax-error because of it.
Furthermore, you're checking if(!empty($_POST)) - this could really be any POST-form. You should remove this code
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if(!empty($_POST))
{
as you're checking if the inputs are set just below the above code.
As a final note, when you're using die();, you should use exit; instead. They really do the same thing, but usage of die() is more for error-checking, like "Script can't run any further - die now!", while exit; is more like "I would like to stop the script from running now, I'm done - thanks!".
Normally it’s easier to include the processing code inside the form page. That way, if you encounter errors, you can:
allow the code to fall through to the form again
persist old values by using the value="…" attribute
Roughly it looks like this:
<?php
$email=$username=''; // etc
if(isset($_POST['submit'])) { // or whatever you name the submit button
// validate data
if(!$errors) {
// process
// new location
}
// retain values from above
}
?>
<form>
<label>Name: <input type="text" name="username" value="<?php print $username; ?>"></label>
<label>Email: <input type="text" name="email" value="<?php print $email; ?>"></label>
<!-- etc -->
<button type="submit" name="submit">Send Message</button>
</form>
For ease and management, you can put the PHP code above into a separate file to be included.
The problem your sample above is that although you do redirect to a new page on success, you don’t go anywhere otherwise.
If you want to do it with a separate processing script, you will need to conclude by redirecting back to the original form on failure. However, you will find that persisting old data is more difficult that way.
What I want is to show the error (message), only if the user do a false action. For example, if the field is empty, it will show (Please fill all the fields). I've already done that, but the problem that I have is that it shows also if the user enter to the page for the first time, meaning it does NOT respects the (if condition) that I have written !
The question :
How to show the message only if one of the fields is empty ?
Any ideas on how I can solve it ?
Here is my code :
<?
$conn = mysqli_connect('localhost', 'db', 'db_pass', 'db_name') or die("Error " . mysqli_error($conn));
$email = filter_var(trim($_POST['email']), FILTER_VALIDATE_EMAIL);
$old_password = trim($_POST['old_pass']);
$new_password = trim($_POST['new_pass']);
$email = mysqli_real_escape_string($conn,$email);
$old_password = mysqli_real_escape_string($conn,$old_password);
$new_password = mysqli_real_escape_string($conn,$new_password);
if(empty($email) || empty($old_password) || empty($new_password)){
echo 'Please fill all the fields !<br>';
}
else{
$sql="UPDATE users SET pass='$new_password' WHERE email='$email' AND pass='$old_password'" or die("Error " . mysqli_error($conn));
$result = mysqli_query($conn,$sql);
mysqli_close($conn);
}
if($result){
echo'Password changed successfully !';
}
elseif(!$result) {
echo 'The email/password you provided is false !';
}
?>
Validation of any form happens in the "action" file within a condition i.e. the validation should be subjected to the event of user clicking the submit button. For this to work you should check that
1. Your form has a submit button with a name property set to say submit (can be anything)
eg: <input type="submit" name="submit" id="someid" value="Submit" />
2. The form must have action property pointing to a processor file
eg: <form action = "somefile.php" method = "post">
3. In the somefile.php file the validation code must be within a condition which checks for the event of form been submited
eg://somefile.php
<?php
if(isset($_POST['submit']{
//all the validation code goes here
}else{
//for a single page form and validation
// the code for displaying the form can go here
?>
I suggest you to do this:
First define a variable with plain $_POST[] for eg $name = $_POST['name'];
Then, check if all the vatiables you've define are empty or not.
Lastly, Use escape_string() or whatever you want.
The solution is to check for a variable that you know will always be set if the form is submitted, usually the submit button.
For example, if your form ends like this:
...
<input type="submit" name="change_password" value="Change password" />
</form>
then in the PHP code you could check
if(isset($_POST['change_password'])) {
// The submit button was in the POSTed data, so this is a form submit
} else {
// This is a new page load
}
Alternatively, if you are POSTing the data, you can check which HTTP method was used to call the form:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Form was posted
} else {
// $_SERVER['REQUEST_METHOD'] == 'GET'
}
The pattern I commonly use is:
$showForm = true;
if( is_form_postback() ) {
if( data_is_valid() ) {
redirect_to_thank_you_page();
} else {
show_validation_errors();
$showForm = false;
}
}
if($showForm) {
// Print the form, making sure to set the value of each input to the $_POSTed value when available.
}