Getting PHP variable to display in HTML Div - php

Trying to get the error messages of $missing to appear in the form div with id error, and if the form is filled out correctly display the $complete message into div with id success.
<?php
$error = false;
$missing = "";
if ($_POST) {
$complete = "<p><strong>Thank you!</strong> Your message was sent,
we'll get back to you ASAP!</p>";
if (filter_var($_POST["email"], FILTER_VALIDATE_EMAIL) === false {
$missing .= "A vaild email address is required.<br>";
$error = true;
}
if (!$_POST['subject']) {
$missing .= "A subject field is required.<br>";
$error = true;
}
if (!$_POST['content']) {
$missing .= "A content field is required.<br>";
$error = true;
}
if ($error) {
$missing = "<p>". $missing."</p>";
} else {
$complete;
}
}
?>
This is the HTML form where trying to display.
<form method="post">
<h1>Get in touch!</h1>
<div id="error" class="alert alert-danger" role="alert">
<? echo $missing; ?></div>
<div id="success" class="alert alert-success" role="alert"><? echo $complete; ?></div>
Can't really see where i'm going wrong here, any help would be amazing. Thanks.

<? does not mean anything in PHP (unless you have enabled short open tags in your php.ini file). It's usage is discouraged, as it can be disabled - maybe this is what happened here.
There are two other starting tags for PHP, <?php and <?= (the latter of which is only for echoing, and the one that I suspect you want to use).
Try replacing <? echo $missing; ?> with <?=$missing?>, and <? echo $complete; ?> with <?=$complete?>.
Also, you are never setting $complete to contain any value, and there are scenarios when it will not be defined at all, which will cause an error.
You should define it to be empty at the top of your PHP code (like you do with $missing), and then in your else statement assign some value to it, i.e. $complete = "Success!".

See comments in code.
<?php
$error = false;
$missing = "";
if ($_POST) {
$complete = "<p><strong>Thank you!</strong> Your message was sent, we'll get back to you ASAP!</p>";
if (filter_var($_POST["email"], FILTER_VALIDATE_EMAIL) === false ) { // There was a missing parenthesis here.
$missing .= "A vaild email address is required.<br>";
$error = true;
}
if ($_POST['subject']=="") { // Check if empty, not if exist... It may exist as empty.
$missing .= "A subject field is required.<br>";
$error = true;
}
if ($_POST['content']=="") {
$missing .= "A content field is required.<br>";
$error = true;
}
if ($error) {
$missing = "<p>". $missing."</p>";
$complete = ""; // Remove the success string here.
}
}
?>

I think it should not be (because when you submit the form it always post so you have to check whether it is blank or not)
if (!$_POST['subject'])
&& if(!$_POST['content'])
( -it means if data is not posted)
It should be
if($_POST['subject']=='')
if($_POST['content']=='')'
( - it means if data is blank)
And in the HTML page
you should use
<?php echo $missing; ?> or <?=$missing;?>
<?php echo $complete; ?> or <?=$complete;?>

Without seeing your form, it's hard to address anything there, but as you have it, it would be better to do a bit of a rework. You don't need the $error marker and you should store the errors in an array. If the array has a count greater than one at the end, then there is an obvious error. You should also remove empty spaces in the post values first before you determine if, in fact, the value is empty:
<?php
# Make a function to remove spaces in the array. If the user types two empty
# spaces, it's considered not empty, so this will remove that and only leave
# actual string content (or empty).
function trimArray($array)
{
# Trim the value of empty spaces
if(!is_array($array))
# Send back since not an array
return trim($array);
# Loop through array and apply this same function
foreach($array as $key => $value) {
$array[$key] = trimArray($value);
}
# Return this array
return $array;
}
# Store your errors in an array
$missing = array();
# Check if the post is empty or not
if(!empty($_POST)){
# Remove empty spaces from values in the post
$POST = trimArray($_POST);
# Check email
if(!filter_var($POST["email"], FILTER_VALIDATE_EMAIL))
$missing[] = "A vaild email address is required.";
# Check if subject set
if(empty($POST['subject']))
$missing[] = "A subject field is required.";
# Check if content
if(empty($POST['content']))
$missing[] = "A content field is required.";
if(empty($missing)) {
# Send mail here
# Also check that it was successful...
}
}
?>
<!-- You only need one div that has a ternary condition. Set the class and message value -->
<!-- based on whether the $message array is empty or not -->
<form method="post" action="#">
<h1>Get in touch!</h1>
<?php
# You have no neutral condition so if there is no post, then it will
# still come back as saying it's successful.
# But that doesn't make any sense if no post was sent....
if(isset($_POST['email'])) { ?>
<div id="error" class="alert alert-<?php echo (!empty($missing))? 'danger' : 'success' ?>" role="alert">
<p><?php echo (!empty($missing))? implode('<br />',$missing) : "<strong>Thank you!</strong> Your message was sent, we'll get back to you ASAP!" ?></p>
</div>
<?php } ?>

Related

Setting General Messages Using Flash Message

I have a simple register form, my form validates but will not show error messages or validation messages
This is my form function
function validate_new_user()
{
$errors = [];
if (isset($_POST['register'])) {
$email = $_POST['email'];
$name = str_replace(" ", "", $_POST['username']);
$password = $_POST['password'];
if (empty($email)) {
$errors[] = "Email Address is required";
}
if (empty($name)) {
$errors[] = "Username is required";
}
if (strlen($password) < 5) {
$errors[] = "Password must be at least 6 characters long";
}
if (!empty($errors)) {
set_message($errors[0], WARNING);
} else if (create_new_user($email, $name, $password)) {
set_message('Please check your email for user Information.', SUCCESS);
redirect_to_url("/user/login");
}
}
}
I call my validation function in my form page
<?php validate_new_user(); ?>
so if there is an error it should set message but don't.
now if it successfully it redirects to login and sets a flash message also and I call it with
<?php display_message(); ?>
That don't display a message either
Flash message code
define('SUCCESS', 'success');
define('INFO', 'info');
define('WARNING', 'warning');
function set_message($message, $type = 'success')
{
if (!empty($_SESSION['flash_notifications'])) {
$_SESSION['flash_notifications'] = [];
}
$_SESSION['flash_notifications'][] =
$message = [
'<div class="alert . $type .">$message</div>'
];
}
function display_message()
{
if (isset($_SESSION['flash_notifications'])){
return $_SESSION['flash_notifications'];
}
}
my goal is to use one set message for all notifications with styles but I cannot get none of the messages to display
I’ll assume you’re calling session_start() at the beginning of the script.
Your usage of functions makes the problem much easier to diagnose! Sometimes, though, it helps to have a different set of eyes look at it.
Your function set_message() has a couple of errors:
The initialization of $_SESSION['flash_notifications'] should occur if it is empty, but instead you are initializing if it is not empty. Hence nothing can be added
Malformed assignment. When you are building the message array to save in $_SESSION, there is no need to reassign $message. Also, usage of single quotes does not interpret variables within the quotes, so the html snippet is not what you expect.
Corrected function:
function set_message($message, $type = 'success')
{
if (empty($_SESSION['flash_notifications'])) {
$_SESSION['flash_notifications'] = [];
}
$_SESSION['flash_notifications'][] = '<div class="alert '. $type .'">'.$message.'</div>';
}
Note, it might be more understandable to write it this way:
$_SESSION['flash_notifications'][] = <<<FLASH
<div class="alert $type'">$message</div>
FLASH;
Your function display_message() is almost correct as is, except you’re returning an array, not a string. If you’re going to print it, it must be converted into a string:
function display_message()
{
if (isset($_SESSION['flash_notifications'])){
return join('',$_SESSION['flash_notifications']);
}
}
Then when you call it in your html, use the short print tag instead of the regular <?php tag:
<!— somewhere in your view (html output) —>
<?= display_message() ?>
<!— continue html —>

quicker way to set variable on page, instead of having in each if statement

I have a fairly straight-forward validation system on my registration page within my website. It all works fine, however, it seems unnecessarily messy; with always checking if a variable ($regOpen) is true, and then setting a variable ($errors) to true each time there is an error.
This is the very simplified script and relative HTML:
<?php
$regOpen = false;
$errors = false;
if(Input::is("register")){ // if a user has clicked register
$regOpen = true;
}
if($regOpen){ // checking if input is set first time
if(Input::empty("email")){
echo '<span>Your email address must not be left blank.</span>';
$errors = true; // setting to true for the first time
}
if($email->exists()){
echo '<span>A user with that email already exists.</span>';
$errors = true; // 2nd
}
if(!filter_var(Input::get("email"), FILTER_VALIDATE_EMAIL)){
echo '<span>That is not a valid email type.</span>';
$errors = true; // 3rd
}
}
?>
<input type="text" name="email">
<?php
if($regOpen){ // 2nd
if(Input::empty("password")){
echo '<span>Your password must not be left blank.</span>';
$errors = true; // 4th
}
if(strlen(Input::get("password")) < 4){
echo '<span>Your password must be a minimum of 4 characters.</span>';
$errors = true; // 5th
}
}
?>
<input type="password" name="password">
<?php
if($errors){ // if there are errors
echo '<span>Registration failed.</span>';
} else {
// register user
echo '<span>Registration successful.</span>;
}
?>
In reality, I actually have about several fields I need to check (each with their own list of errors to check), so as you can imagine; checking and setting all these variables seems a bit tedious and unnecessary.
What I want to know is, if there is a way to only have to set the $errors variable to true, once. Not only that, if there is a way to reduce the way I check if $regOpen is true (instead of checking each time I need to check for errors).
Thanks.
You could use $errors as an array for errors instead of being just an indicator. Then you could check if $errors array is not empty, then it contains errors.
Here's a clearer version of your code:
<?php
function print_errors($errors) {
foreach($errors as $error) {
echo '<span>' . $error . '</span>';
}
}
$regOpen = Input::is("register");
$errors = [];
if($regOpen){ // checking if input is set first time
if(Input::empty("email")){
$errors['email'][] = "Your email address must not be left blank.";
}
if($email->exists()){
$errors['email'][] = "A user with that email already exists.";
}
if(!filter_var(Input::get("email"), FILTER_VALIDATE_EMAIL)){
$errors['email'][] = "That is not a valid email type.";
}
if(Input::empty("password")){
$errors['password'][] = "Your password must not be left blank.";
}
if(strlen(Input::get("password")) < 4){
$errors['password'][] = "Your password must be a minimum of 4 characters.";
}
}
?>
<?php isset($errors['email']) ? print_errors($errors['email']) : null; ?>
<input type="text" name="email">
<?php isset($errors['password']) ? print_errors($errors['password']) : null; ?>
<input type="password" name="password">
<?php
if(count($errors) > 0){ // if there are errors
echo '<span>Registration failed.</span>';
} else {
// register user
echo '<span>Registration successful.</span>';
}
?>
You may now get the idea.
First of all, many of the checking are not necessary at PHP level, you can use the HTML 5 form validation for many cases. Secondly, for a few case that HTML5 form validation can't handle, you don't need to purposely set $errors=true, you could do something like $error=$email->exists();.

Validating simple RSVP form through PHP

I am trying to validate my RSVP form using only PHP. The user should receive an error message when the form is incomplete. I am trying to avoid the use of jQuery.
I am using this tutorial:
http://premium.wpmudev.org/blog/how-to-build-your-own-wordpress-contact-form-and-why/
The form is functioning fine but I haven't been able to get the error messages to display at all. I am using Wordpress and I want the form to appear at the footer of every page; not sure if this complicates matters. Here is my code:
<?php
$response = "";
//function to generate response
function my_contact_form_generate_response($type, $message) {
global $response;
if ($type == "success") {
$response = "<div class='success'>{$message}</div>";
} else {
$response = "<div class='error'>{$message}</div>";
}
}
//response messages
$missing_content = "Please supply all information.";
$email_invalid = "Email Address Invalid.";
$message_unsent = "Message was not sent. Try Again.";
$message_sent = "Thanks! Your message has been sent.";
//variables defined for messages
$email = $_POST["rsvp_email"];
$name = $_POST["rsvp_name"];
$attend = $_POST["rsvp_attend"];
$number = $_POST["rsvp_number"];
//variables defined for message to admin
$to = get_option('admin_email'); //sending to wordpress admin email
$subject = "Just Kidding You Foo";
$headers = "From: $email\n";
$message = "$name $attend.\n RSVPs $number of people";
//conditional statements used for form validation
//validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
my_contact_form_generate_response("error", $email_invalid);
} else { //email is valid
//validate presence of name and message
if(empty($name) || empty($attend) || empty($number)) {
my_contact_form_generate_response("error", $missing_content);
} else { //ready to go!
$sent = wp_mail($to,$subject,$message,$headers);
if($sent) {
my_contact_form_generate_response("success", $message_sent); //message sent!
} else {
my_contact_form_generate_response("error", $message_unsent); //message wasn't sent
}
}
}
?>
<div id="page-rsvp">
<h1>RSVP</h1>
<div id="respond">
<?php echo $response; ?>
<form action="<?php the_permalink(); ?>" method="post">
<!--Name here-->
<div class="rsvp-full"><label for="rsvp_name"><input type="text" name="rsvp_name" value="Your name"></label></div>
<div class="rsvp-full"><label for="rsvp_email"><input type="text" name="rsvp_email" value="Your email"></label></div>
<!--status of attendance-->
<div class="rsvp-full">
<div class="rsvp-element"><input id="radio-button" type="radio" name="rsvp_attend" value="accepts">Accepts</div>
<div class="rsvp-element"><input id="radio-button" type="radio" name="rsvp_attend" value="declines">Declines</div>
</div>
<!--number of guests attending-->
<div class="rsvp-full"><input type="number" name="rsvp_number" min="1" max="5">Total number of guests attending</div>
<div id="submit-button" class="rsvp-full"><input id="submit-button" type="submit"></div>
</form>
</div>
</div>
TIA!!!
I'm not that familiar with WP, but if I understand correctly, I believe you're trying to ensure all the fields are filled out.
Check your brackets! You need to be sure your curly brackets are opening and closing where you want them to. Otherwise the output of the page won't display. I write in all my braces because I'm not smart enough to be sure I know where they start and stop. I've taken the liberty of editing them into your question. I believe there was one missing at the end.
Once I fixed the brackets and removed functions my computer didn't have, it worked fine.
Tip 0: Try turning error reporting on for this script - error_reporting(E_ALL); at the top of this script. I always do for development.
Tip 1: use the placeholder attribute instead of value for things like "your name".
Tip 2: make sure the $_POST vars are set. I would do this by checking if they're set and then setting them to '' if they aren't; something like this:
//variables defined for messages
// you could do it like this:
if (isset($_POST["rsvp_email"])) {
$email = $_POST["rsvp_email"];
} else {
$email = '';
}
// or like this:
$name = '';
if (isset($_POST["rsvp_name"])) {
$name = $_POST["rsvp_name"];
}
// or even using a ternary operator:
$attend = isset($_POST["rsvp_attend"]) ? $_POST["rsvp_attend"] : '';
//but this will trigger a "Notice" error if the post var isn't set.
$number = $_POST["rsvp_number"];

Processing Contact Form

I am adding a contact page to my website, but having issues with the comment text box. When the user enters invalid information into the name and email text field, the website redirects the user back to the contact page to fill out the correct information. However, I want the comment box to be optional for the user. For example, the user will enter their name and email, but doesn't have any comments. The code should then process the information. Currently, my code will redirect the user back to the contact page because the user did not enter any information into the comment box. Any suggestions on how to fix this error?
Thanks!
if (empty($_REQUEST['comment'])) {
$error = TRUE;
} else {
$comment = $_REQUEST['comment'];
$form['comment'] = $comment;
if (!preg_match("/^.{0,50}$/", $comment)) {
$error = TRUE;
$messages['comment'] = "<p class='errorMessage'> You have entered invalid information.</p>";
} else {
$_SESSION['comment'] = $comment;
}
}
If you want to allow the content box to be empty, just let an empty value be an acceptable value. This means only running your validation against that field if there is a value present. This means removing your if/else statement since empty($_REQUEST['comment']) is no longer a valid check.
if (!empty($comment) && !preg_match("/^.{0,50}$/", $comment)) {
I just added !empty($comment) && to your check which basically says, "if there is a value go ahead and validate it".
One thing you should also do if you use this code is trim whitespace from your comment box values. Otherwise a user could type a space character and that would not be considered empty:
$comment = trim($_REQUEST['comment']);
Final code:
$comment = trim($_REQUEST['comment']);
$form['comment'] = $comment; // I am assuming this is used elsewhere
if (!empty($comment) && !preg_match("/^.{0,50}$/", $comment)) {
$error = TRUE;
$messages['comment'] = "<p class='errorMessage'> You have entered invalid information.</p>";
} else {
$_SESSION['comment'] = $comment;
}

Printing a PHP error inline instead of erasing the entire page

How can I make PHP print an error inline instead of changing the entire page?
I'd like it to target #errors and fill that instead of changing everything.
The code I'm currently using is die ("Incorrect username or password.");
I'm very new to PHP so sorry if this is a pretty easy thing to do.
Put the error in a variable where you do your logic and print its contents in #errors. For example:
if (username_is_incorrect()) $error = 'Incorrect username or password.';
And in the HTML
<?php if (isset($error)):?><div id="errors"><?=$error?></div><?php endif;?>
There are 2 ways of doing it.
A real inline method is not entirely PHP-based, as it cannot be used without JavaScript and AJAX calls.
Note the irritating disadvantage of this method: you will need to re-check every field again upon receiving form data finally.
Another one will reload your page but it will be the same page with all the form fields, entered data and also freshly generated error messages. This is called POST/Redirect/GET pattern
here is a short example
<?
if ($_SERVER['REQUEST_METHOD']=='POST') {
$err = array();
//performing all validations and raising corresponding errors
if (empty($_POST['name']) $err[] = "Username field is required";
if (empty($_POST['text']) $err[] = "Comments field is required";
if (!$err) {
// if no errors - saving data
// and then redirect:
header("Location: ".$_SERVER['PHP_SELF']);
exit;
} else {
// all field values should be escaped according to HTML standard
foreach ($_POST as $key => $val) {
$form[$key] = htmlspecialchars($val);
}
} else {
$form['name'] = $form['comments'] = '';
}
include 'form.tpl.php';
?>
while in the form.tpl.php file you have your form fields, entered values and conditional output of error messages
<? if ($err): ?>
<? foreach($err as $e): ?>
<div class="err"><?=$e?></div>
<? endforeach ?>
<? endif ?>
<form>
<input type="text" name="name" value="<?=$form['name']?>">
<textarea name="comments"><?=$form['comments']?></textarea>
<input type="submit">
</form>

Categories