PHP and form handling - php

I have been working with PHP and MySQL for about two months and I recently began using forms. I have a main form-processing file:
if($_POST['checkforpothole'] == "yes"){
echo "thank you for your help"."<br/>";
echo "please enter in a latitude and longitude"."<br/>";
include 'FormForGettingLatAndLong.php';
$Lat = $_POST['latitude'];
$Long = $_POST['longitude'];
include 'MySQLSample.php';
echo addCoord($Lat, $Long);
include 'MySQLSample.php';
die();
}
if($_POST["checkforpothole"] == "no"){
echo "here is the table"."<br/>";
include 'MySQLSample.php';
die();
}
?>
The form I am attempting to access is as follows:
<?php
?>
<!DOCTYPE HTML>
<html>
<body>
<form action="FormProcessing.php" method="post">
Latitude: <input type="text" name="latitude"><br>
Longitude: <input type = "text" name = "longitude"><br>
<input type="submit">
</form>
</body>
</html>
Here is the checkforpothole form:
<?php
?>
<!DOCTYPE HTML>
<html>
<body>
<form action="FormProcessing.php" method="post">
Add a new pothole? (yes or no): <input type="text" name="checkforpothole"><br>
<input type="submit">
</form>
</body>
</html>
I am having trouble accessing latitude and longitude in this form, which is in a separate file. Is there a way to access an index from a second form after accessing from another form initially. Please let me know if there is a problem in the first program, specifically with the first if statement.

First of all, I think the logic of your code needs a bit of revision.
if($_POST['checkforpothole'] == "yes"){
echo "thank you for your help"."<br/>";
echo "please enter in a latitude and longitude"."<br/>";
include 'FormForGettingLatAndLong.php';
$Lat = $_POST['latitude'];
$Long = $_POST['longitude'];
include 'MySQLSample.php';
echo addCoord($Lat, $Long);
include 'MySQLSample.php';
die();
}
if($_POST["checkforpothole"] == "no"){
echo "here is the table"."<br/>";
include 'MySQLSample.php';
die();
}
?>
As i concluded from your code it appears that you want to get additional information using a second form when user submitted the first form. and you're trying to do so by including the second form when you are processing the first form and then immediately reading the values of second form:
include 'FormForGettingLatAndLong.php';
$Lat = $_POST['latitude'];
$Long = $_POST['longitude'];
but this way, you won't have the Longitude and Latitude! because you just posted the second form to user to get that data! and when she posts back the second form, execution of your code will start from beginning (in a separate process). working with forms is not like conventional input procedures (like old "cin<<" , "fscanf()" or "System.console().readLine()"). instead you should print the second form and wait for user to submit that.
so you can do what you want using these three files:
index.html:
<!DOCTYPE HTML>
<html>
<body>
<form action="firstFormProcessing.php" method="post">
Add a new pothole? (yes or no): <input type="text" name="checkforpothole"><br>
<input type="submit">
</form>
</body>
</html>
firstFormProcessing.php:
<?php
if($_POST['checkforpothole'] == "yes"){
echo "thank you for your help"."<br/>";
echo "please enter in a latitude and longitude"."<br/>";
echo <<<END
<!DOCTYPE HTML>
<html>
<body>
<form action="secondFormProcessing.php" method="post">
Latitude: <input type="text" name="latitude"><br>
Longitude: <input type = "text" name = "longitude"><br>
<input type="submit">
</form>
</body>
</html>
END;
die();
}
if($_POST["checkforpothole"] == "no"){
echo "here is the table"."<br/>";
include 'MySQLSample.php';
die();
}
?>
secondFormProcessing.php:
<?php
echo "now i have Latitude=$_POST[latitude] and Longitude=$_POST[longitude]";
?>
P.S. it's my first Answer on stackoverflow. i hope this will help you and by the way sorry for my bad English.

I would take 2 files instead of messing on one page, this is how I would do it.
If this helps you then don't forget to mark the question as answered.
index.php
<?php
if($_SERVER['REQUEST_METHOD'] === "POST") {
if(isset($_POST['checkForPothole'])) {
if($_POST['checkForPothole'] == true) {
header("Location: addPole.php");
}
}
}
?>
<!DOCTYPE HTML>
<html>
<body>
<form action="index.php" method="post">
Add a new pothole? (yes or no): <input type="text" name="checkForPothole"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
addPole.php
<?php
if($_SERVER['REQUEST_METHOD'] === "POST") {
if(isset($_POST['latitude']) && isset($_POST['longitude'])) {
if(!empty($_POST['latitude']) && !empty($_POST['longitude']) {
require_once("MySQLSample.php");
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
addCoord($latitude, $longitude); //guessing that this is a function in the mysqlsample file
}
}
}
?>
<!DOCTYPE HTML>
<html>
<body>
<form action="FormProcessing.php" method="post">
Latitude: <input type="text" name="latitude"><br>
Longitude: <input type="text" name="longitude"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Related

Values input in html form not taken by php

I tried to execute the following html code:
<html>
<head>
<title>Listing 9.1 A simple HTML form</title>
</head>
<body>
<form action="listing.php" method="POST">
<p><strong>Name:</strong><br>
<input type="text" name="user"></p>
<p><strong>Address:</strong><br>
<textarea name="address" rows="5" cols="40"></textarea></p>
<p><input type="submit" value="send"></p>
</form>
</body>
</html>
And this is the code of the associated php file (listing.php):
<html>
<head>
<title>Listing Reading input from a form </title>
</head>
<body>
Welcome <?php echo $_POST["user"]; ?><br>
Your email address is: <?php echo $_POST["address"]; ?>
</body>
</html>
I was able to get the form and enter values as shown below:
Form Input
But, when I clicked 'Send Message', it displays only:
Welcome
Your email address is:
Without the values that I entered through the form.
When I tried to run the php file directly from the local host (http://localhost/listing.php), I received these error messages:
Welcome
Notice: Undefined index: user in C:\xampp\htdocs\listing.php on line 7
Your email address is:
Notice: Undefined index: address in C:\xampp\htdocs\listing.php on line 8
I even modified the php code as follows, but still got the same output:
<html>
<head>
<title>Listing Reading input from a form </title>
</head>
<body>
Welcome <?php
if(isset($_POST['submit'];)) {
session_start();
$user = $_POST['user'];
echo "$text";}else {echo 'Could not load text!';}?><br>
Your email address is: <?php echo $_POST["address"]; ?>
</body>
</html>
I would really appreciate it if you could give some advice to make it work.
Thanks
if(isset($_POST['submit'];)) should be changed,so you check if address and user is isset. Furthermore you normally don't want ; in your if statements.
Here i have a optimized version for you. the !empty is added so we also check if the inputs are not empty.
if (isset($_POST["name"] && isset($_POST["address"])) {
if (!empty($_POST["name"] && !empty($_POST["address"]) {
// execute code as u would
}
}
Notice: Undefined index: address in C:\xampp\htdocs\listing.php on line 8
This is caused by the use of the ';' in the if condition.
Remove that and you should be good. for now.
Try this code:
<html>
<head>
<title>Listing Reading input from a form </title>
</head>
<body>
Welcome <?php
if(isset($_POST['submit']))
{
session_start();
$user = $_POST['user'];
echo $user;
echo "<br><br>Your Email Address is: ".$_POST['address'];
}
else
{
echo 'Could not load text!';
}
?>
<br>
<form action="" method="POST">
<p><strong>Name:</strong><br>
<input type="text" name="user"></p>
<p><strong>Address:</strong><br>
<textarea name="address" rows="5" cols="40"></textarea></p>
<p><input type="submit" value="send" name="submit"></p>
</form>
</body>
</html>
In your second code block $text isn't defined anywhere. Do you mean to have $user?
<html>
<head>
<title>Listing Reading input from a form</title>
</head>
<body>
Welcome
<?php
if(isset($_POST['submit'])) {
session_start();
echo isset($_POST['user']) ? $_POST['user'] : "User";
} else {
echo "User";
}
?>
<br>
Your email address is:
<?php
echo isset($_POST["address"]) ? $_POST["address"] : "Address"
?>
</body>
</html>
Try this and let me know:
<?php
session_start();
if(isset($_POST['submit'])) {
$user = $_POST['user'];
echo "Welcome ".$user;
echo "<br>";
echo "Your email address is: ".$_POST["address"];
}else {
// you may get rid of this block if you like
echo 'Could not load text!';
}
?>
<html>
<head>
<title>Listing 9.1 A simple HTML form</title>
</head>
<body>
<form action="" method="POST">
<p><strong>Name:</strong><br>
<input type="text" name="user"></p>
<p><strong>Address:</strong><br>
<textarea name="address" rows="5" cols="40"></textarea></p>
<p><input type="submit" name='submit' value="send"></p>
</form>
</body>
</html>

HTML Form (with PHP) requires I press submit button twice before it takes me to the action form

I'm new to PHP so please bear with me.
I'm trying to decide the action based on the given input.
Given below is the code I've written for this simple task
<html>
<head>
<meta charset="UTF-8">
<title>SAMPLE</title>
</head>
<body>
<form method="POST" action="<?php
if(isset($_POST['submit_button']))
{
if($_POST['name_field'] === "USERA")
{
echo "output.php";
}
else
{
echo "wronguser.php";
}
}
?>">
Username : <input type="text" name="name_field" value="<?php
if(!isset($_POST['name_field']) || $_POST['name_field']=== "")
{
echo "Enter Something" ;
}
?>">
<input type="submit" name="submit_button" value="SUBMIT BUTTON !">
</form>
</body>
</html>
Here I want the form to redirect to "output.php" if the user is "USERA" or "wrongouput.php" for any other user name entered. Although it works as expected, I'm redirected to the right page only when I press the submit button the 2nd time.
Why is this ?
Also, reloading the page doesn't seem to bring back the original page with the text field containing the default "Enter Something" text. I have to run it all over again from the IDE.
Why is this ?
You can try a different approach
<?php
if(isset($_POST['submit_button']))
{
if($_POST['name_field'] === "USERA")
{
require_once("output.php");
}
else
{
require_once("wronguser.php");
}
}
else
{
?>
<html>
<head>
<meta charset="UTF-8">
<title>SAMPLE</title>
</head>
<body>
<form method="POST" action="">
Username : <input type="text" name="name_field" value="<?php
if(!isset($_POST['name_field']) || $_POST['name_field']=== "")
{
echo "Enter Something" ;
}
?>">
<input type="submit" name="submit_button" value="SUBMIT BUTTON !">
</form>
</body>
</html>
<?php
}
?>
Take your code out of the action, make the action for the form self so it fires on itself, then put your PHP above all the HTML at the top of the file. That'll stop the double click issue.
<?php
if(isset($_POST['submit_button']))
{
if($_POST['name_field'] === "USERA")
{
echo "output.php";
}
else
{
echo "wronguser.php";
}
}
?>">
Username : <input type="text" name="name_field" value="<?php
if(!isset($_POST['name_field']) || $_POST['name_field']=== "")
{
echo "Enter Something" ;
}
?>
<html>
<head>
<meta charset="UTF-8">
<title>SAMPLE</title>
</head>
<body>
<form method='post' action="<?php $SERVER['PHPSELF']; ?>">
<input type="submit" name="submit_button" value="SUBMIT BUTTON !">
</form>
</body>
</html>

PHP Keep the variable scope even after the page reload

The website generates the random number from 1 to 100 when accessing the first page(page1.php). And the user will guess the number.
The first page contains
- a text box for accepting a
number from the user, and a submit button.
The second page(page2.php) will be returned to the user if the guess number is too high or too low. And the page shows a message telling the user "Too High" or "Too Low". The page also contains
a button(retry button) that allows the user to go back to the first page(page1.php) to re-enter a new number
a button that allows the user to quit the game.
The third page(page3.php) is returned to the user if the guess is correct. The page displays "Correct", the random number, and the count of tries.
And I have this index.php which is heart for all the pages. And here is the code.
index.php
<?php
$name = '';
$inputnumber = '';
$random = 33; //this is just an assumption to keep it simple
$message = '';
$guesscount = '';
if (isset($_POST['action'])) {
$action = $_POST['action'];
}
if ($action === 'guess') {
$guesscount = $_POST['$guesscount'];
$inputnumber = $_POST['$inputnumber'];
if ($inputnumber == $random) {
$message = "Correct!";
include 'page3.php';
}
if ($inputnumber > $random) {
$message = "Too High";
include 'page2.php';
}
if ($inputnumber < $random) {
$message = "Too Low";
include 'page2.php';
}
}
if ($action === 'retry') {
include 'page1.php';
}
page1.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Number Guess</title>
</head>
<body>
<h1>Number Guess</h1>
<form name="myForm" action="index.php" method="post" >
Number Guess: <input type="text" name="$inputnumber" value="<?php if(isset($inputnumber)==1){
echo $inputnumber;}else echo ""; ?>" /><br>
<input type="submit" name="action" value="guess" />
<hr>
Guess Count: <?php echo $guesscount; ?>
</form>
</body>
</html>
page2.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Number Guess</title>
</head>
<body>
<h1>Number Guess</h1>
<form name="myForm" action="index.php" method="post" >
Message: <?php echo $message; ?>
<input type="hidden" name="$guesscount" value="<?php echo $guesscount;?>"/><br>
<input type="submit" name="action" value="retry" />
<hr>
Guess Count: <?php echo $guesscount;?>
</form>
</body>
</html>
page3.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Number Guess</title>
</head>
<body>
<h1>Number Guess</h1>
<form name="myForm" action="index.php" method="post" >
Message: <?php echo $message; ?>
Number of Tries: <?php echo $guesscount; ?>
<input type="submit" name="action" value="ok" />
</form>
</body>
</html>
page1.php is the page to load first.
Challenge I have faced is, I couldn't keep the $guesscount stable always. It keeps resetting on me. I have tried session but couldn't resolve it.Please help resolving it.
Thanks in advance.
I don't know why but my gut feeling tells me that the reason why the session is not working for you on other pages is because you do not initiate it ??
So what you have to do is:
index.php
<?php
session_start();
$_SESSION['myVariable'] = 'myVariable';
?>
page1.php
<?php
session_start();
$mySessionVar = $_SESSION['myVariable'];
var_dump($mySessionVar); // <- this should print myVariable
?>
You may get an error saying that $_SESSION is null or not set and to prevent that you can just enclose $_SESSION inside and isset method
if(isset($_SESSION['myVariable']) && $_SESSION['myVariable'] != null) {
$mySessionVar = $_SESSION['myVariable'[;
}

Display PHP POST results after a form submit, then reload same blank form when page "Refresh" clicked

After over 6 hours of searching here and other forums/blogs, still found no operational method to do this, all on same page; so I remain confident this has not been asked in exact same way: Enter some data to a form, submit, show results... then if user clicks "Refresh", show the original blank form and not show a browser message about "You are resending data, etc. etc." Here is the base code, it functions as expected, just desire to have starting blank form show after clicking browser "Refresh". I have attempted both PRG and Sessions methods without success.
<!DOCTYPE html >
<head>
<title>Refresher test</title>
</head>
<body>
<br/><br/><h2>What Me Refresh</h2>
<?php
//If form not submitted, display form.
if (!isset($_POST['submit'])||(($_POST['text']) == "")){
?>
<p><h3>Enter text in the box then select "Go":</h3></p>
<form method="post" action="RfrshTst.php" >
<textarea rows="5" cols="50" name="text" >
</textarea>
<input type="submit" name="submit" value="Go" />
</form>
<?php
//If form submitted, process input.
} else {
//Retrieve show string from form submission.
$txt = $_POST['text'];
echo "The text you entered was : $txt";
} ?>
</body>
</html>
This solution uses the session.
First stores in the session the post field if it exists and then redirects to the same page.
If it finds the field in the session, it gets it and remove it from session and show it on the page.
<?php
$txt = "";
session_start();
if (isset($_POST['submit']) && (($_POST['text']) != "")) {
$_SESSION['text'] = $_POST['text'];
header("Location: ". $_SERVER['REQUEST_URI']);
exit;
} else {
if(isset($_SESSION['text'])) {
//Retrieve show string from form submission.
$txt = $_SESSION['text'];
unset($_SESSION['text']);
}
}
?>
<!DOCTYPE html >
<head>
<title>Refresher test</title>
</head>
<body>
<br/><br/><h2>What Me Refresh</h2>
<?php
if($txt != "") {
echo "The text you entered was : $txt";
} else {
?>
<p><h3>Enter text in the box then select "Go":</h3></p>
<form method="post">
<textarea rows="5" cols="50" name="text" >
</textarea>
<input type="submit" name="submit" value="Go" />
</form>
<?php } ?>
</body>
</html>
Try this code. You need to use JS to refresh without POSTing again.
<!DOCTYPE html >
<head>
<title>Refresher test</title>
</head>
<body>
<br/><br/><h2>What Me Refresh</h2>
<?php
//If form not submitted, display form.
if (!isset($_POST['submit'])||(($_POST['text']) == "")){
?>
<p><h3>Enter text in the box then select "Go":</h3></p>
<form method="post" action="RfrshTst.php" >
<textarea rows="5" cols="50" name="text" >
</textarea>
<input type="submit" name="submit" value="Go" />
</form>
<?php
//If form submitted, process input.
} else {
//Retrieve show string from form submission.
$txt = $_POST['text'];
echo "The text you entered was : $txt";
?>
<button onclick="location = location.href">Refresh</button>
<?php
} ?>
</body>
</html>
even Wiki has an article for you. I wonder how couldn't you find it?
you can do it with php:
<?php
// handle $_POST here
header('Location:yourscript.php');
die();
?>
JS:
window.location = window.location.href;
or Post/Redirect/Get which is the best I think
You can't just delete the $_POST data from the server. The browser alerts it because it is stored by the browser. If it resubmits the data then it will send it back to the server and repopulate $_POST
You can achieve this by setting a cookie / session variable, which tells you the form was already processed.
<?php session_start(); ?>
<!DOCTYPE html >
<head>
<title>Refresher test</title>
</head>
<body>
<br/><br/><h2>What Me Refresh</h2>
<?php
//If form not submitted, display form.
if (isset($_POST['submit']) && !isset($_SESSION['user'])){
//Retrieve show string from form submission.
$txt = $_POST['text'];
echo "The text you entered was : $txt";
$_SESSION['user'] = true;
//If form submitted, process input.
} else {
?>
<p><h3>Enter text in the box then select "Go":</h3></p>
<form method="post" action="" >
<textarea rows="5" cols="50" name="text" >
</textarea>
<input type="submit" name="submit" value="Go" />
</form>
<?php
} ?>
</body>
</html>
Dont forget to empty the action as you have mentioned in question(bold) All on same page
<form method="post" action="RfrshTst.php" >
^--Here^

PHP form not processing in process.php

I'm having difficulty figuring out why my PHP form is processing on process.php but not returning to the form page with the appropriate $messages. Am I missing a line of code? I wrote this all up myself and it's the first time.
Here is my html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test Contact Form - jQuery</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
<h3>Contact Us</h3>
<?php echo $contact_message; ?>
<form id="myForm" method="post" action="process.php">
<input name="name" type="text" value="<?php echo $_POST[name]; ?>" placeholder="Name" required/>
<br>
<input name="email" type="email" value="<?php echo $_POST[email]; ?>" placeholder="you#yourmail.com" required/>
<br>
<textarea name="message" class="message" placeholder="We can answer your questions." required>
<?php echo $_POST[message]; ?>
</textarea>
<br>
<button type="submit" name="submit" class="btn send">
<img src="img/send.png">
</button>
<br>
<?php echo $contact_success_message; ?>
</form>
<!--close contact form-->
</body>
</html>
And here is my process.php
<?php
//checks for valid email
function is_valid_email($email) {
$result = true;
$pattern = '/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\#([a-z0-9])(([a-z0-9-])*([a-z0-9]))+(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i';
if(!preg_match($pattern, $email)) {
$result = false;
}
return $result;
}
//when send is pressed, validate fields
if(isset($_POST['submit'])) {
$valid = true;
$contact_message = '';
if ( $_POST['name'] == "" ) {
$contact_message .= "You forgot to tell us your name. ";
$valid = false;
}
if ( !is_valid_email($_POST['email']) ) {
$contact_message .= "A valid email is required, don't worry we don't share it with anyone. ";
$valid = false;
}
if ( $_POST['message'] == "" ) {
$contact_message .= "What did you want to ask us? ";
$valid = false;
}
//if everything checks out, send the message!
if ( $valid == true ) {
$safe_email = str_replace("\r\n","",$_POST[email]);
$mail = "From: $_POST[name]\n";
$mail .= "Email: $_POST[email]\n";
$mail .= "$_POST[message]\n";
mail('ME#MYEMAIL.COM','New Contact from RN+',$mail,"From: $safe_email\r\n");
$contact_success_message = 'Brilliant I say! We will be in contact with you shortly.';
//clear form when submission is successful
unset($_POST);
}
}
?>
I could have sworn that I've used this before but this time it's not returning to the contact page.
It looks like you meant to use the code like this:
form.php
<?php include 'process.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test Contact Form - jQuery</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
<h3>Contact Us</h3>
<?php echo $contact_message; ?>
<form id="myForm" method="post" action="process.php">
<input name="name" type="text" value="<?php echo $_POST[name]; ?>" placeholder="Name" required/><br>
<input name="email" type="email" value="<?php echo $_POST[email]; ?>" placeholder="you#yourmail.com" required/><br>
<textarea name="message" class="message" placeholder="We can answer your questions." required><?php echo $_POST[message]; ?></textarea><br>
<button type="submit" name="submit" class="btn send"><img src="img/se
__
formnd.png"></button><br>
<?php echo $contact_success_message; ?>
</form><!--close contact form-->
</body>
</html>
The form processor will set the appropriate variables you are outputting in your HTML code. Since process.php checks if the method is POST, you don't have to do that in the form page.
If you want process.php to redirect back to your form, you need to add a PHP header code like: header('Location: http://www.example.com/form.php');
If you want to carry through any data back to the original page, include it in the URL as a GET variable: header('Location: http://www.example.com/form.php?message='.$messagetext); You can then retrieve this on your form page through use of GET: echo $contact_success_message = $_GET['message'];
Do not forget to exit(); or die(); after your redirect!
If you don't have any reason for excluding a single PHP page, you could merge the two (form and process) into one php page.
<?php
//checks for valid email function
...
if(isset($_POST['submit'])) {
...
}
?>
...your HTML goes here...
This will display just the form if no data has been submitted, and if the form has been submitted will "reload" the page, perform the action, and display the appropriate message. Change the form action to action="" so the file will post to itself.
I would recommend using jQuery validation. It is easier and will help with any issues you might have in returning the message.
http://docs.jquery.com/Plugins/Validation
Something like this...
$("#myForm").validate({
rules: {
name: { required: true; }
},
messages: {
name: "You forgot to tell us your name.",
}
});
You can do this for email fields and for your whole form. You can find plenty of examples online.
Just include your other fields. If you do it this way the validation is client side and the form will process and then you forward to a thank you for contacting us page.

Categories