HTML Form Directing to PHP File or Include PHP File - php

Which has higher security?
Including the PHP file on a web page for form use, or directing the user to a PHP file when they press a form button?
Example 1: include 'filename';
Example 2: form action="sendingtheuserhere.php" method="post"
Thank you

Generally, it wouldn't matter whether you include the PHP code that handles form data into the file that contains the form or to have a separate PHP file for the same purpose.
What would matter is how you handle the form data. Below is an example:
form.php - has the HTML form
<html>
<head></head>
<body>
<form action="send.php" method="post">
<input name="subject" />
<textarea name="message"></textarea>
<button>Send</button>
</form>
</body>
</html>
send.php - handles form data
<?php
$user_subject = $_POST['subject'];
$user_message = $_POST['message'];
$send_to = 'myemail#gmail.com';
mail($send_to, $user_subject, $subject_message);
?>
Now with the above code, there are a couple things you should know.
The send.php file has unsafe code.
Visiting the send.php will send an email to the $send_to address whether someone files the form or not.
Now if you were to have to separate files, every time you visit the send.php file, an email would be sent. That is whether you fill in the form or you simply visit send.php link.
Second, if you were to combine the two files, you would have an email sent to you every time someone opens your form. That is because the mail(); function is triggered every time.
To combat this, you have to make sure the mail function triggers only when the form is submitted. You can do so by changing the code in send.php to the following:
new send.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") { // checks whether a POST request actually exists or not.
$user_subject = strip_tags(trim($_POST['subject']));
$user_message = strip_tags(trim($_POST['message']));
$send_to = 'myemail#gmail.com';
mail($send_to, $user_subject, $subject_message);
} else {
echo 'form not filled';
}
?>
Now, in the above code, the first thing we did is to check whether a POST request actually existed. If not, you'll see "Form not filled". After that, to make the request a little more secure to any sort of code injections we used the PHP trim(); and strip_tags(); function.
You can combine the two PHP files like so:
form.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") { // checks whether a POST request actually exists or not.
$user_subject = strip_tags(trim($_POST['subject']));
$user_message = strip_tags(trim($_POST['message']));
$send_to = 'myemail#gmail.com';
mail($send_to, $user_subject, $subject_message);
}
?>
<html>
<head></head>
<body>
<form action="form.php" method="post">
<input name="subject" />
<textarea name="message"></textarea>
<button>Send</button>
</form>
</body>
</html>

Related

How I can pass user input between php files?

Now I have Simple email Login form
<form action="one.php">
<input type="email" name="email"/>
</form>
one.php is email filter gmail users and header them to a custom path
<?php
$email = $_POST['email'];
if (stripos($email, '#gmail.com') !== false) {
header('Location: ../gmail/index.html');
} else {
header('Location: /unknownusers');
}
?>
now we done with the first page
my question is
how can I email name to another page' example in /gmailusers
<html>
<head>
</head>
<body>
<div>
<font>Welcome back,</font>
<?php
include 'one.php';
echo $email; ?>
</div>
</body></html>
$email will not work in this because one.php doesn't have saved info
how I can make this
welcome back 'User.Email#gmail.com'
in index.html file
Can any body help me with the php code.
The easiest way to do this is to not use location redirection, but just include the file you want to show.
one.php
<?php
$email = $_POST['email'];
if (stripos($email, '#gmail.com') !== false) {
include "gmail.php";
} else {
header('Location: /unknownusers');
}
gmail.php
(This file would replace gmail/index.html because most server configurations won't pass .html files to the PHP processor.)
<html>
<head>
</head>
<body>
<div>
<font>Welcome back, <?php echo $email; ?></font>
</div>
</body></html>
In this case, one.php shows the gmail user what gmail.php dictates, and redirects other users to the unknownusers page.
If you want the 'login' to be persistent (so your server remembers who this person is), you'll need a session.
What you're doing doesn't make sense, but to get it working, in two.php replace...
echo $email;
with
echo $_POST['email'];
HOWEVER You're reloading the page in one.php, so the code change above should never be executed. (Why are you doing that?) Anyway, if security is not an issue, in one.php you can pass the email to the other pages by doing this...
header('Location: ../gmail/index.html&email='.$_POST['email']);
then, in the index.html file, you access the variable $_GET['email'].
If security is an issue, this gets more complicated.

captcha code not working

I have designed the comments box for getting comments. Instead of using captcha plugins, i have prepared custom captcha with 5 digit number. When I submit the details, still I getting error page. I have checked various sites in Google but could not find the correct answer.
comments.html - Comment box for comments
captcha.php - Custom captcha with 5 digit code
submit.php - for processing the code
error.html - error page for wrong entry
thank.html - Page on submitting successful
I am unable to sort-out where the mistake is. Kindly help me in this regards.
The sources codes of comments.html and submit.php is given below.
=========COMMENTS.HTML==============
<form action="submit.php" method="post">
Name: <input type="text" name="name" /> <br>
Email: <input type="text" name="email" /> <br>
Comments: <textarea name="coments" /> <br>
Enter Captcha <img src="captcha.php"><input type="text" name="vercode" /> <br>
<input type="submit" name='submit' onclick="show_confirm()" value="SUBMIT" />
</form>
=============SUBMIT.PHP=================
<?php
session_start();
if ($_POST["vercode"] != $_SESSION["vercode"] OR $_SESSION["vercode"]=='')
{
//This page should not be accessed directly. Need to submit the form.
header('Location: error.html');
exit;
}
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
if(empty($name) || empty($email)||empty($comments))
{
header('Location:error.html');
exit;
}
if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $_POST[email]))
{
header('Location:error.html');
exit;
}
$email_from = 'info#xxxxx.com';
$email_subject = "CONTACT FORM";
$email_body="============================\n".
"FULL NAME: $name\n".
"EMAIL-ID: $email\n".
"COMMENTS: $comments\n".
$to = "info2#xxxxx.com";
$headers = "From: $email_from \r\n";
mail($to,$email_subject,$email_body,$headers);
//done. redirect to thank-you page.
header('Location: thank.html');
?>
You need
session_start()
at the very top of your submit.php, that starts or resume your session so that you can access $_SESSION
You should check if the form was submitted first, then process the code. Example:
if(isset($_POST['submit'])) { // process stuff }
You didn't show what specific error you get, so I'm just going to link you to this simple PHP-GD captcha that I have used previously in some projects and works like a charm. Is really simple and easy to implement.
Simple PHP-GD captcha image
It looks like it may have something to do with your regex verification always returning false.
You may want to test if the rule you set is correct. Also, I have read on php.net that eregi() is now obsolete in 5.3.0, so maybe use preg_match() with PCRE_CASELESS flag instead ?

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)

using modal popup for php redirect

I have a php mail form (working fine) that currently redirects to a thank you page. I am revamping the site and would like to (instead of redirecting to another page) have (upon successful submit) a modal popup appear and say thank you. I would also need to have the form cleared since the user would be staying on the current page. I have searched (both on stackoverflow and web searches) for a solution. I have found a few "ideas" but nothing that has worked. I am currently using modal popups on other things on the site (since revamp) and generally understand how they work. I also have a basic understanding of php. I was thinking if its possible(?) to have some type of javascript in header to invoke the modal popup. I've also seen ideas of it needing to be AJAX.
Any help would be greatly appreciated.
Here's my html for form:
<p class="formrequired">Required fields are marked with an asterisk(*)</p>
<form action="form.php" method="post">
<ol class="forms">
<li><label for="first_name">*First Name</label><input type="text" name="first_name"/></li>
<li><label for="last_name">Last Name</label><input type="text" name="last_name"/></li>
<li><label for="email">*Email</label><input type="text" name="email"/></li>
<li><label for="comment">*Message</label><textarea name="comment"cols="45" rows="5"></textarea></li>
<li><input type="submit" value="Submit" class="submit"/>
</ol>
</form>
and my php:
<?php
$myemail = "person#email.com";
$first_name = check_input($_POST['first_name'], "Please enter your first name");
$last_name = check_input($_POST['last_name']);
$email = check_input($_POST['email']);
$comment = check_input($_POST['comment'], "Please enter your message");
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("E-mail address is not a valid email address");
}
$subject="New form submitted on Napoleonville Fire";
$message = "Hello Jordy!
Your contact form has been submitted by:
First Name: $first_name
Last Name: $last_name
E-mail: $email
They left the following message:
$comment
End of message.
";
mail($myemail, $subject, $message);
header('Location: thankyou.html');
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)
{
?>
<html>
<body>
<b>Please correct the following error:</b><br />
<?php echo $myError; ?>
</body>
</html>
<?php
exit();
}
?>
Again, thanks for any and all help.
I will have a "part 2" if this can be solved.
Two flows I can think of
Non-AJAX
Submit your form to the server as you currently do. Then when redering the success page, render the page with the modal showing. Provide a close button of some sort that set's display none on it or deletes it from the DOM altogether. In this approach you can handle rendering the empty form with PHP. This is the more traditional paradigm.
AJAX
For this, add an event handler to the form submission. Submit the form via AJAX, but don't immediately clear the form fields. Wait for the response from the server. If the server finds a validation error in the form submission for example you will have to update the form to reflect this error. If the server returns a success response, clear the form fields with Javascript and show the modal.

php contact form clean code

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>

Categories