In my website, it presents a list of program titles. When a title is clicked, it displays the content and an email form. The form just takes an email and mails the title as the subject and the content of the page in the email.
The link will pass a variable 'info'. 'info' contains the ID for the post in my database. The problem occurs when I click the submit button. It will not send an email, and refresh the page. This causes the url to loose the 'info' variable and loose all content on the page.
The page works perfectly if I hardcode the ID in the php and don't use $_GET['info'].
Is there something I am missing?
<?php
$id = $_GET['info'];
/*****************************************************
open conection to the mySQL database
******************************************************/
$configs = include('config.php');
//Create a connection
$con = mysqli_connect(
$configs['host'], //host
$configs['username'], //username
$configs['password'], //password
$configs['dbname'] //dbname
);
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
/*****************************************************
Populate the page
******************************************************/
$sql="
SELECT p.post_title, p.post_content
FROM they_posts AS p
WHERE p.ID='".$id."'
";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
/*Title*/
echo '<h1>'.$row['post_title'].'</h1><hr>';
/*content*/
echo '<h2>Details: </h2><br>'.$row['post_content'].'<br>';
$title= $row['post_title'];
$content = $row['post_content'];
/*****************************************************
E-mail Form
******************************************************/
include('includes/email_test.php');
}
?>
And this is the email_test.php
<div data-role="collapsible">
<h1>Send Reminder Email</h1>
<?php
function spamcheck($field)
{
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
// display form if user has not clicked submit
if (!isset($_POST["submit"]))
{
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
Your Email: <input type="text" name="to"><br>
<input type="submit" name="submit" value="Submit Feedback">
</form>
<?php
}
else // the user has submitted the form
{
// Check if the "from" input field is filled out
if (isset($_POST["to"]))
{
// Check if "from" email address is valid
$receivecheck = spamcheck($_POST["to"]);
if ($receivecheck==FALSE)
{
echo "Invalid input";
}
else
{
$to = $_POST["to"]; //receiver
$subject = $title;
$message = $content;
// message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// send mail
mail("$to",$subject,$message,"From: noreply#address.com\n");
echo "reminder has been sent";
}
}
}
?>
</div>
I have used isset($id) to display a back button for when submit is pressed. This will bring back the information but the email is still never sent.
In your scenario you must have info=post_id in your current url to get $_GET['info']
1st way:
Change your form action like this:
<form method="post" action="<?php echo $_SERVER["PHP_SELF"].'?info='.$_GET['info']; ?>">
then in action it will be :
/your_page.php?info=current_post_id
then in action page you can get info by $_GET['info']
2nd way:
or you can add extra hidden form field in your form for post_id like this:
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
Your Email: <input type="text" name="to"><br>
<input type="submit" name="submit" value="Submit Feedback">
<input type="hidden" name="post_id" value="<?php echo $_GET['info'];">
</form>
After that In your action page you can get post_id by $_POST['post_id']
It should make sense!
Thanks
$_GET['info'] will only work if your form is defined with method='GET'.
If your form is defined with method='POST' then you need to use $_POST['info'].
If you want your code to work no matter whether the form is using GET or POST, then use $_REQUEST['info'].
Related
I want my contact form input fields to save the user's inputs if there's an error, otherwise have them cleared if the email goes through. Right now it works except when the email is sent the fields are still filled in. I could refresh the page but then it doesn't show the 'Your email has been sent' message.
Here's my form:
<form class="contact-form" action="" method="post">
<input type="text" name="name" value="<?php if(isset($_POST["name"])) echo $_POST["name"]; ?>" />
</form>
I tried adding something to my php code that handles the email business - if the message was sent, unset($_POST["name"]), and also adding to this form input's php else echo ''; but that didn't seem to work. It seems the variable was still set.
Let's assume that your page is contact.php.
You php code should be something like this:
// we will keep here error message
$error = '';
// if request is get and isset sent
if ($_SERVER["REQUEST_METHOD"] === "GET" and isset($_GET["sent"]))
echo '<p id="output-area">Message has been sent.</p>';
else {
// if request is post
if ($_SERVER["REQUEST_METHOD"] === "POST") {
// then verify input data
if (!empty($_POST['msg'])) {
// if mail was sent, redirect to contact.php?sent
if (mail("someone#example.com", "My subject", $_POST['msg'])){
header('Location: contact.php?sent');
exit;
} else
$error = "Mail does not sent.";
} else
$error = 'Please fill in all inputs.';
}
}
if ($error != '')
echo '<p class="error">Error: ' . $error . '</p>';
// here goes your form
echo '<form class="contact-form" action="contact.php" method="post">
<textarea name="msg">' . (!empty($_POST["msg"]) ? $_POST["msg"] : '') . '</textarea>
<input type="submit" value="send">
</form>';
You should set error flag while error occurred. try this
$error=false;
if(isset($_POST['submit'])){
$msg = $_POST['msg'];
if(mail("someone#example.com","My subject",$msg)){
}else{
$error = "mail does not sent";
}
}
" />
I have this simple php code that generate a random code and display it to the user. I need to verify using a text input if the user insert the displayed code, like a captcha, but i will use this script to redirect the user after the verification,to the registration form page. The code is generated, but i can't verify it, maybe i've missed something in the code?
NB: This is not a spam prevention system. As said in the comments, there are valid solution better than this to prevent spam. This is a starting draft for an user invitation system, if you want to downvote the question please consider this.
<?php
function randomCode() {
$code_variable = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789";
srand((double)microtime() * 1000000);
$i = 0;
$rand_Code = '';
while ($i <= 7)
{
$num = rand() % 33;
$tmp = substr($code_variable, $num, 1);
$rand_Code = $rand_Code . $tmp;
$i++;
}
return $rand_Code;
}
$code = randomCode();
if(isset ($_POST['verify'])){
if($_POST['user_code'] == $code ){
echo 'Valid code.';
header('Location: index.php');
}
}
?>
<form method="post" action="">
<input type="text" name="verification_code" disabled value="<? echo $code;?>">
<input type="text" name="user_code">
<button type="submit" name="verify">Verify code</button>
</form>
You will never get Valid code. being displayed on the screen since every time user clicks on Verify code button, the page will refresh and a new random captcha code will get generated and stored in $code. So that's why $_POST['user_code'] will never be equal to $code.
One workaround would be to append the captcha code in the URL itself, so that you could verify the authenticity of user-inputted captcha by comparing it with $_GET[...] data. So you need to change your form in the following way,
<form method="post" action="?captcha=<?php echo $code; ?>">
<input type="text" name="verification_code" disabled value="<?php echo $code;?>">
<input type="text" name="user_code">
<button type="submit" name="verify">Verify code</button>
</form>
Subsequently, verify captcha in the following way,
// your code
if(isset ($_POST['verify'])){
if($_POST['user_code'] == $_GET['captcha'] ){
// your code
}
}
Sidenote(s):
Don't output anything before the header(...); statement, otherwise you would see headers already sent error. Go through this SO thread to get more info on this.
header(...); alone is not sufficient to redirect the user to a different page, use exit(); after header(...); statement.
I've added the php mail() function to send the invitation code to users. It's working fine, i've divided the code into two parts. the first one manage the user invitation code sending:
<form method="post" action="?invitation=<?php echo $code; ?>">
<label for="email">Email</label>
<input type="text" name="email">
<button type="submit" name="send_invitation">Send invitation code</button>
</form>
<?php
session_start();
ob_start();
if(isset($_POST['send_invitation'])){
function randomCode()
{
$code_variable = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789";
srand((double)microtime() * 1000000);
$i = 0;
$rand_Code = '';
while ($i <= 7)
{
$num = rand() % 33;
$tmp = substr($code_variable, $num, 1);
$rand_Code = $rand_Code . $tmp;
$i++;
}
return $rand_Code;
}
$_SESSION['code'] = randomCode();
$_SESSION['tmp_mail'] = $_POST['email'];
if(isset($_POST['verify'])){
$to = $_POST['email']; // this is your Email address
$from = "noreply#domain.com"; // this is the sender's Email address
$subject = "Affiliate invitation code";
$message = $_SESSION['code'] . " " . " is your invitation code.";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "Mail Sent. Thank you " . $first_name . ", we will contact you shortly.";
}
?>
The second part of the script is on another page and manage the check for the code matching between stored code into the $_SESSION['code'] variable and the user input
<?php
session_start();
ob_start();
function redirect(){
header('refresh:3; url=affiliate/index.php');
exit;
}
if(isset($_POST['verify'])){
if($_POST['user_code'] == $_SESSION['code']){
echo "Valid invitation code. You can now register using $_SESSION['tmp_mail'] email address.";
} else { echo "Wrong code. Please enter a valid code or request a new one."; }
?>
<form method="post" action="?invitation=<?php echo $code; ?>">
<label for="Code">Invitation Code</label>
<input type="text" name="user_code">
<button type="submit" name="verify">Send invitation code</button>
</form>
I am currently trying to make a HTML form page [main.html], which will take following input :
Name, Email, and Contact Number
when the data is submitted, it will go to PHP script [validate.php] where it will be validated. like whether the name contains any invalid character set or number etc.
if the validation fails, it should return error msg e.g "Data Validation Fails".
and if the validation is successful, PHP page should return the data to main.html where the received data needs to be displayed and user is asked to confirm it again.
Once the data is confirmed by the User, it will be send data to another PHP Script file [store.php] for storing in a text file [e.g. UserDb.txt].
I am very much new to PHP and HTML with no knowledge of JQuery. I can somehow prepare main.html and store.php but heavily confused for validate.php page.
Please tell me how can i send back the data from PHP page [validate.php] to HTML page [main.html] to ask for confimation ??
Please do not suggest solutions involving JQuery and AJAX.
There are lot of webpages for that which I can find on Internet, but i could not find any solution particularly for this case. I Hope it is possible to send data back to HTML Page from PHP Script.
Form action tag is there for that action. Lets see on an example. here we have our form main_form.php;
<form action="validation.php" method="post">
<h2>Form</h2>
<span class="error">* required field.</span>
Name:
<input name="name" type="text" value="">
<span class="error">* <?php echo $nameError;?></span>
E-mail:
<input name="email" type="text" value="">
<span class="error">* <?php echo $emailError;?></span>
Gender:
<input name="gender" type="radio" value="female">Female
<input name="gender" type="radio" value="male">Male
<span class="error">*<?php echo $genderError;?></span>
Website:
<input name="website" type="text" value="">
<span class="error"><?php echo $websiteError;?></span>
Comment:
<textarea cols="40" name="comment" rows="5">
</textarea>
<input name="submit" type="submit" value="Submit">
</form>
Now lets see how we validate on validation.php;
<?php
// Initialize variables to null.
$nameError ="";
$emailError ="";
$genderError ="";
$websiteError ="";
// On submitting form below function will execute.
if(isset($_POST['submit'])){
if (empty($_POST["name"])) {
$nameError = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameError = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailError = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid or not
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email)) {
$emailError = "Invalid email format";
}
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check address syntax is valid or not(this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website)) {
$websiteError = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderError = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//php code ends here
?>
If there is an error this script will return error to the our main_form.php.For errors use css to show them in red like below error.css;
.error{
color:red
}
TL;DR: Set form action to validation.php. Keep it simple.
To start and set a session variabl :
session_start(); //at top of page
$_SESSION['name_of_field'] = $_POST['name_of_field']; //do checks on the post data!
To use a session varible :
session_start(); //at top of page
$my_new_value = $_SESSION['name_of_field'];
you will get data in varible.
Or you can send data via URL
Write this in php
header('Location: http://yoursite.com/page2.php?name='.$name.'&email='.$email);
and get
$name = $_GET['name'];
$email = $_GET['email'];
You may also try
Rename your main.html to main.php then include validate.php above your form tag to display errors above form. Thus, your form action would be self or blank
<?php include "validate.php"; ?>
<form action ="" method ="post"... >
But if there are no errors, then from validate.php you can redirect to the index.php for user confirmation using
header('Location: index.php?name='.$name);
The value of name can be accessed using $_GET['name'];
Thanks in advance for your help. I am new to PHP. I have done a lot of learning to get to this point, but I am currently stuck.
I have a form with a 'fields-section' and a 'proof-section' that has 3 buttons - proof, edit and send. Initially, the 'fields-section' is displayed and the 'proof-section' is hidden. Of the 3 buttons, the 'proof' button is visible while the other 2 are not. After the form is completed and 'proof' is clicked, the fields are validated, some fields are transformed into Hebrew and a proof is presented to the user by hiding the 'fields-section' and showing the 'proof-section'. Here the 'edit' and 'send' buttons are available and the 'proof' button is hidden. I am integrating this form within a Wordpress page template.
I am finding that the PHP variables do not have any value and I don't understand why.
If I change echo htmlspecialchars($line1); to
if(isset($_POST['line1'])){
echo htmlspecialchars($_POST['line1']);
}
It works...but this solution doesn't work for $line1_hebrew because this is a calculated field. I deleted unnecessary code below to keep it short.
Below is my code from the Wordpress template:
<?php
include "hebrew-memorial-creator.php";
add_action( 'genesis_after_loop', 'em_form');
/**
* Output the form to the page
*
*/
function em_form() {
?>
<div id="hebrew-memorial-creator">
<form name="hebrewMemorialForm" action="" method="POST">
<div id="field_section">
<div>
<label for="line1">Line 1: </label><input type="text" name="line1" id="line1" value="<? echo htmlspecialchars($line1);?>" size="50" maxlength=40 />
<input type="hidden" name="line1_hebrew" id="line1_hebrew" value="<?php htmlspecialchars($line1_hebrew);?>" />
</div>
.... deleted some fields here
</div><!--field-section-->
<input type="submit" id="proof_button" name= "proof_button" value="PROOF">
<input type="submit" id="edit_button" name="edit_button" value="EDIT">
<input type="submit" id="submit_button" name="submit_button" value="SEND">
<div id="proof_section">
<?php echo htmlspecialchars($proof);?>
</div><!--proof-section-->
</form>
</div><!--hebrew-memorial-creator-->
<?php
} // end function em_form
genesis();
?>
Below is my code from hebrew-memorial-creator.php:
<?php
if (isset($_POST['line1'])) { $line1 = $_POST['line1']; }
... deleted code for other fields...
if(isset($_POST['proof_button'])) {
$formerrors = false;
// validate fields
// email address is required
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo 'email error';
$emailErr = 'Please enter a valid email address';
$formerrors = true;
}
if (! ($formerrors)) {
// for line1 - line4, create line1_hebrew - line4_hebrew - converting lowercase letters to Hebrew characters
// and write to hidden form fields
$line1_hebrew = convert($line1);
... deleted code for additional fields
// all fields validated
// show proof fields and submit/proof buttons
$proof = '<div class="bronze"><p style="font-size: 36px; text-align:center;">HERE IS YOUR PROOF :</p>';
$proof .= '<p>Line1: ' . htmlspecialchars($line1) . ' ==> ' . htmlspecialchars($line1_hebrew) . '</p>';
... deleted code for other fields
$proof .= '</div>';
$proof .= "<script>
$('#field_section').hide();
$('#proof_section').show();
$('#proof_button').hide();
$('#edit_button').show();
$('#submit_button').show();
$('html,body').scrollTop(0);
</script>";
` // curious if anyone has a better solution to hiding/showing field`
} // end if no errors
return;
} // end proof button pressed
if (isset($_POST['submit_button'])) {
....deleted formatting of mail variables
mail( $to, $subject, $message, $headers );
wp_redirect( get_site_url() . '/thank-you');
} // end send button pressed
// replacing any lowercase characters with their hebrew character equivalent
function convert($line) {
if (($line == '') || ($line == ' ')) {
return $line;
}
$newLine = "";
for ($i=0; $i < strlen($line); $i++) {
//$character = substr($line, $i, 1);
$character = $line[$i];
... deleted code
} // end for
return $newLine;
} // end function convert
?>
In this program when i am clicking submit button the page directly goes on other page 2222.php. The error message not pop up.. I just want hit error message when clicking on submit button...
php_validation.php
<?php
// Initialize variables to null.
$nameError ="";
$emailError ="";
$genderError ="";
$name = $email = $gender ="";
// On submitting form below function will execute.
if(isset($_POST['submit']))
{
if (empty($_POST["name"])) //---------------------------------------------- -------------------------
{
$nameError = "Name is required";
}
else
{
$name = test_input($_POST["name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameError = "Only letters and white space allowed";
}
//-----------------------------------------------------------------------
}
if (empty($_POST["email"])) //---------------------------------------------- -------------------------
{
$emailError = "Email is required";
}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid or not
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailError = "Invalid email format";
}
}
//-----------------------------------------------------------------------
if (empty($_POST["gender"]))
{
$genderError = "Gender is required";
}
else
{
$gender = test_input($_POST["gender"]);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" name="myForm" action="2222.php">
<p>First Name:
<input type="text" name="fname" id="fname" />
<span class="error">* <?php echo $nameError;?></span>
</p>
<br><br>
<p>
Email:
<input type="text" name="email" id="email">
<span class="error">* <?php echo $emailError;?></span>
</p>
<br><br>
<p>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">*<?php echo $genderError;?></span><br><br />
</p>
<input class="submit" type="submit" name="submit" value="Submit" >
</form>
</body>
2222.php
<?php
$name = $_POST['fname'];
$email = $_POST['email'];
$radio = $_POST['gender'];
echo "<h2>Your Input:</h2>";
echo "user name is: ".$name;
echo "<br>";
echo "user email is: ".$email;
echo "<br>";
echo "user is ".$radio;
?>
So I've done a quick code for you :
Here is your "php_validation.php" :
<?php
//Init error var
$nameError = '';
$emailError = '';
$genderError = '';
//Did we have an error ?
if(isset($_GET['error'])){
//Split error return into an array
$errorList = explode('_', $_GET['error']);
//Verify every possible error
if(in_array('name',$errorList)){
$nameError = 'Please enter your name<br>';
}
if(in_array('email',$errorList)){
$emailError = 'Please enter your email<br>';
}
if(in_array('gender',$errorList)){
$genderError = 'Please enter your gender';
}
}
?>
I didnt changed the form
Then this is your "2222.php" :
<?php
$error ='';
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//When we receive data
if(isset($_POST)){
//Verify all possible data and set error
if(!empty($_POST['fname'])){
$name = test_input($_POST['fname']);
}else{
$error .= 'name_';
}
if(!empty($_POST['email'])){
$email = test_input($_POST['email']);
}else{
$error .= 'email_';
}
if(!empty($_POST['gender'])){
$radio = test_input($_POST['gender']);
}else{
$error .= 'gender_';
}
//if we have an error then redirect to form with error
if(!empty($error)){
header("Location:php_validation.php?error=".$error);
}
}
?>
Didnt changed your output on this page either.
So as I said previously when you here is what happend when you click the submit button :
Submit Click
Form sent to 2222.php as $_POST and you're redirected to this page
There is no way that could be working if your form is posting on an other page than the one where the check is made.
Since your form's action is "2222.php", on click the submit button will automatically redirect you to 2222.php before doing anything.
If you want to check what you've received by your form, you can do it in your "2222.php", then redirect it with the error message to php_validation.php
You could do one of the following things:
Do all the checking in Javascript "onClick" function
Do Ajax call "onClick" to a handler page, get the validation message from that page.
Do the validation on "2222.php" page
action back to the same page (since you are doing some validation here) and redirect after validation on "2222.php" page
Now depends only on you which fits your program.
If you want to stay on the same page you could submit the form to an iframe, as the results of the processing script would be displayed in the iframe itself.
Example:
files:
file-with-form.php
form-submit-processing-file.php
Code examples:
file-with-form.php
<!DOCTYPE html>
<html>
<head>
<title>[Your page title]</title>
</head>
<body>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<!-- Form -->
<form action="[path-to-form-submit-process]" method="[GET|POST]"
target="form-processor">
<div>
<label>First Name:
<input type="text" name="fname" id="fname" />
<span class="error">* <?php echo $nameError ?></span>
</label>
</div>
<div>
<label>Email:
<input type="text" name="email" id="email">
<span class="error">* <?php echo $emailError ?></span>
</label>
</div>
<div>
<label>Gender:
<p><input type="radio" name="gender" value="female"> Female</p>
<p><input type="radio" name="gender" value="male"> Male</p>
<p><span class="error">*<?php echo $genderError ?></span></p>
</label>
<input class="submit" type="submit" name="submit" value="Submit" >
</div>
</form>
<!-- The iframe to submit the form to -->
<iframe name="form-processor" id="form-processor"
src="[path-to-form-submit-process]"></iframe>
<!--
NOTE: The error message spans are left there just because you had them
in your code, those will not work here at this point, actually depending
on your php configuration will most probably throw errors/warnings,
because such variables were not defined at all...
-->
</body>
</html>
As:
[path-to-form-submit-process] - a placeholder to be replaced with the URL to the file/ Controller -> Action that would process the passed form data
[*] - placeholders that should be replaced with the values for your case
form-submit-processing-file.php
<?php
# Processing the form fields and displaying the messages
$post = $_POST;
# Preprocessing the passed data
// Here you would filter out data from the $_POST superglobal variable
# Validating the passed data
// Check if the data entries, e.g.
// Flag for error risen - does not let the process to be completed
$invalidFormData = false;
$messages = [];
function addErrorMessage($message, &$messages, &$errorFlag)
{
$errorFlag = true;
$errorMessageTemplate = '<p class="error-message">{message}</p>';
array_push($messages, str_replace('{message}', $message,
$errorMessageTemplate));
}
// Validating the email
$email = array_key_exists('email', $post)
? $post['email']
: null;
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
// Raising the flag for an error on validation
addErrorMessage("$email is not a valid email address", $messages, $invalidFormData);
}
// ........
// validation of rest of fields
// ........
$internalError = false;
# Some business logic after the validation, recording more messages etc.
try {
// ........
} catch (Exception $e) {
$internalError = true;
}
# Stop execution on internal error
if ($internalError === true)
{
?>
<h2>Sorry, there's an error on our side... we'll do all in our
powers to fix it right away!</h2>
<?php
exit;
}
# Displaying the results
if ($invalidFormData === true) {
// Building errors message
$messagesHeading = '<h2>There were problems submitting your data. :/</h2>';
} else {
$messagesHeading = '<h2>Your data was successfully submitted! Yay!</h2>';
}
// Placing the heading in front of other messages
array_unshift($messages, $messagesHeading);
// Displaying the messages:
echo implode('', $messages);
However I believe this should be done via an AJAX call insted.
Also there are a lot of bad practices in this case, so I would suggest checking out some design patterns and architectures as MVC for instance and consider using a framework like Symfony/Laravel/CodeIgniter... There are a lot of tools that will make your life easier :)