Save PHP Form Input to Web Page - php

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

Related

ASK PHP : how to send form data to different .php file

I have a code like this:
<body>
<?php
// define variables and set to empty values
$namaErr = $nikErr = $shiftErr = "";
$nama = $nik = $shift = $keterangan = $tgl = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["nama"])) {
$namaErr = "<br><i>Nama tidak boleh kosong</i>";
} else {
$nama = test_input($_POST["nama"]);
// cek nama harus pake huruf tanpa simbol
if (!preg_match("/^[a-zA-Z ]*$/",$nama)) {
$namaErr = "<br><i>Nama harus diisi dengan Huruf dan tanpa karakter simbol</i>";
}
}
if (empty($_POST["nik"])) {
$nikErr = "<br><i>NIK tidak boleh kosong</i>";
} else {
$nik = test_input($_POST["nik"]);
// cek nik harus pake angka tanpa simbol
if (!preg_match("/^[0-9]*$/",$nik)) {
$nikErr = "<br><i>NIK harus diisi dengan Angka</i>";
}
}
if (empty($_POST["keterangan"])) {
$keterangan = "";
} else {
$keterangan = test_input($_POST["keterangan"]);
}
if (empty($_POST["shift"])) {
$shiftErr = "<i>Pilih salah satu Shift Kerja</i>";
} else {
$shift = test_input($_POST["shift"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div class="container">
<form name="fmk" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
</html>
I want to send the form data to Proses.php to show the form data, but when I change the section form action from <form name="fmk" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post"> to
<form name="fmk" action="<?php echo htmlspecialchars(proses.php);?>" method="post"> or
<form name="fmk" action="proses.php" method="post">, it succeeds in submitting the form data to Proses.php, but the PHP code inside Proses.php fails to check the form data for validation. My objective is when I click the Submit button, it will go to another page and show the result from form data with PHP syntax when the input field is not empty. If some input fields are empty, it will show the red sign and not go to the other page (still on the first page).
Please help me to solve this problem.
Sorry for my bad english, Love from Indonesia :)
If you want the form validation on the client side to happen as (show the red sign if empty) you must add the required attribute to your input fields.In this way you can successfully check your form inputs and in addition if you want to set the input pattern for your input you can also use pattern attribute in your inputs.Both of these will validate your form on the client side.
Hope this might help you.
how to send form data to different .php file
There are a couple of ways to do this depending on how you want to process the information. You can use the form to send over post by setting your action attribute to the desired page. Setting the method attribute to post allows the name of the input fields to be carried over to that page through the server. On the target page you check the $_POST globals to make certain they are set and if they are set, you can then define them or call on their global variables in your code.
The way I do this on my target page is to first check if the submit button is set in the global POST array. If I have a button that submits my form and that name is name="submit" the $_POST will store that as a value in the global array.
if(isset($_POST['submit'])){
//submit is set, I can now check for the other values in the global $_POST array
if (empty($_POST["nama"])) {
$namaErr = "<br><i>Nama tidak boleh kosong</i>";
} else {
$nama = test_input($_POST["nama"]);
// cek nama harus pake huruf tanpa simbol
if (!preg_match("/^[a-zA-Z ]*$/",$nama)) {
$namaErr = "<br><i>Nama harus diisi dengan Huruf dan tanpa karakter simbol</i>";
}
}
}
If I have an issue here. For example I am testing and I know the things are set in the form, I can var_dump($_POST) and make certain that $_POST values are set by looking at the results of my $_POST array and checking the key/value pairs.
The other way to direct a user once they submit a form is by having the form action set to self or leaving your action attribute out completely. You can check if the submit button is set and then parse through the global $_POST array within the if(isset($_POST['submit])){ //form has been submitted check inputs, run validations and set errors, etc, etc... } conditional. You can do all the work on the same page the form is on using this method and then once all has been successfully completed use a header redirect to send the user to the desired page you wish for them to visit with a success url post.
It would be something to the effect:
if(isset($_POST['submit'])){
if(isset($_POST['name'])){
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$msg = "Success, thank you for submitting";
// maybe check validation of inputs and run other inputs through sanitation etc...
// once you finish your checks if all is good set your url params
$host = $_SERVER['HTTP_HOST']; // sets your server name
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); // PHP_SELF
$root = 'proses.php';
$urp = '?success';// adds a url post to your url and this can be checked on the other page
header("Location: http://$host$uri/$root$urp");
exit;
}else{
// run error code here
$error = true;
$msg = "Error please try again";
}
}

PHP single page form validation form not validating

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!!!

PHP Form sends Email even if Email and Name are invalid

Hi everyone and thanks for your time!
Although it's the first time that I try PHP, I've been making a PHP Form and so far I've been able to make it validate the fields, and also that the form doesn't send anything if the fields are empty.
Now... The fields "Name" and "Email" have validation filters...
"Name" doesn't allow more than "letters and white spaces" and "Email" doesn't allow an "invalid Email format".
Example:
Name: Rob3rt... it has a number
Email: anything... isn't an Email address
Subject and Message have no validation filters...
The problem is, that if I fill up all fields, the form sends the Email, even if the information written on "Name" and "Email" doesn't agree with their validation filters...
Q: How can I hold the form from sending an Email, until all fields have the correct information inside?
Here's the code:
// This is the validation code //
<?php
// define variables and set to empty values
$nameErr = $emailErr = $commentErr = $subjectErr = "";
$name = $email = $comment = $subject = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "<h5>Name is required</h5>";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "<h5>Only letters and white space allowed</h5>";
}
}
if (empty($_POST["email"])) {
$emailErr = "<h5>Email is required</h5>";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "<h5>Invalid email format</h5>";
}
}
if (empty($_POST["comment"])) {
$commentErr = "<h5>Message is required</h5>";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["subject"])) {
$subjectErr = "<h5>Subject is required</h5>";
} else {
$subject = test_input($_POST["subject"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form>
Form comes here
</form>
// This is the sending code... I think the problem is here... //
<?php
if($_POST['name']!="" && $_POST['email']!="" && $_POST['comment']!="" && $_POST['subject']!="") {
$to = "myemail#whatever.com";
$email = "From: " . $email . "\r\n";
$subject = "" . $subject . "\r\n";
$comment = "" . $comment . "\r\n";
mail($to,$subject,$comment,$email);
echo "good";
}
else {
"bad";
}
?>
It is not working, because you never check if an error occurred, you are only checking if the fields are not empty before you send the mail.
The simplest way to fix it is replacing
if($_POST['name']!="" && $_POST['email']!="" && $_POST['comment']!="" && $_POST['subject']!="") {
with
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $nameErr === '' && $emailErr === '' && $commentErr === '' && $subjectErr === '') {
There is no no need to check for empty fields again, you have already done it before, so you just need to check if you are POSTing the form and if all errors are empty.
Some advice on how to generally improve your code:
1) Do not handle the HTTP POST in two positions (once above the form and once below). Merge it together in one PHP code block.
2) At least make sure that the user can't re-submit a successful form by reloading the site. After a successful submit, redirect the page. Something like this:
mail($to,$subject,$comment,$email);
header('Location:' . $_SERVER['REQUEST_URI'] . '?status=ok');
exit();
3) separate your HTML from your PHP or you will end up with a huge file which gets hard to maintain. Put your HTML form in a separate file and include it.
Although imho the nicest solution for a form is to sanitize in in JavaScript, submit it via AJAX (with angular, react, jQuery, whatever), handle it (and sanitize the data again) in PHP, send a 4xx HTTP header on error and return the error messages as a JSON object, which you then use in JavaScript.

Can not validate an HTML form with php & Apache2

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 3 fields validating correctly. The submissions post to a text file correctly. However

I have 3 fields validating correctly. The submissions post to a text file correctly. However, they post - - (as I have in the code to separate each section) even when the submit button is clicked without filling in the information. There should not be any empty information with just 2 - - printed to the text file without filling in the 3 fields first. How can I fix that? Sorry for the inconvenience, I answered my own question in another post and was able to fix the problem. Thank you for your time.
Here is my code
<?php
if(isset($_POST['name'], $_POST['email'], $_POST['website'])) {
if(empty($_POST['name'])) {
$errors[] = "Name is required";
} else{
$name = htmlentities($_POST['name']);
$name = test_input($_POST['name']);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$errors[] = "Only letters and white space allowed for the name";
}
}
if(empty($_POST['email'])) {
$errors[] = "Please provide your Email address.";
} else if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ===
false){
$errors[] = "Your Email is not valid.";
} else {
$email = htmlentities($email);
}
if(empty($_POST['website'])) {
$errors[] = "Please provide your company URL.";
} else{
$website = htmlentities($_POST['website']);
$website = test_input($_POST['website']);
if(!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website)) {
$errors[] = "Please provide a valid URL for your company.";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$name = $_POST['name'];
$email = $_POST['email'];
$website = $_POST['website'];
$data = $name . " - " . $email . " - " . $website;
$file = "textfile.txt";
if($_POST){
file_put_contents($file, $data . PHP_EOL, FILE_APPEND);
}
?>
In the html I have
<?php
if(empty($errors) === false){
?>
<ul>
<?php
foreach($errors as $error){
echo "<li>",$error,"</li>";
}
?>
</ul>
<?php
}else{
if(isset($name, $email, $website)){
echo "<b>Thank you for your submission.</b>";
}
}
?>
</div>
<div class="wrapper w3-round-xlarge">
<div class="formtitle w3-round-xlarge">Thank you for filling in all fields below
</div>
<div class="formwrapper w3-round-xlarge">
<form name="mobile" id="mobile" method="post" enctype="multipart/form-data" action="data.php"><br/>
etc. (the html document starts and ends correctly. Thank you for your help.
If all three inputs are required them, place required into the html input.
<Input name="email" required />
Do this for each input. This will not allow for the form to be processed until all fields are filed.
Sorry to inconvenience anyone for taking the time to read my post. I was able to fix the problem simply by removing the following from the php code above my html and changing the following
if($_POST){
file_put_contents($file, $data . PHP_EOL, FILE_APPEND);
}
to ...
<?php
}else{
if(isset($name, $email, $website)){
file_put_contents($file, $data . PHP_EOL, FILE_APPEND);
echo "<b>Your submission has been sent.</b>";
}
and adding it to the html div area

Categories