I want to have an email sending system on my site.
The problem is when I try to assign a variable text from my HTML file it does not happen. I want that what is inside the variable should be written in the message of the email. Here's my code:
<html>
<?php include('form.php'); ?>
<head>
</head>
<body>
<form action="./form.php" method="post">
<div name="name"><input type="text" id="name"></div>
<div name="surname"><input type="text" id="surname"></div>
<div name="message"><textarea rows="4" cols="50" id="message">Inserisci qui il tuo testo.</textarea></div>
<div name="subject"><select id="subject">
<option selected="selected">--Inserisci Oggetto--</option>
<option>Registrazione al sito</option>
<option>Recupero credenziali</option>
</select></div>
<input type="submit" value="Invia penzolini"/>
<input type="hidden" name="button_pressed" value="1" />
</form>
</body>
</html>
<?php
$dochtml = new domDocument();
$dochtml->loadHTML('index.html');
if(isset($_POST['button_pressed']))
{
//prendi nome
$name = $dochtml->getElementById('name');
//prendi cognome
$surname = $dochtml->getElementById('surname');
//prendi l'oggetto della mail
$subject = $dochtml->getElementById('subject');
//msg<70 caratteri
$msg = "Inviato da" . ' ' . $name . $surname . ' ' . $dochtml->getElementById('message'); // /n=spazio
// manda mail
mail("panzersit#gmail.com",$subject,$msg);
echo 'Email inviata.';
}
?>
PHP cannot directly access your DOM. PHP runs only the server and on simple terms takes requests and gives a response.
Upon submit of this form to it's action page ./form.php, the values of the input forms are stored in the $_POST in a key named after it's name attribute. In your HTML code, add name attributes to the input tags like so:
<form action="./form.php" method="post">
<div name="name"><input type="text" name="name"></div>
<div name="surname"><input type="text" name="surname"></div>
</form>
Now if I submit this form and input Zachary for name input tag and Taylor for surname input tag, I can grab these values like so:
in ./form.php file:
$name = $_POST['name'];
// "Zachary"
$surname = $_POST['surname'];
// "Taylor"
To validate if anything was input in the first place, use:
isset($_POST['key']) since SOMETIMES input values with a null value are not even sent to the action page. This prevents PHP from throwing errors if you reference a $_POST key that does not exist.
Looking at documentation ( http://php.net/manual/pt_BR/domdocument.getelementbyid.php ) i'm locate a pontual observation:
"Please note that if your HTML does not contain a doctype declaration, then getElementById will always return null."
Post the contents of form.php will help to recreate the scenario.
To get the posted data from your submitted form, you can do it using $_POST['fieldname']
Just try as below and see what you are getting after form submission.
//echo "<pre>";
//print_r($_POST);
Uncomment above 2 lines, see what you are getting and COMMENT IT AGAIN.
if( isset($_POST['name']) )
{
$name = $_POST['name'];
}
if( isset($_POST['surname']) )
{
$surname = $_POST['surname'];
}
if( isset($_POST['subject']) )
{
$subject = $_POST['subject'];
}
Related
I am trying to make a php program where user will input $name but it will replace with its variable. The code is given bellow
<form method="post" >
<textarea type="text" name="preview"></textarea>
<input type="submit" value="preview"></input>
<form>
<?php
$name="Nahid";
echo $_POST['preview'];
?>
I am expecting an output like: My name is Nahid.
when user will input: My name is $name.
I modified the code to help achieve the stated objective of the program.
I also added some comments to help you understand the code.
I replaced <textarea> with an input field, and I changed the name from 'preview' to 'name' to avoid confusion.
<!DOCTYPE html>
<html>
<head>
<title>Name Preview</title>
</head>
<body>
<form action= "" method="post">
<label>Name: </label>
<input type="text" name="name">
<input type="submit" name="submit" value="PREVIEW"></input>
<form>
</body>
</html>
<?php
// Ensure that form is submitted
if(isset($_POST['submit']))
{
// Ensure that a name is entered
if (isset($_POST['name']) && !empty($_POST['name']))
{
// Store user's input in a variable
$name = htmlentities($_POST['name']);
// Display name
echo "<p>";
echo "My name is " . $name;
echo "</p>";
}
else
{
// Display notification if no name is entered.
echo "Please enter your name";
}
}
?>
Hope that is helpful.
if you enter your name in text area and submit form so you will see entered text
if you enter same value 'Nahid' in text area so you think $name is showing instead of $_POST['preview']
you can concat $name with $_POST['preview'] using dot
test folooowing code:
echo $name . ' <br> ' . $_POST['preview'];
please enter another name in textarea to test it
I have a form that has action="file.php" , That PHP file has the cheeks and outputs , I want these outputs to be on the same form page.
The form exists in an html file :
<form class="" method="post" action="file.php">
<!-- Some Form Fields -->
</form>
The file.php contains some checks and outputs like:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
if ( empty($name){
echo "Name can't be empty.";
}
}
How to show these outputs on the same page next to the form?
If you are posting to the same page, you can echo errors on the same page & retain the posted data no problem with something like this.
in php
$errors = []
if (empty($name){
$errors['name'] = "Name can't be empty.";
}
... and on the form
<php if (isset($errors['name'])) echo $errors['name']; ?>
<input name='name' value="<?php if (isset($_POST['name'])) echo $_POST['name']; ?>"></input>
If you are posting to a different url, then you will have to redirect back to the form page or include the form page, and pass the $errors and the $_POST data.
Do everything in the same file.php:
<form class="" method="post" action="file.php">
<!-- Some Form Fields -->
</form>
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
if ( empty($name){
echo "Name can't be empty.";
}
}
If you're trying to have that validation in the same form file, let's call it 'form.html', first rename it to 'form.php'. Then add the <?php ?> tags above all the html code, and write your code there.
For that to work, you need to have to left empty the action attribute in form
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
if ( empty($name){
echo "Name can't be empty.";
}
}
?>
<!-- Some HTML Code-->
<form class="" method="post" action="">
<!-- Some Form Fields -->
</form>
I hope this answer your question about having the code in the same page, but if what you're trying to do is check if field is empty, i recommend you use the 'required' attribute in the html form's input.
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
}
}
I have an email form that checks three fields, name, valid email and comments. But the way it's set up now, since name and comments are in one function it first checks name and comments even if email is not valid, how can I re-write it so it checks the fields in order. Also, I would like to re-display the fields that have no errors, so the user doesn't have to type again. Please help. Thanks
<?php
$myemail = "comments#myemail.com";
$yourname = check_input($_POST['yourname'], "Enter your name!");
$email = check_input($_POST['email']);
$phone = check_input($_POST['phone']);
$subject = check_input($_POST['subject']);
$comments = check_input($_POST['comments'], "Write your comments!");
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("Enter a valid E-mail address!");
}
exit();
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<!doctype html>
<html>
<body>
<form action="myform.php" method="post">
<p style="color: red;"><b>Please correct the following error:</b><br />
<?php echo $myError; ?></p>
<p>Name: <input type="text" name="yourname" /></P>
<P>Email: <input type="text" name="email" /></p>
<P>Phone: <input type="text" name="phone" /></p><br />
<P>Subject: <input type="text" style="width:75%;" name="subject" /></p>
<p>Comments:<br />
<textarea name="comments" rows="10" cols="50" style="width: 100%;"></textarea></p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
<?php
exit();
}
?>
First off, I would suggest you validate ALL of the fields at once, and display all appropriate error messages on the form. The primary reason is that it can be bad user experience if they have to submit your form a whole bunch of times because they have to address one error at a time. I'd rather correct my email address, password, comments, and selection in one try instead of fixing one at a time just to reveal what the next error is.
That said, here are some pointers on validating the form like you want. This is typically how I approach a form doing what you want to do. This assumes your form HTML and form processor (PHP) are together in the same file (which is what you have now). You can split the two, but the methods for doing that can be a bit different.
Have one function or code block that outputs the form and is aware of your error messages and has access to the previous form input (if any). Typically, this can be left outside of a function and can be the last block of code in your PHP script.
Set up an array for error messages (e.g. $errors = array()). When this array is empty, you know there were no errors with the submission
Check to see if the form was submitted near the top of your script before the form is output.
If the form was submitted, validate each field one at a time, if a field contained an error, add the error message to the $errors array (e.g. $errors['password'] = 'Passwords must be at least 8 characters long';)
To re-populate the form inputs with the previous values, you have to store the entered values somewhere (you can either just use the $_POST array, or sanitize and assign the $_POST values to individual variables or an array.
Once all the processing is done, you can check for any errors to decide whether the form can be processed at this point, or needs new input from the user.
To do this, I typically do something like if (sizeof($errors) > 0) { // show messages } else { // process form }
If you are re-displaying the form, you simply need to add a value="" attribute to each form element and echo the value that was submitted by the user. It is very important to escape the output using htmlspecialchars() or similar functions
With those things in place, here is some re-work of your form to do that:
<?php
$myemail = "comments#myemail.com";
$errors = array();
$values = array();
$errmsg = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
foreach($_POST as $key => $value) {
$values[$key] = trim(stripslashes($value)); // basic input filter
}
if (check_input($values['yourname']) == false) {
$errors['yourname'] = 'Enter your name!';
}
if (check_input($values['email']) == false) {
$errors['email'] = 'Please enter your email address.';
} else if (!preg_match('/([\w\-]+\#[\w\-]+\.[\w\-]+)/', $values['email'])) {
$errors['email'] = 'Invalid email address format.';
}
if (check_input($values['comments']) == false) {
$errors['comments'] = 'Write your comments!';
}
if (sizeof($errors) == 0) {
// you can process your for here and redirect or show a success message
$values = array(); // empty values array
echo "Form was OK! Good to process...<br />";
} else {
// one or more errors
foreach($errors as $error) {
$errmsg .= $error . '<br />';
}
}
}
function check_input($input) {
if (strlen($input) == 0) {
return false;
} else {
// TODO: other checks?
return true;
}
}
?>
<!doctype html>
<html>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<?php if ($errmsg != ''): ?>
<p style="color: red;"><b>Please correct the following errors:</b><br />
<?php echo $errmsg; ?>
</p>
<?php endif; ?>
<p>Name: <input type="text" name="yourname" value="<?php echo htmlspecialchars(#$values['yourname']) ?>" /></P>
<P>Email: <input type="text" name="email" value="<?php echo htmlspecialchars(#$values['email']) ?>" /></p>
<P>Phone: <input type="text" name="phone" value="<?php echo htmlspecialchars(#$values['phone']) ?>"/></p><br />
<P>Subject: <input type="text" style="width:75%;" name="subject" value="<?php echo htmlspecialchars(#$values['subject']) ?>" /></p>
<p>Comments:<br />
<textarea name="comments" rows="10" cols="50" style="width: 100%;"><?php echo htmlspecialchars(#$values['comments']) ?></textarea></p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
I have a more advanced example which you can see here that may give you some guidance as well.
Hope that helps.
The simplest option is to use a form validation library. PHP's filter extension, for example, offers validation and sanitization for some types, though it's not a complete solution.
If you insist on implementing it yourself, one issue you'll have to consider is what counts as the order: the order of the elements in the form or the order of the user input in $_POST. On most browsers, these should be the same, but there's no standard that enforces this. If you want to go off of form order, you'll need to define the form structure in one place, and use that information to do things like generating or validating the form (a consequence of the Don't Repeat Yourself (DRY) principle). Iterating over the appropriate structure will give you the order you desire: looping over the form gives you form order, whereas looping over $_POST gives you user input order.
It looks like you want to more than simply validate the data; you also want to prepare it for use, a process called "sanitization".
When it comes to sanitization, define different kinds of sanitizers, rather than a single check_input function. Specific sanitizers could be functions, or objects with an __invoke method. Create a map of form fields to sanitizers (for example, an array of input name to sanitizer callbacks). The order of the elements in the mapping sets the order of the sanitization; if you use a single structure to define the form information, the display order and sanitization order will thus be the same.
Here's a very broad outline:
# $fields could be form structure or user input
foreach ($fields as $name => $data) {
# sanitize dispatches to the appropriate sanitizer for the given field name
$form->sanitize($name, $data);
# or:
//sanitize($name, $data);
# or however you choose to structure your sanitization dispatch mechanism
}
As for setting an input's value to the user-supplied data, simply output the element value when outputting the element. As with all user input (really, all formatted output), properly escape the data when outputting it. For HTML attributes, this means using (e.g.) htmlspecialchars. Note you should only escape outgoing data. This means your sanitization functions shouldn't call htmlspecialchars.
You can improve usability by placing each error next to the corresponding input, adding an "error" class to the element and styling the "error" class to make it stand out. Improve accessibility by wrapping <label> elements around the label text.
Use this structure of script:
<?php
$errors = array();
if (isset($_POST['send'])) {
// check data validity
if (!mailValid($_POST['email']))
$errors[] = 'Mail is not valid';
...
// send data by email
if (!$errors) {
// send mail and redirect
}
}
?>
<html>
...
<?php
if ($errors) {
// display errors
foreach ($errors as $error) {
echo "$error<br />";
}
}
?>
<form ...>
...
Email: <input type="text" name="email" value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : '' ?>" />
...
</form>
...
</html>
You could always do it like this, using filter_var and in_array checks:
<?php
$myemail = "comments#myemail.com";
//Pre made errors array
$errors=array('name'=>'Enter Your name',
'email'=>'Please enter valid email',
'phone'=>'Please enter valid phone number',
'subject'=>'Please enter valid subject, more then 10 chars',
'comment'=>'Please enter valid comment, more then 10 chars');
//Allowed post params and its validation type
$types = array('name'=>'string',
'email'=>'email',
'phone'=>'phone',
'subject'=>'string',
'comment'=>'string');
//A simple validation function using filter_var
function validate($value,$type){
switch ($type){
case "email":
return ((filter_var($value, FILTER_VALIDATE_EMAIL))?true:false);
break;
case "phone":
return ((preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $value))?true:false);
break;
case "string":
return ((strlen($value) >=10 )?true:false);
break;
default:
return false;
break;
}
}
//If forms been posted
if(!empty($_POST) && $_SERVER['REQUEST_METHOD'] == 'POST'){
//Assign true, if all is good then this will still be true
$cont=true;
$error=array();
foreach($_POST as $key=>$value){
//if key is in $types array
if(in_array($key,$types)){
//If validation true
if(validate($value, $types[$key])==true){
$$key=filter_var($value, FILTER_SANITIZE_STRING);
}else{
//Validation failed assign error and swithc cont to false
$error[$key]=$errors[$key];
$cont=false;
}
}
}
}
if($cont==true && empty($error)){
//Send mail / do insert ect
}else{
//Default to form
?>
<!doctype html>
<html>
<body>
<form action="" method="post">
<p>Name: <input type="text" name="name" value="<?=#htmlentities($name);?>"/> <?=#$error['name'];?></P>
<P>Email: <input type="text" name="email" value="<?=#htmlentities($email);?>" /> <?=#$error['email'];?></p>
<P>Phone: <input type="text" name="phone" value="<?=#htmlentities($phone);?>"/> <?=#$error['phone'];?></p><br />
<P>Subject: <input type="text" style="width:75%;" name="subject" /> <?=#$error['subject'];?></p>
<p>Comments: <?=#$error['comment'];?><br />
<textarea name="comment" rows="10" cols="50" style="width: 100%;"><?=#htmlentities($comment);?></textarea></p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
<?php
}?>
Trying to make my own contact form with php. Is there a better/cleaner way to approach this?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1 /DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Contact Form Practice</title>
</head>
<body>
<form method="POST" action="mailer.php">
Name:
<br>
<input type="text" name="name" size="19"><br>
<br>
Your Email Adress:
<br>
<input type="text" name="email" size="19"><br>
<br>
Message:
<br>
<textarea rows="9" name="message" cols="30"></textarea>
<br>
<br>
<input type="submit" value="Submit" name="submit">
</form>
</body>
</html>
----------------php---------------
<?php
if(isset($_POST['submit'])) {
$to = "mail#cheapramen.com";
$subject = "Contact";
$name_field = $_POST['name'];
$email_field = $_POST['email'];
$message = $_POST['message'];
$body = "From: $name_field\n E-Mail: $email_field\n Message:\n $message";
echo "Data has been submitted to $to!";
mail($to, $subject, $body);
} else {
echo "4! OH! 4!";
}
?>
The code seems correct, but I'd highly recommend adding in some data validation. You'll want to make sure all required fields are filled out with valid info. Also be sure to encode/strip any HTML, JS, etc for security/readability purposes.
Lastly, you should also consider using CAPTCHA to guard against spam. I've got an old site running code similar to this and used to get over 500 spam emails a day!
That's pretty much it, maybe on successful completion you can do a header() redirect to a confirmation page, but as far as processing the form what you have is pretty standard.
Also, you want to sanitize your data as a standard practice of accepting any user input.
You might want to look into implementing a CAPTCHA to prevent the bots from hammering your form as well.
PHP Captcha
One thing you definitely want to do is make the data a bit safer to send in the email. I would at least run the htmlentities and strip_tags on the input data but you should definitely look in to doing further validation.
Also instead of isset($_POST["SUBMIT"]) I would maybe do something like...
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// body code here
}
I would HIGHLY recommend looking up some information about PHP mail() hijacking and making sure you are not going to leave your script vulnerable to such an attack. Also what everyone else suggested is very good to do as well.
In the question, you had 2 separate files processing the form. The problem is if you get a validation error, you are left with little choice but the awful "Please click you back button" solution.
Consider this template PHP file that will handle it all on one page, provide for data validation, errors, re-submitting, and the whole 9 yards.
<?php
// Read input variables from _POST
$FormAction = (isset($_POST['FormAction']) ? $_POST['FormAction'] : '');
$FirstName = trim(isset($_POST['FirstName']) ? $_POST['FirstName'] : '');
...
// Define script variables
$Errors = array();
// Process input if data was posted.
switch($FormAction)
{
case 'Process':
// validation code
if(empty($FirstName) or strlen($FirstName) > 20)
$Errors[] = "First name is required.";
...
if(count($Errors) > 0)
break;
// Here we have valid data.. Do whatever...
// Now, redirect somewhere.
header('Location: http://www.next.com/whatever');
exit;
}
?>
<html>
<body>
<?php if(count($Errors)) { ?>
<div class="Error">
<?php foreach($Error as $Error) { ?>
<div><?php echo htmlspecialchars($Error); ?></div>
<?php } ?>
</div>
<?php } ?>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER['REQUES_URI'], ENT_QUOTES); ?>" />
<input type="hidden" name="FormAction" value="Process" />
First Name:
<input type="text" name="FirstName" value="<?php echo htmlspecialchars($FirstName, ENT_QUOTES); ?>" />
...
<input type="submit" />
</form>
</body>
</html>