How to use php in html form? - php

This is a simple Captcha form which is working well and prints the requested result after I press ‘submit’.
<?php
session_start();
$msgCaptcha = "";
?>
<?php
if (isset($_POST['submit'])){
$secCode = isset($_POST['secCode']) ? strtolower($_POST['secCode']) : "";
if ($secCode == $_SESSION['securityCode']) {
$msgCaptcha = "valid code";
$result = true;
}
else {
$msgCaptcha = "wrong security code";
$result = false;
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
name:<input name="myname" type="text"><br />
Security code: <input class="text" name="secCode" type="text">
<img src="securityCode.php" /><br />
<?php echo $msgCaptcha ?>
<input name="submit" type="submit" value="submit">
</form>
. i.e.
If my input is the same as like in the picture the printing is “valid security code”
and if the input is not the same, the printing is “wrong security code”.
When I change in the form the code to action="mailer.php" this file is opened but ignore of any input in the Captcha validation.
I need mailer.php to be open after Captcha validation.
I have tried onsubmit and some other options, but none of them works as a solution for the above.
Any help would be greatly appreciated.

You could try to include mailer.php after the $msgCaptcha = "valid code"; line.
Any code inside mailer.php would be executed in that block of code, and any $_POST variables required by mailer.php would be available.
The bottom line is, when you call mailer.php, you must have captcha validation in front of that file, otherwise any bot/spammer can bypass your captcha protection just by submitting the form directly to mailer.php
Keep in mind, bots generally ignore javascript, so the validation has to be done server side.
You may want to set a variable prior to including mailer.php that it will check so even if someone did try to directly submit to mailer.php, it won't process the form unless the file was included.
If this doesn't help, post the code for mailer.php so we know what the contents of that file are.

Use header()
if ($secCode == $_SESSION['securityCode']) {
$msgCaptcha = "valid code";
header("Location: http://www.website.com/ ... /mailer.php");
}

Related

PHP Errors aren't showing

I have a simple HTML script:
<form action="" method="post">
<input type="text" name="amount">
<?php echo $amountError; ?>
<input type="submit">
</form>
And I display errors using this:
<?
$amount = $_POST['amount'];
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (empty($_POST['amount'])) {
$amountError = 'Empty amount';
} else {
header("Location: apmoketi.php");
}
?>
In the apmoketi.php file there is only one line
echo $amount = $_POST['amount'];
However, when I'm trying to display data in the apmoketi.php page, I don't get the value of the $amount variable using action="", but using action="apmoketi.php" I can get it but my PHP code doesn't checking for any errors, why?
A call to header("Location: apmoketi.php"); makes the browser follow the specified URL as another, completely separate request. This new request doesn't have access to the POST data of the previous one.
Your options:
use include so apmoketi.php has access to the variables of the current script
use sessions to preserve data between requests
use a query parameter to carry the value over:
header('Location: apmoketi.php?amount=' . urlencode($amount));
When you redirect to header("Location: apmoketi.php");, the variables are no longer in $_POST[] so you need to set a session variable before you redirect:
$_SESSION['amount'] = $amount;
the way i do it is i have a folder called action with subfiles in there lets say the file called file2 in this file all the php action happens.
and in the root of my folder i have another file called file1 and in here theres the html and now how i would do it is
<form action="action/file2.php" method="post">
<input type="text" name="amount">
<?php echo $amountError; ?>
<input type="submit">
</form>

PHP: Refresh page on invalid form submit

How can I refresh a page with a form on submission pending the outcome of the submitted data and display a result.
e.g I have a page with a form:
<form action="" method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
The engine that handles the form is external, but required in the page:
require_once 'form_engine.php';
form_engine.php checks the input,
$success = "true";
$errorMessage = " ";
$name = $_POST['name'];
if ( $name == '') {
$errorMessage = 'Please enter your name';
$success = false;
}
else (if $success = true) {
// do something with the data
}
The form page contains the result:
<form action="" method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
<p><?php echo $errorMessage; ?></p>
Will the error message get displayed after the form is submitted incorrectly? Or do I have to use a session to store it?
You need something like this:
if (!isset($_POST['name']))
instead of
if ( $name == 'name')
UPDATE
Try this, it should give you the idea:
<?php
$errorMessage = false;
if (isset($_POST['submit'])) {
if (!isset($_POST['name']) || $_POST['name']=='') {
$errorMessage = 'Please enter your name';
}
else {
// do something with the data
echo "Success!!";
}
}
?>
<form method="post">
<input type="name" value="" name="name" placeholder="Your Name" />
<input type="submit" name="submit" />
</form>
<p><?php if ($errorMessage) echo $errorMessage; ?></p>
Note: leaving out the action attribute will just submit the form to the current page
Note 2: The PHP here could very well be stored in another page. Using require() is the same as putting the code directly into the page.
You can use redirect on php side:
header('Location: www.mysite.com/index.php');
You seem to be a little confused in terms of the exact process that occurs in terms of rendering a page, as do some of those commenting. You do not need to use sessions to solve this problem. There is no need to store anything server-side between page requests because the user's browser with retain everything that you need, at least for this situation. My guess is the others took you mentioning an "external engine" and thought that the form would be submitting away to a different site/page.
form loops
Below is a diagram showing a typical form request loop:
You do not have to do this, as coding is as much about personal preference to anything else, but typically people will design their form to submit back to the same URI that generated it — as you seem to be doing in your example, by leaving the action attribute blank. By doing this, as long as you embed everything you wish to pass back to the server side within the form — each time the user submits — that information will be resent and be available in PHP.
Obviously you need to be wary of what information might constitute as sensitive, as this data should only ever be written into markup if your requests are protected by HTTPS/SSL. You should also filter/escape any user input to prevent markup injection into your site. You can prevent many problems by using htmlentities, however this can cause issues depending on the values you are trying to capture from the user. Because you are using double quoted HTML attributes (the right way to do them ;) I have not set the ENT_QUOTES option.
back to the point
So in the above loop the user will be shown the form for the first time, and after any subsequent submit, which means that each time your PHP notices that there is an error you can just add your message into the page flow. The trick with this kind of system is what exactly do you do once the form is fully complete. To get out of the loop most people will use a header location call:
<?php
require_once 'form_engine.php';
$name = !empty($_POST['name']) ? trim($_POST['name']) : '';
$name = htmlentities($name);
if ( $success ) {
header('location: next-step.php');
exit;
}
?>
<form action="" method="post">
<input type="name" value="<?php echo $name; ?>" name="name" placeholder="Your Name" />
<input type="button" name="submit" value="submit form "/>
</form>
<?php
if ( $errorMessage ) {
echo "<p>$errorMessage</p>";
}
?>
form engine repairs
You should also rectify your form_engine.php as per my comments above and Shekhar Joshi's answer, although I would keep the header code outside of your engine logic, and leave that decision to the code that requires in the engine — as the above does.
may be, you are looking for this! the header() method.
$success = true;
$errorMessage = " ";
$name = $_POST['name'];
if(isset($_POST['name'])) {
if ( $_POST['name'] == '') {
$errorMessage = 'Please enter your name';
$success = false;
header('Location: www.something.com/some.php');
}
else if ($success == true) {
// do something with the data
}
}

Why am I getting this PHP error?

So here's my full code
<!DOCTYPE html>
<html>
<body>
<h1>Encrypt</h1>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Enter word to encrypt<input type="text" name="in">
<input type="submit">
<hr>
</form>
<h1>Decrypt</h1>
<form>
Enter word to decrypt<input type="text" name="out">
<input type="submit">
<hr>
</form>
</body>
</html>
<?php
$encrypt = $_POST['in'];
?>
And here's the error I get
Notice: Undefined index: in in /Users/idrisk/Colourity/si/index.php on line 20
Line 20 is $encrypt = $_POST['in']; and I don't see what I'm doing wrong with it. Any ideas?
As a general practice for forms in php, always check if the submit button has been clicked.
First name your submit button:
<input type="submit" name="submit">
then further in your php:
if (isset($_POST['submit'])) {
// do your stuff, eg...
$encrypt = $_POST['in'];
}
EDIT #1: Added to that, you seem to have 2 forms and 2 submit buttons. I suggest you keep only one form, and one submit button (remove the 2nd form element and submit button).
If you really need 2 forms, name your submit buttons differently and then you can call them separately.
<input type="submit" name="submit-in">
<!-- ... -->
<input type="submit" name="submit-out">
<?php // ...
if (isset($_POST['submit-in'])) {
// do your stuff, eg...
$encrypt = $_POST['in'];
}
if (isset($_POST['submit-out'])) {
// do your stuff, eg...
$dencrypt = $_POST['out'];
}
EDIT #2: If you want to echo stuff posted in your form, make sure you do the form submission checking and variable setting before the form and then echo the variable after the form (or wherever you want).
you need to first check if the form has been sent, if it hasn't then $_POST['in'] does not yet exist thus throwing the error
May be nothing but you called a php script after closing the form /form, the body /body and then then the HTML /html
replace this code $encrypt = $_POST['in']; by this $encrypt = #$_POST['in'];
this is an error on client server when you upload this file on remote server you will not saw this. use # sign on the client server when you saw this error in future.

Losing form data

I want to use back option on php without losing the form data.
I've tried this way;
if ($username==""){
echo 'Please fill. <input type="button" value="Back" onClick="history.back()">';
} else{
$doaction;
}
And this way;
$url= $_SERVER['HTTP_REFERER'];
if ($username==""){
echo "Please fill.";
header("refresh: 2; url=$url");
}
else{
$doaction;
}
On both ways I lose my data. How can I make this better?
This worked for me and using ob_start(); (in PHP below) needs to be included, otherwise it will throw an error, such as:
PHP Warning: Cannot modify header information - headers already sent by (output started)
Use the following exactly as shown, then modify to suit later.
Using Sessions is a way to achieve this. Each field will re-appear in the input boxes, if they were filled.
HTML form (form.php)
<?php
session_start();
?>
<form method="post" action="submitted.php">
<p>
<label for='name'>Your Name:</label>
<br>
<input type="text" name="username" value="<?php echo isset($_SESSION['username']) ? $_SESSION['username'] : '' ?>">
</p>
<p>
<label for='name'>Email:</label>
<br>
<input type="text" name="email" value="<?php echo isset($_SESSION['email']) ? $_SESSION['email'] : '' ?>">
</p>
<input type="submit" name="submit" value="Submit">
<br>
</form>
PHP (submitted.php)
<?php
ob_start();
session_start();
$_SESSION['username'] = $_POST['username'];
$_SESSION['email'] = $_POST['email'];
$url= $_SERVER['HTTP_REFERER'];
$username=$_POST['username'];
$email=$_POST['email'];
// use this one below, if you want to check more than one field
// if (empty($_POST['username']) || empty($_POST['email']) ){
if (empty($_POST['username'])){
echo "Fill in all fields.";
header("refresh: 2; url=$url");
}
else{
echo "OK, redirecting back to show fields are showing, or not.";
header("refresh: 2; url=$url");
}
Your approach reloads the formular, so the webserver will send a clean form to the client. If you want a prefilled form you will have to use a PHP script which knows the formerly filled in values and creates a prefilled form.
In the code you have used, (assuming you have a form further up) there is no data being passed between the pages because nothing is telling the script to transfer the data between that page and it's destination.
In your first example, history.back() simply tells the browser to go back to the last page viewed before the current one. In your second example, your header line essentially just tells the browser to go back to the previous page after two seconds.
To keep data between page transfers, without any further knowledge of what you're doing, I would suggest using JavaScript to fetch your form data and pass it into a URL used in a window.location call (forming a GET request with your form data in it), OR by using javascript to set a cookie containing the data input before you tell the browser to switch page.
In the first solution, you could then use php's $_GET global to access your form data.
In the second solution, you could use javascript to re-populate the form on page load (or at will)

PHP form - on submit stay on same page

I have a PHP form that is located on file contact.html.
The form is processed from file processForm.php.
When a user fills out the form and clicks on submit,
processForm.php sends the email and direct the user to - processForm.php
with a message on that page "Success! Your message has been sent."
I do not know much about PHP, but I know that the action that is calling for this is:
// Die with a success message
die("<span class='success'>Success! Your message has been sent.</span>");
How can I keep the message inside the form div without redirecting to the
processForm.php page?
I can post the entire processForm.php if needed, but it is long.
In order to stay on the same page on submit you can leave action empty (action="") into the form tag, or leave it out altogether.
For the message, create a variable ($message = "Success! You entered: ".$input;") and then echo the variable at the place in the page where you want the message to appear with <?php echo $message; ?>.
Like this:
<?php
$message = "";
if(isset($_POST['SubmitButton'])){ //check if form was submitted
$input = $_POST['inputText']; //get input text
$message = "Success! You entered: ".$input;
}
?>
<html>
<body>
<form action="" method="post">
<?php echo $message; ?>
<input type="text" name="inputText"/>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
The best way to stay on the same page is to post to the same page:
<form method="post" action="<?=$_SERVER['PHP_SELF'];?>">
There are two ways of doing it:
Submit the form to the same page: Handle the submitted form using PHP script. (This can be done by setting the form action to the current page URL.)
if(isset($_POST['submit'])) {
// Enter the code you want to execute after the form has been submitted
// Display Success or Failure message (if any)
} else {
// Display the Form and the Submit Button
}
Using AJAX Form Submission which is a little more difficult for a beginner than method #1.
You can use the # action in a form action:
<?php
if(isset($_POST['SubmitButton'])){ // Check if form was submitted
$input = $_POST['inputText']; // Get input text
$message = "Success! You entered: " . $input;
}
?>
<html>
<body>
<form action="#" method="post">
<?php echo $message; ?>
<input type="text" name="inputText"/>
<input type="submit" name="SubmitButton"/>
</form>
</body>
</html>
Friend. Use this way, There will be no "Undefined variable message" and it will work fine.
<?php
if(isset($_POST['SubmitButton'])){
$price = $_POST["price"];
$qty = $_POST["qty"];
$message = $price*$qty;
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="#" method="post">
<input type="number" name="price"> <br>
<input type="number" name="qty"><br>
<input type="submit" name="SubmitButton">
</form>
<?php echo "The Answer is" .$message; ?>
</body>
</html>
You have to use code similar to this:
echo "<div id='divwithform'>";
if(isset($_POST['submit'])) // if form was submitted (if you came here with form data)
{
echo "Success";
}
else // if form was not submitted (if you came here without form data)
{
echo "<form> ... </form>";
}
echo "</div>";
Code with if like this is typical for many pages, however this is very simplified.
Normally, you have to validate some data in first "if" (check if form fields were not empty etc).
Please visit www.thenewboston.org or phpacademy.org. There are very good PHP video tutorials, including forms.
You can see the following example for the Form action on the same page
<form action="" method="post">
<table border="1px">
<tr><td>Name: <input type="text" name="user_name" ></td></tr>
<tr><td align="right"> <input type="submit" value="submit" name="btn">
</td></tr>
</table>
</form>
<?php
if(isset($_POST['btn'])){
$name=$_POST['user_name'];
echo 'Welcome '. $name;
}
?>
simple just ignore the action attribute and use !empty (not empty) in php.
<form method="post">
<input type="name" name="name">
<input type="submit">
</form>
<?PHP
if(!empty($_POST['name']))
{
echo $_POST['name'];
}
?>
Try this... worked for me
<form action="submit.php" method="post">
<input type="text" name="input">
<input type="submit">
</form>
------ submit.php ------
<?php header("Location: ../index.php"); ?>
I know this is an old question but since it came up as the top answer on Google, it is worth an update.
You do not need to use jQuery or JavaScript to stay on the same page after form submission.
All you need to do is get PHP to return just a status code of 204 (No Content).
That tells the page to stay where it is. Of course, you will probably then want some JavaScript to empty the selected filename.
What I do is I want the page to stay after submit when there are errors...So I want the page to be reloaded :
($_SERVER["PHP_SELF"])
While I include the sript from a seperate file e.g
include_once "test.php";
I also read somewhere that
if(isset($_POST['submit']))
Is a beginners old fasion way of posting a form, and
if ($_SERVER['REQUEST_METHOD'] == 'POST')
Should be used (Not my words, read it somewhere)

Categories