I have this small test page trying to mess around and figure out PHP code, from what I understand, after filling the forms and hitting submit, something should happen. Depending on what you entered.
<!DOCTYPE html>
<html>
<head>
<title>PHP Testing Page</title>
</head>
<body>
<?php
echo "Testing Page, working great!\n";
$theDate = date("M-d-Y ");
echo "Today is " . $theDate;
$email1 = $_POST['email1'];
$email2 = $_POST['email2'];
function checkEmail()
{
$email1 = $_POST['email1'];
$email2 = $_POST['email2'];
echo $email1;
echo $email2;
if($email1==$email2)
{
echo "\nE-Mail Addresses match.";
}
else
{
echo "\nCheck to make sure your E-Mails match";
}
}
?>
<form name="checkingEmail" action="." method="post">
E-Mail: <input type="text" name="email1" value="E-Mail Here" />
<br />
Retype E-Mail: <input type="text" name="email2" value="Confirm E-Mail" />
<br />
<input type="button" value="Submit" onClick="checkEmail()">
</form>
</body>
</html>
After the forms are filled (via visiting page) and the Submit button is clicked, nothing happens. Can someone explain please?
********EDIT******FIXED**
Found a work around! No functions, works like a charm.
<!DOCTYPE html>
<html>
<head>
<title>PHP Testing Page</title>
</head>
<body>
<?php
echo "Testing Page, working great!\n";
$theDate = date("M-d-Y ");
echo "Today is " . $theDate;
?>
<form name="checkingEmail" action="test.php" method="post">
E-Mail: <input type="text" name="email1" value="E-Mail Here" />
<br />
Retype E-Mail: <input type="text" name="email2" value="Confirm E-Mail" />
<br />
<input type="submit" value="Submit">
</form>
<?php
$email1 = $_POST["email1"];
$email2 = $_POST["email2"];
if($email2==null)
{
/*I believe this just stops it from checking the rest of the conditions, that
way it won't echo anything until someones enters valid (non-null) input*/
$email2 = "notnull";
}
else if($email1==$email2)
{
echo "Good Job.";
}
else
{
echo "Failure to comply.";
}
?>
</body>
I have the check outside of a function, so I don't have to call it or anything like that. Also, with the first if statement, if $email2 is null (When they first load it) it will
simply change $email2 to "notnull" and stop checking statements because it found a valid
one. (Not 100%)
Where is your submit button ?
<input type="button" value="Submit" onClick="checkEmail()">
^
The type should be submit
As mentioned on this answer comments, you can't call a php function from javascript.
When you do it you'll call checkEmail from a javascript, which isn't defined.
So, you'll get the following error:
Uncaught ReferenceError: checkEmail is not defined
type should be submit;
If you change it to the submit and then run it, it should be fine. You should use submit type with Form elements.
Related
I've just got into php recently, and now i am working on a login form which has a signup page and a signup script to do all the database and such. But my $_POST is not working at all. I`ve tried searching online, confirm that my xampp/php/php.ini setting enable post process, and such. But all i get is nothing. To make the problem simpler i used a post tutorial code online
Posttest.php
<!DOCTYPE HTML>
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" id="name" name="name"><br>
E-mail: <input type="text" id="email" name="email"><br>
Submit
</form>
</body>
</html>
welcome.php
<html>
<body>
<?php
$disname="";
$disname = isset($_POST['name']) ? $_POST['name'] : '';
echo "$disname is your username";
var_dump($_POST);
?>
</body>
</html>
and the result is empty. Please help i`ve been working on this problem for few days.
Everything looks fine but the submit href link, which you should replace with a Submit input type:
Submit
to:
<input type="submit">
You can't use "a" tag for submit. "a" tag just direct to address. So you should use this:
<input type = "submit" value = "Submit">
<!DOCTYPE HTML>
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" id="name" name="name"><br>
E-mail: <input type="text" id="email" name="email"><br>
<input type = "submit" value = "Submit">
</form>
</body>
</html>
///////////////////////////////////////////////////////
//////welcome.php
<html>
<body>
<?php
$disname="";
$disname = isset($_POST['name']) ? $_POST['name'] : '';
echo "$disname is your username";
var_dump($_POST);
?>
</body>
</html>
I am currently learning the most basic PHP ever. I have 5 files.
index.php:
<html>
<head>
<title>Budget Calcule</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h2>Put in your: - </h2>
<form action="functions.php" method="post">
<h3>Income</h3>
<label>Salary: <input name="salary" type="text" /></label><br />
<h3>Outgoings</h3>
<label>Living: <input name="living" type="text" /></label><br />
<label>Insurance: <input name="insurance" type="text" /></label><br />
<label>Communication: <input name="communication" type="text" /></label><br />
<label>Loan: <input name="loan" type="text" /></label><br />
<label>Food & Drink: <input name="foodAndDrink" type="text" /></label><br />
<label>Entertaintment / Shopping: <input name="entertainmentOrShopping" type="text" /></label><br />
<label>Transport: <input name="transport" type="text" /></label><br />
<label>Other: <input name="other" type="text" /></label><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
this is my functions.php:
<?php
include('variables.php');
if(!($_POST['Submit'])){
if(isset($_POST['salary'])){
header('Location: output.php');
return $_POST['lon'];
}else{
echo "All fields are required";
}
}
?>
this is my variables.php:
<?php
$salary= $_POST['salary'];
$living= $_POST['living'];
$insurance= $_POST['insurance'];
$communication = $_POST['communication'];
$loan = $_POST['loan'];
$food = $_POST['food'];
$entertaintmentOrShopping = $_POST['entertaintmentOrShopping'];
$transport = $_POST['transport'];
$other= $_POST['other'];
?>
this is my output.php file:
<?php
include('outputFunction.php');
?>
<html>
<head>
<title>Output.php</title>
</head>
<body>
<?php myText(); ?>
</body>
</html>
and last but not least, this is my outputFunction.php file:
<?php
include('variables.php');
function myText(){
echo "Your salary per month is: " . $_POST['salary'];
}
?>
Now you're thinking "why have he split up his code in different files?" Well first of all, I split the variables from functions.php because I wanted outputFunctions.php to get the variables from variables.php so i could echo my `$_POST['salary']; . The function myText(); outputs the text just fine, but it doesnt output the $_POST['salary'];.
I do not know why it doesnt work, I just wonder if you could be my extra eyes and see if I've done some mistake.
PS! Don't down vote my question just because you think it's stupid. I am having problem with this issue and been working on it for hours without advancing anywhere.
A few things:
You don't need to include a variables.php file. The variables you're accessing are global and you're just creating duplicates that aren't being used. They also go away after the page changes since you're re-declaring them each page load.
You are also trying to call a variable that doesn't exist when you reference $_POST['lon'] instead of 'loan'.
And finally to actually answer your question:
Your myText() function is referencing a variable that is not there anymore.
You need to merge functions.php and outputFunction.php and output.php into one file so the variables aren't lost and all the processing is done without opening a new file each time. I can see your original concept for separated files but an output file is going to be the file to process the input data from the form.
Now in your newly merged output.php, you should have something resembling this:
<html>
<head>
<title>Output</title>
</head>
<body>
<?php
if(isset($_POST['Submit'])) {
if(isset($_POST['salary'])) {
echo "Your salary per month is: " . $_POST['salary'];
}
} else {
echo "All fields required.";
}
?>
</body>
</html>
This means only two files - your form page and this page.
A few more tips:
If you want to check if the form was submitted, it has look something like this:
if(isset($_POST['Submit'])){ ... }
Also, you should add a name="" attribute to your submit-Button:
<input type="submit" name="Submit" value="Submit" />
And what is the variables.php for? You don't use any of those variables.
When you redirect the user via header() the data that is stored in the $_POST array gets lost.
You could directly redirect to ouput.php
<form action="output.php" method="post">
And do something like this:
<?php
include('outputFunction.php');
if(isset($_POST['Submit'])) {
if(isset($_POST['salary'])) {
?>
<html>
<head>
<title>Output.php</title>
</head>
<body>
<?php myText(); ?>
</body>
</html>
<?php
} else {
echo "All field required";
}
}
?>
By the way you can always check what your $_POST contains with print_r($_POST);
This can be very useful for debugging.
OK so I have an email form on index.php. I am using mail_check.php to validate that both fields are filled in.
(there are more that is being validated, but not included as it is not the issue)
The main issue is that from the mail_check.php I want to be sent back to the index.php with a message in placed in the div id="mailrespond". I have chosen both PHP and Javascript to achieve this.
Index.php
<div id="mailrespond"></div>
<form method="post" action="mail_check.php">
<span>Name: <input type="text" name="name" maxlength="30" /></span><br />
<span>Email: <input type="text" name="email" maxlength="30" /></span><br />
<input type="submit" value="Sign Up" name="registration">
</form>
</div>
mail_check.php
if(isset($_POST['registration']))
$name = $_POST['name'];
$email = $_POST['email'];
if(empty($email) || empty($name)){
// if email and name are empty
//header ("location: index.php");
?>
<script language="javascript" type="text/javascript">
window.location.replace("index.php");
function msg() {
// creating elements are a safer method then innerHTML
dv = document.createElement('div'); // creates a Div element
dv.setAttribute('class', 'error_msg'); // adds error styling
txt = document.createTextNode('please enter your name and email '); // create the message
dv.appendChild(txt); // place the text node on the element
document.getElementById("mailrespond").appendChild(dv);
}
window.onload = msg;
</script>
<?php }
The code goes on, but My issue is that I am not getting the feed back messages. I am a little new to this all - if you can help that would be much appreciated! :)
<---- #downvoter please leave a reason! Thanks
Try this (and don't call a form field name, please since a form can have a name too)
Index.php
<!DOCTYPE html>
<html>
<head>
<title>Mail respond</title>
<script>
window.onload=function() {
document.getElementById("mailform").onsubmit=function(){
if (this.fullname.value=="" || this.email.value=="") {
alert("Please fill in name and email");
return false;
}
return true; // allow form submission
}
}
</script>
</head>
<body>
<div id="mailrespond"></div>
<form method="post" action="mail_check.php" id="mailform">
<span>Name: <input type="text" name="fullname" maxlength="30" /></span><br />
<span>Email: <input type="text" name="email" maxlength="30" /></span><br />
<input type="submit" value="Sign Up" name="registration">
</form>
</div>
</body>
</html>
mail_check.php
<?PHP
if(isset($_POST['registration']))
$name = $_POST['fullname'];
$email = $_POST['email'];
if(empty($email) || empty($name)){
// if email and name are empty - only seen if JavaScript is turned off
?>
<h3>You did not fill in name and email</h3>
<p>please wait to be redirected or click <a href='index.php'>here</a></p>;
<meta http-equiv="refresh" content="3; url=http://example.com/index.php" />
<script type="text/javascript">
window.onload=function() {
setTimeout(function() {
window.location.replace("index.php");
},3000);
}
</script>
<?php } ?>
You're redirecting to index.php in the msg function, so it does nothing else.
You should do it by pure PHP, set a component in $_SESSION, redirect by PHP to index.php and in the index.php check if the component exists.
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.
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>