- PHP Forms – Part2
- 4. Validating form data
- 5. Sanitizing form data
- strip_tags():
- htmlspecialchars():
- htmlentities():
- mysql_real_escape_string():
- Courses
- Formatting PHP Form Output for HTML Emails: A Guide
- How to format output from php form to html email
- How to create an email body from PHP output
- Get HTML output in PHP
- How can I add space in PHP between two outputs
PHP Forms – Part2
New here? Like SchoolsOfWeb on Facebook to stay up to date with new posts.
This is the part 2 of the PHP form. If you didn’t read the previous lesson, please read the previous one at first.
4. Validating form data
Now that you have learned how to retrieve form data, you need to validate it. It is necessary as because a user may add invalid or garbage data in the form. User inputted data are always suspicious. So, you need to be sure that the data are properly formatted.
There are different ways to validate form data. We’ll discuss few of those below. Consider the following form-
In the above form, the name is required and the username is required and must be at least 5 characters long. Let’s write the processing script (form-process.php) to validate the following four conditions-
- If the submit form button has been clicked
- If the user has added his name
- If the user added username
- If the username is at least 5 characters long.
else< echo “Name is missing.”; echo “
”; > if(!empty ($_POST[‘username’]))< // Check if the username is empty if(strlen($_POST[‘username’]) < 5 )< // Check if the username is at least 5 characters. echo “Username must be at least 5 characters long.”; echo “
”; >else < echo $name = $_POST[‘username’]; >>else< echo “Username is missing.”; echo “
”; > >else < echo “Unauthorized access to this page.”; >?>
- How to check whether a user has come to this page from the form page: Any user may come to this page directly pasting the URL of this page in the browser. To prevent unauthorized access, we’ll check whether the user comes to this page clicking the form button. PHP has a built-in function isset() which can take a variable as parameter and can check whether the variable is set. In line 3, we take the submit button as variable and check whether the submit button has been clicked. Here is the code again-
if(isset($_POST[‘send’]))
If the user comes here directly the function will return false and the warning at line 19 will be displayed-
“Unauthorized access to this page.”
5. Sanitizing form data
It is easy for hackers to inject malicious code through form inputs, remove important files from server, damage your database etc. So, you need to sanitize user inputs to remove suspicious characters or to alter user inputs to usable form. There are few built-in php functions that helps to sanitize form data. These are as follows-
strip_tags():
strip_tags() removes any HTML and PHP tags from a string.
Form input:
Lets add in the comment box in the form and hit submit.
htmlspecialchars():
Consider these five special characters – ampersand (&), double quote, single quote, greater than (>), and less than (<) characters. They have special meaning to HTML. For example in the beginning of an html page, we use less than (<) and greater than (>) characters that is . Problem is, hackers can also pass malicious scripts embedded in tags through form inputs. So, what you’ll do to protect this? Well, you can convert those special characters to their equivalent HTML entities. After converting, “less than character” (<) becomes < The following table shows the special HTML characters and their equivalent entities-
Special Characters | Equivalent Entities |
&(ampersand) | & |
“(double quote) | " |
‘(single quote) | ' |
<(less than) | < |
>(greater than) | > |
And, here is the form processing script (form-process4.php)
Form input:
Lets add in the comment box in the form and hit submit.
Explanation:
If you see the source of the output page(form-process4.php), you’ll see the following
<script>alert("Hi");</script>
See that the HTML special characters are converted to their equivalent html entities. In this format, the code has no power to do any harm.
On the other hand, if we didn’t use the htmlspecialchars() function, you’ll see a popup message says-“hi”. And, the source of the page would be-
htmlentities():
Other than the above 5 special characters, there are more characters in HTML. htmlentities() function converts all applicable characters to HTML entities.
strip_tags(): This function removes all the HTML and PHP tags from a string. So, if the users try to add any HTML or PHP tags in a form field where it is not allowed, you can remove those tags by using this function.
Note: HTML and PHP tags are not allowed.
And, here is the form processing script (form-process5.php)
Form input:
Lets add “HTML body starts with
Output:
HTML body starts with and end with
mysql_real_escape_string():
When interacting user inputs with the database, you need to escape it properly (to learn more about the escaping characters, click here) to play safely. mysql_real_escape_string() function helps to escaping any problematic characters.
And, here is the form processing script (form-process6.php)
"; if(mysql_num_rows($result) !=0) echo "Access Granted."; else echo "Access Denied."; >else < echo "Unauthorized access to this page."; >?>
Form input:
Let’s assume we have a database named “test” that has a table named “users”. Table user has two columns – “Username” and “Password”. The table has one sample data (“admin” as username and “123456” as password). Now, let’s add “anyname”(without double quote) as username field and “’ OR ” = ‘”(without double quote) as password field in the form.
Output:
SELECT * FROM users WHERE Username=’anyname’ AND Password=” OR ” = ”
Access Granted.
Explanation:
Though the Username and Password is not matched with the database information the query return a match, grant access. Please look at the query string in the Output. The last part (OR ‘’=’’) of the query satisfy the condition, hence, found a match.
Now, if we escape the user inputs, this wouldn’t be happened. mysql_real_escape_string() function escaping a quotation mark by adding a backslash in front of it. Now, uncomment line 9 and 10, and run the rum again. If you add the previous inputs, the output will be as follows-
Output:
SELECT * FROM users WHERE Username=’anyname’ AND Password=’\’ OR \’\’ = \”
Access Denied.
‹‹ PHP Forms – Part1 : Previous Lesson | Next Lesson: PHP Forms – Part3 ›› |
Courses
Formatting PHP Form Output for HTML Emails: A Guide
There is a possibility that your server may be exploited to send spam through automated posts using your script. To send emails in html format, one needs to support multipart content, which can be complex to implement. Creating a visually appealing html content requires knowledge of html and css.
How to format output from php form to html email
Depending on your requirements, creating a complete code for sending emails in HTML format may require a significant amount of effort.
- In your code, I have to mention you that you have might have a security issue since you allow your server to send email from a form with no validation. In some way, someone could use your server to send spam by automating the post from your script.
- email could be send in html according mime formats which could be quite complex to implement if you want to support multipart content (one version in plain text and one version in html). Fortunately most clients supports html today.
- If you want to send a beautiful html content well designed and so one, you must learn html and css. You should be aware to mail clients, do not always supports all css attributes, which make development a bit long.
I have tested it and it seems to be working well. You should give it a shot.
My first heading
My first paragraph
"; echo $error."
"; echo "Please go back and fix these errors.
"; die(); > // validation expected data exists if(!isset($_POST['first_name']) || !isset($_POST['last_name']) || !isset($_POST['email']) || !isset($_POST['security'])) < died('We are sorry, but there appears to be a problem with the form you submitted.'); >$first_name = $_POST['first_name']; // required $last_name = $_POST['last_name']; // required $email_from = $_POST['email']; // required $security = $_POST['security']; // required $code = $_POST['code']; // not required $error_message = ""; $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]$/'; if(!preg_match($email_exp,$email_from)) < $error_message .= 'The Email Address you entered does not appear to be valid.
'; > $security_exp = "/blue/"; if(!preg_match($security_exp,$security)) < $error_message .= 'Wrong solar system - sorry.
'; > $string_exp = "/^[A-Za-z .'-]+$/"; if(!preg_match($string_exp,$first_name)) < $error_message .= 'The First Name you entered does not appear to be valid.
'; > if(!preg_match($string_exp,$last_name)) < $error_message .= 'The Last Name you entered does not appear to be valid.
'; > if(strlen($error_message) > 0) < died($error_message); >$email_message = "Form details below.\n\n"; function clean_string($string) < $bad = array("content-type","bcc:","to:","cc:","href"); return str_replace($bad,"",$string); >$email_message .= "First Name: ".clean_string($first_name)."\n"; $email_message .= "Last Name: ".clean_string($last_name)."\n"; $email_message .= "Email: ".clean_string($email_from)."\n"; $email_message .= "code: ".clean_string($code)."\n"; // create email headers $headers = "Content-type: text/html\r\n"; $headers .= 'From: '.$email_from."\r\n". 'Reply-To: '.$email_from."\r\n" . 'X-Mailer: PHP/' . phpversion(); @mail($email_to, $email_subject, $email_message, $headers); @mail($email_from, $email_subject, $email_message, $headers); ?>
To format your email in HTML, it’s necessary to include the appropriate header details.
$headers = 'From: '.$email_from."\r\n". .
Concatenate the $headers .= with a dot to obtain the desired result.
$headers = "Content-type: text/html\r\n"; $headers .= 'From: '.$email_from."\r\n". .
Keep in mind that the first header line does not require a dot/concatenate, but subsequent headers will need it. For further guidance, refer to the manual on PHP.net.
Then add your HTML where you wish.
- The documentation for the PHP function used for sending emails can be found at the following URL: http://php.net/manual/en/function.mail.php.
How to format output from php form to html email, Firstly I am not a programmer — so I am trying to adapt things to what I need. I have been working for some weeks on a html form that produces a unique code and emails the data to me and the form o
How to create an email body from PHP output
Please note that I am still learning PHP, so my answer may not be entirely accurate. That being said, I believe I’ve just finished the second step of my project, which relates to the topic you’re discussing. To achieve this, I formatted all of my variables on the confirmation page in the following manner.
Setting all variables can simplify the use of the echo function. Instead of repeating the process of typing out variables, you can use a shortened version, such as . Once you have organized them, you can create an email template from your confirmation page that will display the variables correctly in each field. However, this approach may not be the most efficient, and it is simply a suggestion from someone who is still learning.
In case you require assistance with turning your confirmation page into an email template, I would be pleased to offer further help. To avoid overcrowding the response, I won’t elaborate much as I cannot comment until I reach 50 rep and I don’t want to digress from the topic.
Display php search results in html table, im running this php script and not quite getting the result i want. at the moment its giving me this output scuba tank mike 0.00 450.00 5.00 2012-06-04 18:50:22 scuba tan
Get HTML output in PHP
The form tag is invalid within another form. Although the name attribute is accurate, the tag itself should be .
Send email with PHP from html form on submit with the, I want to send an email with PHP when a user has finished filling in an HTML form and then emailing information from the form. I want to do it from the same script that displays the web page that has the form.
How can I add space in PHP between two outputs
The html entity code that generates a solitary space character is represented by .
You can also use the below code:
The presence of a single empty space can be directly interpreted by browsers, allowing it to function properly.
Html — How to create an email body from PHP output, The basic idea would be to wrap the output of your confirm.php script in output buffering control, capture the output and use that in your mail body. Welcome to StackOverflow. I think you should edit your question to re-focus it on the thing you want to achieve, namely to turn a PHP output (which is in HTML …