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
Related
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!!!
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 am making a user system on a website and I cannot get the form to post to the file.
Here is the form in the HTML file:
<form method="post" action="php/userlogin.php">
<p><input type="text" name="usernameL" value=""></p>
<p><input type="password" name="passwordL" value=""></p>
<p><input type="submit" name="submit" value="Login"></p>
</form>
And the userlogin.php in the php directory:
<?php
$username = $password = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = test_input($_POST["usernameL"]);
$password = test_input($_POST["passwordL"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
I'm new to forms and can't find an answer anywhere or even a question like this. How would I fix this?
You code is working fine.
The problem might be with the file structure. Please check that.
Ex: If your html file in the root folder of your project, Then the userlogin.php files should be there in project_root_folder/test/
So the file structure should be...
Root/
index.html
Test/
userlogin.php
Code is fine.
Just output the values of the variables.
echo $username.' '.$password;
You can see that the data is being posted.
Well your code seems to work perfectly fine, maybe the problem is with your testing enviroment, you need solution like XAMPP https://www.apachefriends.org/ to run php scripts on your computer. Other way is to run scripts remotely on some free webhosting that supports php.
If this is not the case then to check if actually data was sent, modify your code this way:
...
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = test_input($_POST["usernameL"]);
$password = test_input($_POST["passwordL"]);
echo $username."<br/>";
echo $password."<br/>";
}
...
I have the following PHP code:
<?php
//Connection to PDO Database
?>
<form method="post" action="">
<p>Busisness telephone 1</p><input id="business_telephone_01" name="business_telephone_01" tabindex="auto" value="<?php echo $result['business_telephone_01']; ?>" type="text" />
<input name="submit" type="submit" value="Save Changes"></form>
<?php
//Get from Form
if((empty($_POST['submit']) === false)){
$business_telephone_01 = $_POST['business_telephone_01'];
//Formating of telephone numbers
$message = 'This message I want to display';
echo 'This is another message';
}
echo $message;
//Code to update table through PDO
?>
Regardless of where I do the echo whether it is echo 'This is another message'; within the conditional brackets or _ echo $message;_ outside the brackets nothing is being echoed and no error is being displayed.
The html form and the PDO are working correctly and are being updated but nothing is being echoed. No error is being shown in the error log.
UPDATE:
If I use if((empty($_POST['submit']) === false)){ I get PHP
Notice: Undefined variable: hello
If I use if (isset($_POST['submit'])) { I get PHP Notice:
Undefined variable: hello
If I use if (!isset($_POST['submit']))
{ it gives me a list of undefined variables that I use e.g. from
my code above business_telephone_01
My full code
if((empty($_POST['submit']) === false)){
//Get from Form
$address_building_name = $_POST['address_building_name'];
$address_building_number = $_POST['address_building_number'];
$address_street = $_POST['address_street'];
$address_locality = $_POST['address_locality'];
$address_postcode = $_POST['address_postcode'];
$address_country = $_POST['address_country'];
//Formating of address
$address_building_number = strtoupper($address_building_number);
$address_building_number = str_replace(' ','',$address_building_number);
$address_building_name = ucwords($address_building_name);
$address_street = ucwords($address_street);
$address_locality = ucwords($address_locality);
$address_postcode = strtoupper($address_postcode);
$address_country = ucwords($address_country);
echo 'Hello';
$good = 'Good bye';
}
echo $good;
I'd be willing to bet $message isn't being echo'd because it's never initialized. (The if block, where it is supposed to be initialized, is not being executed because the conditional is failing.)
First off, you should use isset to determine if a POST variable has been submitted:
if (isset($_POST['submit'])) {
Or, to see if it has not been submitted:
if (!isset($_POST['submit'])) {
Secondly, you should enable error reporting on your program and let us know what errors (if any) you are getting:
error_reporting(E_ALL);
ini_set("display_errors", 1);
You can add these two lines to the very top of your script, right after the opening <?php line, which should help shed some light on the situation.
The problem could be that the $message variable is never set within your if statement.
If the 'if' condition is not matched, then $message is never set and you will not be able to echo the value.
To test, you could set the $message variable to some value before you start your if statement.
$message = 'condition failed';
if(isset($_POST['submit'])){
....
$message = 'This message I want to display';
}
echo $message;
If the condition is met, it will echo "This message I want to display".
If the condition fails, it will echo 'condition failed';
A quick dirty test, but it will tell you if the $message variable will be initialized inside your 'if' statement.
ok so im here trying to practice some php (im a super beginner) and so long story short,
i put form elements in one page, passed it to the process php.
Im just messing aound trying to see what ive learned so far. i dont get any errors, just dont understand why it doesnt work.
<?php
$yourname = htmlspecialchars($_POST['name']);
$compname = htmlspecialchars($_POST['compName']);
$response = array("please enter correct information","hmm" . "$yourname");
function nametest() {
if (!isset($yourname)){
$yourname = $response[0];}
else {
$yourname = $response[1];;
}
}
?>
<?php nametest(); ?>
what im trying to do is, that if the name isnt set, to make a variable equal to a value inside response.
Try
function nametest() {
if (!isset($yourname)){
$yourname = $response[0];
} else {
$yourname = $response[1];
}
return $yourname;
}
print nametest();
The function needs to return a value to be printed. I also noticed you have two ;; behind line 5.
Because you are assigning $yourname and $compname in the first two lines:
$yourname = htmlspecialchars($_POST['name']);
$compname = htmlspecialchars($_POST['compName']);
UPDATE You can check if these are set in POST, and therefore not need to check them later:
$yourname = isset($_POST['name']) ? htmlspecialchars($_POST['name']) : "oops, no value";
$compname = isset($_POST['compName']) ? htmlspecialchars($_POST['compName']) : "oops, no value";
They will always be set, even if NULL or empty. So, your later calls to isset() will always be true.
Instead, you may check if they are empty with the empty() function:
UPDATE Not necessary according to corrections in comments. Your isset() should work.
// Check with empty()
// but still won't work properly. keep reading below...
function nametest() {
if (!empty($yourname)){
$yourname = $response[0];}
else {
$yourname = $response[1];;
}
}
However, there is another problem here of variable scope. The variables are not available inside the function unless you either pass them in as parameters or use the global keyword:
// $yourname is passed as a function argument.
function nametest($yourname, $response) {
if (!empty($yourname)){
$yourname = $response[0];}
else {
$yourname = $response[1];;
}
}
Getting there... Now your function assigns $yourname, but it doesn't return or print any value. Add a return statement, and then you can echo out the result:
function nametest($yourname, $response) {
if (!empty($yourname)){
$yourname = $response[0];}
else {
$yourname = $response[1];;
}
// Add a return statement
return $yourname;
}
// Now call the function, echo'ing its return value
echo nametest($yourname, $response);
Variable Scope is the biggest mistake here, your function can not 'see' the variables that you created outside of it, do this:
<?php
.
.
.
function nametest($yourname, $response) { // This creates two new variables that
// are visible only by this function
if (!isset($yourname)){
$yourname = $response[0];
} else {
$yourname = $response[1]; // Get rid of the extra semicolon
}
return $yourname; // This $yourname is only visible by this function so you
// need to send it's value back to the calling code
}
?>
<?php nametest($yourname, $response); ?> // This sends the values of the
// variables that you created at the
// top of this script