I'm learning PHP. A beginner. The code from the tutorial I follow is below.
<?php
if (isset($_POST['submit']) && (!empty($_POST['submit']))) {
$from = 'Alexey Pazukhin (alexey.pazukhin#mail.ru)';
$subject = $_POST['subject'];
$text = $_POST['elvismail'];
$output_form = FALSE;
if (empty($subject) && empty($text)){
echo 'Subject and text fields are empty. <br/>';
$output_form = TRUE;
}
if (empty($subject) && (!empty($text))) {
echo 'Subject field is empty. <br/>';
$output_form = TRUE;
}
if ((!empty($subject)) && empty($text)) {
echo 'Text field is empty. <br/>';
$output_form = true;
}
if((!empty($subject)) && (!empty($text))){
$dbc = mysqli_connect('localhost', 'root', 'root', 'elvis_store')
or die ('Connection failed. MySQL');
$query = "SELECT * FROM email_list";
$result = mysqli_query($dbc, $query)
or die('DB query error');
while ($row = mysqli_fetch_array($result)) {
$first_name = $row['first_name'];
$last_name = $row['last_name'];
$msg = "Dear $first_name $last_name, \n $text";
$to = $row['email'];
mail($to, $subject, $msg, 'From:' . $from);
echo 'Message sent:' . $to . '<br/>';
}
mysqli_close($dbc);
}
}
else {
$output_form = TRUE;
}
if ($output_form) {
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<label for="subject">Subject of email:</label><br />
<input id="subject" name="subject" type="text" value="<?php echo $subject; ?>" size="30" /><br />
<label for="elvismail">Body of email:</label><br />
<textarea id="elvismail" name="elvismail" rows="8" cols="40"><?php echo $text; ?></textarea><br />
<input type="submit" name="Submit" value="Submit" />
</form>
<?php
}
?>
The problem is that code doesn't send any mails after clicking Submit button (either I fill the fields or don't) and returns an empty (new) form in browser (Chrome).
Replace
<input type="submit" name="Submit" value="Submit" />
with
<input type="submit" name="submit" value="submit" />
you can only check - if(isset($_POST['Submit'])). You dont want to check for !empty.
In your input tag you have given name attribute as name="Submit".
so, use $_POST['Submit']
instead of $_POST['submit']
Because post variables are CASE SENSITIVE.
I'd change if (isset($_POST['Submit')) to if (isset($_POST['sendIt'))
and then i'd change <input type="submit" name="Submit" value="Submit" />
to:
<input type="submit" name="sendIt" value="Submit" />
This way your form has it's own unique send value rather than the bog standard submit which could lead to future issues if and when you decide to add anymore forms into the website.
Related
I created this signup page. The problem is when I click submit after I enter the information nothing happens. It just refreshes the same page. The info I enter should import into my database after I hit submit and display a thank you for signing up message after the submission. Please help. I'm trying to keep everything to single page by implementing the html and php code all on one page instead of 2 separate files.
<html>
<body>
<?php
$output_form = true; //declare a FLAG we can use to test whether or not to show form
$first_name = NULL;
$last_name = NULL;
$email = NULL;
if (isset($_POST['submit']) ) { //conditional processing based on whether or not the user has submitted.
$dbc = mysqli_connect('localhost', 'name', 'pswd', 'database')
or die('Error connecting to MySQL server.');
$first_name = mysqli_real_escape_string($dbc, trim($_POST['firstname']));
$last_name = mysqli_real_escape_string($dbc, trim($_POST['lastname']));
$email = mysqli_real_escape_string($dbc, trim($_POST['email']));
$output_form = false; // will only change to TRUE based on validation
//Validate all form fields
if (empty($first_name)) {
echo "WAIT - The First Name field is blank <br />";
$output_form = true; // will print form.
}
if (empty($last_name)) {
echo "WAIT - The Last Name field is blank <br />";
$output_form = true; // will print form.
}
if (empty($email)) {
echo "WAIT - The Email field is blank <br />";
$output_form = true; // will print form.
}
if ((!empty($first_name)) && (!empty($last_name)) && (!empty($email))) {
//End of form validation
//This section establishes a connection to the mysqli database, and if it fails display error message
$query = "INSERT INTO quotes (first_name, last_name, email, " .
"VALUES ('$first_name', '$last_name', '$email')";
$result = mysqli_query($dbc, $query)
or die('Error querying database.');
mysqli_close($dbc);
$to = 'email#email.com';
$subject = 'New Customer';
$msg = "$first_name $last_name\n" .
"Email: $email\n";
$mail = mail($to, $subject, $msg, 'From:' . $email);
if($mail){
header("Location: https://www.locate.com/blue.php".$first_name);
exit();
}
//Display the user input in an confirmation page
echo "<body style='margin-top: 100px; background-color: #f2f0e6;'><p style = 'color: #000000; text-align: center;font-size:300%; font-family:Arial, Helvetica, sans-serif;'><strong>Thanks for signing up!</strong></p><center><p style = 'color: #000000; text-align: center;font-size:200%; font-family:Arial, Helvetica, sans-serif;'>Contact us for any questions
</p>
</center>
</body>";
}//end of validated data and adding recored to databse. Closes the code to send the form.
} //end of isset condition. This closes the isset and tells us if the form was submitted.
else { //if the form has never been submitted, then show it anyway
$output_form = true;
}
if ( $output_form ) { //we will only show the form if the user has error OR not submitted.
?>
<div id="box">
<center><img src="../../images/duck.jpg" class="sign-up" alt="Sign Up"></center>
<br>
<p>Sign Up to get Discount Code</p><br>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?> ">
<div>
<label for="firstname">First name:</label>
<input type="text" id="firstname" name="firstname" size="37" maxlength="37" value=" <?php echo $first_name; ?>" />
</div>
<div>
<label for="lastname">Last name:</label>
<input type="text" id="lastname" name="lastname" size="37" maxlength="37" value="<?php echo $last_name; ?>" />
</div>
<div>
<label for="email">Email:</label>
<input type="text" id="email" name="email" size="37" maxlength="37" value="<?php echo $email; ?>" />
</div>
<div id="submit">
<input type="submit" name="Submit" value="Submit" />
</div>
</center>
</form>
</div>
<?php
}
?>
</body>
You are asking for $_POST['submit'] instead of $_POST['Submit']
So I have two forms that are hidden when submitted. The validation for the second form isn't working. Any clue as to why?
if(isset($_POST['submit'])){
$feet = $_POST['feet'];
$lname = $_POST['lname'];
if(!is_numeric($feet)){
$isValid = false;
$feetError = "Try again buddy";
}
echo "Hello Captain " . $lname . " Are you" . $feet ."ft tall?";
}
elseif(isset($_POST['submit2'])){
$feet2 = $_POST['feet2'];
$lname2 = $_POST['lname2'];
$isValid2 = true;
if(!is_numeric($feet2)){
$isValid2 = false;
$feetError2 = "Try again buddy";
}
echo "Hello Captain " . $lname2 . " Are you" . $feet2 ."ft tall?";
}
else{
?>
<form name="formie" id="formie" action="test1.php" method="post">
<p><label>square feet</label><input type="text" id="feet" name="feet"><span><?PHP echo $feetError; ?></span></p>
<p><label>Last Name</label><input type="text" id="lname" name="lname"></p>
<p><button type="submit" name="submit" id="submit">Submit</button></p>
</form>
<form name="formie2" id="formie2" action="test1.php" method="post">
<p><label>square feet</label><input type="text" id="feet2" name="feet2"><span><?PHP echo $feetError2; ?></span></p>
<p><label>Last Name</label><input type="text" id="lname2" name="lname2"></p>
<p><button type="submit" name="submit2" id="submit2">Submit</button></p>
</form>
<?PHP
}
?>
These are all place holders BTW. The project I'm working on is much much larger, I just want to understand the whole 'hiding forms' thing before I try to implement it on a larger scale.
Thank You guys!
$isSubmitted = false;
$isValid = true;
$isValid2 = true;
$feetError = '';
$feetError2 = '';
if(isset($_POST['submit'])){
$isSubmitted = true;
$feet = $_POST['feet'];
$lname = $_POST['lname'];
if(!is_numeric($feet)){
$isValid = false;
$feetError = "Try again buddy";
} else {
echo "Hello Captain " . $lname . " Are you" . $feet ."ft tall?";
}
}
elseif(isset($_POST['submit2'])){
$isSubmitted = true;
$feet2 = $_POST['feet2'];
$lname2 = $_POST['lname2'];
if(!is_numeric($feet2)){
$isValid2 = false;
$feetError2 = "Try again buddy";
} else {
echo "Hello Captain " . $lname2 . " Are you" . $feet2 ."ft tall?";
}
}
?>
<?php if(!$isSubmitted || !$isValid || !$isValid2) { ?>
<form name="formie" id="formie" action="test1.php" method="post">
<p><label>square feet</label><input type="text" id="feet" name="feet"><span><?PHP echo $feetError; ?></span></p>
<p><label>Last Name</label><input type="text" id="lname" name="lname"></p>
<p><button type="submit" name="submit" id="submit">Submit</button></p>
</form>
<form name="formie2" id="formie2" action="test1.php" method="post">
<p><label>square feet</label><input type="text" id="feet2" name="feet2"><span><?PHP echo $feetError2; ?></span></p>
<p><label>Last Name</label><input type="text" id="lname2" name="lname2"></p>
<p><button type="submit" name="submit2" id="submit2">Submit</button></p>
</form>
<?php } ?>
When you submit a form, the PHP reloads the page. When the page is reloaded, it is reloaded WITH the previous posted values of your form. Therefore it will always trigger your first condition assuming the user is submitting the first form first.
You have 2 solutions. Do separate script, or use another if, instead the if - else. I'd recommend separate script though.
I recommend separate script for each form, with a header redirecting to your website after, it's easier to remember and to order your work afterwards.
Hey guys I am trying to use a value that i got from a previous query in a new one, the value is a string stored in an array, they are the $Name and $Email variables, it looks like this when i var_dump them... string 'nathgold' (length=8) .... I want to use that nathgold as a value in the insert of a new query. I get the error Notice: Array to string conversion in C:\wamp\www\login\post.php on line 30
<?php
include_once('connect-db.php');
session_start();
if(!isset($_SESSION['isLogged']))
{
header("Location: home.php");
die();
}
if (!isset($_REQUEST['MBID'])) exit;
if (!isset($_REQUEST['Parent'])) {
$Parent = 0;
} else {
$Parent = $_REQUEST['Parent'];
}
if (isset($_POST['Title'])) {
$user_info=mysqli_query($connection, "SELECT * FROM usertest WHERE id=".$_SESSION['user']);
$userRow=mysqli_fetch_array($user_info);
$Name = $userRow=['username'];
$Email = $userRow=['email'];
$Title = mysqli_real_escape_string($connection, $_POST['Title']);
$Message = mysqli_real_escape_string($connection, $_POST['Message']);
$CurrentTime = time();
// other filtering here...
$result = mysqli_query($connection, "INSERT INTO mbmsgs (MBID, Parent, Poster, Email, Title, Message, DateSubmitted) VALUES ({$_REQUEST['MBID']}, $Parent, ".$Name.", ".$Email.", '$Title', '$Message', $CurrentTime);");
if ($result) {
echo "Your message has been posted - thanks!<br /><br />";
echo "Back to messageboard";
exit;
} else {
echo "There was a problem with your post - please try again.<br /><br />";
}
}
?>
<form method="post" action="post.php">
Message title: <input type"text" name="Title" /><br /><br />
Message:<BR />
<textarea name="Message" rows="10" cols="40"></textarea><br /><br />
<input type="hidden" name="MBID" value="<?php echo $_REQUEST['MBID']; ?>" />
<input type="hidden" name="Parent" value="<?php echo $Parent; ?>" />
<input type="submit" value="Post" />
</form>
You to convert $name on a string :
use implode("|",$name);
I have a script and it runs very well, but I want know how to echo an error div if recaptcha isn't confirmed. In this script if recaptcha wasn't confirmed the page will reload and nothing will be send to my mail, but I don't know how to display an error that tells the user: "You must verificate that you aren't a robot".
Can you help me?
CODE:
<?php
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"../support/style/contactform.css\">\n";
$emailpattern="^[^# ]+#[^# ]+\.[^# \.]+$";
if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo '<form method="post" id="contactformall">
<p>Nome</p>
<input type="text" name="name" class="contactformimput"/>
<p>Email (obbligatorio)</p>
<input type="text" name="email" class="contactformimput"/>
<p>Numero</p>
<input type="text" name="number" class="contactformimput"/>
<p>Messaggio (obbligatorio)</p>
<input type="text" name="message" onkeyup="adjust_textarea(this)" class="contactformimput" id="contactformtext">
<div class="g-recaptcha" data-sitekey="____key____"></div>
<div id="divcontactbutton">
<input type="reset" name="send" value="Resetta" class="button" id="resetmessage"/>
<input type="submit" name="send" value="Invia Messaggio" class="button" id="sendmessage"/>
</div>
</form>';
exit;
}
$responsejson=file_get_contents("google.com/recaptcha/api/…);
$response = json_decode($responsejson);
if($response->success==false) { echo "<div class=\"emailerror\" id=\"emailnoninviata\"><div><span>•</span> Email non inviata</div></div>";
**/////THIS part DON'T RUN**
}else
{
if (isset($_POST['send'])) {
if(!ereg($emailpattern,$_POST['email'])) {
$emailerror = true;
echo "<div class=\"emailerror\"><div><span>6</span> Email non valida</div></div>";
} if ($_POST['message'] == "") {
$emailerror = true;
echo "<div class=\"emailerror\"><div><span>6</span> Inserisci un messaggio</div></div>";
} elseif ($_POST['message'] != "" and ereg($emailpattern,$_POST['email'])){
$emailerror = false;
};
if ($emailerror == true) {
echo '<form method="post">
<p>Nome</p>
<input type="text" name="name" class="contactformimput"/>
<p>Email*</p>
<input type="text" name="email" class="contactformimput"/>
<p>Numero</p>
<input type="text" name="number" class="contactformimput"/>
<p>Messaggio*</p>
<input type="text" name="message" onkeyup="adjust_textarea(this)" class="contactformimput" id="contactformtext">
<div class="g-recaptcha" data-sitekey="___KEY___"></div>
<div id="divcontactbutton">
<input type="reset" name="send" value="Resetta" class="button" id="resetmessage"/>
<input type="submit" name="send" value="Invia Messaggio" class="button" id="sendmessage"/>
</div>
</form>';
}
if (isset($_POST['send']) and $emailerror == false) {
$to = "mail#gmail.com";
$subject = "B&B";
$user_name = 'Name: ' . $_POST['name'] . "\n";
$user_email = 'Email: ' . $_POST['email'] . "\n";
$user_ip = 'IP: ' . $_SERVER['REMOTE_ADDR'] . "\n";
$user_message = 'Message: ' . $_POST['message'];
$message = $user_name . $user_email . $user_ip . $user_message;
$success = mail($to, $subject, $message);
echo "<div class=\"emailerror\" id=\"emailinviata\"><div> <span>5</span> Email inviata correttamente</div></div>";}
}
}
?>
You are mixing javascript code with php code. Javascripts uses '.' to access class vars/functions, php uses '->'.
Please read this page in order to use Recaptcha with php: https://developers.google.com/recaptcha/old/docs/php
The recaptcha documentation shows that this API request should return JSON. You will need to decode the JSON response to refer to its contents. So do this after you use file_get_contents() to get the response:
$response = json_decode($response);
and then you should be able to check for success with a little adjustment to your syntax.
if($response->success==false)
here is my code. I am not sure why after i input the first and last name the second page does not show the proper text.. The form is suppose to take in first name and last name into a text box.. Then on the next page when person submits it should validate that the proper type of data was input, and then print out text if it was not, or print out text if it was successful.
<body>
<h2 style="text-align:center">Scholarship Form</h2>
<form name="scholarship" action="process_Scholarship.php" method="post">
<p>First Name:
<input type="text" name="fName" />
</p>
<p>Last Name:
<input type="text" name="lName" />
</p>
<p>
<input type="reset" value="Clear Form" />
<input type="submit" name="Submit" value="Send Form" />
</form>
my second form
<body>
<?php
$firstName = validateInput($_POST['fName'],"First name");
$lastName = validateInput($_POST['lName'],"Last name");
if ($errorCount>0)
echo <br>"Please use the \"Back\" button to re-enter the data.<br />\n";
else
echo "Thank you for fi lling out the scholarship form, " . $firstName . " " . $lastName . ".";
function displayRequired($fieldName)
{
echo "The field \"$fieldName\" is required.<br />n";
}
function validateInput($data, $fieldName)
{
global $errorCount;
if (empty($data))
{
displayRequired($fieldName);
++$errorCount;
$retval = "";
}
else
{
$retval = trim($data);
$retval = stripslashes($retval);
}
return($retval);
}
$errorCount = 0;
?>
</body>