Setting General Messages Using Flash Message - php

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 —>

Related

Getting PHP variable to display in HTML Div

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 } ?>

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();.

Multiple IF statements in simple form validation

I am a newbie and trying to implement a simple validation script after reading up, but I can't see how I can have multiple Ifs that will only do an sql insert if all required fields are met. Rather than having the multiple else statements, what is a syntax approach for having all the form validation Ifs together and if one of them fails, then the correct error is shown and the sql is not execute?
if(isset($_POST ['submit'])){
$user_ID = get_current_user_id();
$catErr = $ratingErr = $titleErr = $textErr = "";
if (empty($_POST["category"])) {
$catErr = "Category is required";
} else {
//DO THE INSERT BELOW!
}
if (empty($_POST["rating"])) {
$ratingErr = "Rating is required";
} else {
//DO THE INSERT BELOW!
}
if (empty($_POST["post_name"])) {
$postErr = "Title is required";
} else {
//DO THE INSERT BELOW!
}
if (empty($_POST["text"])) {
$textErr = "Text is required";
} else {
//DO THE INSERT BELOW!
}
//PDO query begins here...
$sql = "INSERT INTO forum(ID,
category,
rating,
post_name,
text
Use one variable for all the error messages and concatenate to it in the branches, so in the end if that variable is still empty string you won't do the insert. (And you don't need any of the empty else blocks that contain nothing but a comment.)
$err = "";
if (empty($_POST["category"])) {
$err .= "<br/>Category is required";
}
if (empty($_POST["rating"])) {
$err .= "<br/>Rating is required";
}
if (empty($_POST["post_name"])) {
$err .= "<br/>Title is required";
}
if (empty($_POST["text"])) {
$err .= "<br/>Text is required";
}
//PDO query begins here...
if($err=='')
{
$sql = "INSERT INTO forum(ID,
category,
rating,
...";
...
}
There are many solutions to your problem. Here are 3 methods of solving your issue.
You could combine all of your if statements like so:
if (empty($_POST['rating']) || empty($_POST'rating']) || ... ) { ... }
and separate them by double pipes.
You could also check the entire array:
if (empty($_POST)) $error = "There was an error!";
You could set a universal error variable and then output it.
A third solution could keep your current syntax but cut down on the amount of lines. You could save lines by doing without brackets. You can create an array and push your errors to the array.
Note: You can use empty() or isset().
// create an array to push errors to
$errors_array = array();
// if a particular field is empty then push the relevant error to the array
if(!isset($_POST['category'])) array_push($errors_array, "Category is required");
if(!isset($_POST['rating'])) array_push($errors_array, "Rating is required");
...
Once you have an array full of errors you can check for them like so:
// if the array is not empty (then there are errors! don't insert!)
if (count($errors_array) > 0) {
// loop through and echo out the errors to the page
for ($i = 0; $i < count($errors_array); $i++) {
echo $errors_array[i];
}
} else {
// success! run your query!
}
You should use javascript to validate the page before it is even processed into a post. This script will run client-side when they hit submit and catch errors before they even leave the page.
Here's a tutorial on how to do something like that: tutorial
Each field can have its own validation parameters and methods, and it will also make the page's code look a lot nicer.
I got it to go with this approach after showdev got me thinking that way. It's not very elegant perhaps, but does the trick, although all the user is taken to a blank page if there are errors and it simple says: Missing category (or whatever). Wondering if I can echo a link or something back to the page with the form from there so the user has an option like "go back and resubmit". Otherwise I will have to handle and display the errors alongside the form which will require a different approach altogether...
if(isset($_POST ['submit'])){
$errors = false;
if(empty($_POST['category'])) {
echo 'Missing category.<br>';
$errors = true;
}
if(empty($_POST['rating'])) {
echo 'Missing rating.<br>';
$errors = true;
}
if(empty($_POST['post_name'])) {
echo 'Missing title.<br>';
$errors = true;
}
if(empty($_POST['text'])) {
echo 'Missing text.<br>';
$errors = true;
}
if($errors) {
exit;
}
// THEN ADD CODE HERE. But how display form again if user makes errors and sees nothing but error message on page if they miss something (which is how it works now)
Generally, if you find yourself repeatedly writing very similar statements, using some sort of loop is probably a better way to go about it. I think what you said about "handling and displaying the errors alongside the form" is really what you need to do if you want the process to be user-friendly. If you put your validation script at the top of the file that has your form in it, then you can just have the form submit to itself (action=""). If the submission is successful, you can redirect the user elsewhere, and if not, they will see the form again, with error messages in useful places.
if (isset($_POST['submit'])) {
// define your required fields and create an array to hold errors
$required = array('category', 'rating', 'post_name', 'text');
$errors = array();
// loop over the required fields array and verify their non-emptiness
foreach ($required as $field) {
// Use empty rather than isset here. isset only checks that the
// variable exists and is not null, so blank entries can pass.
if (empty($_POST[$field])) {
$errors[$field] = "$field is required";
}
}
if (empty($errors)) {
// insert the record; redirect to a success page (or wherever)
}
}
// Display the form, showing errors from the $errors array next to the
// corresponding inputs

Send a POST value only with PHP

I want to use my webpage to recognize if a $_POST is set and the, if it is, print it in the page, so this is what I really have now:
if (isset($_POST['error'])) {
echo '<div id="error">'.$_POST['error'].'</div>';
}
But what I want is that, when an if statement that I have in the same document returns true, to send a POST request to that same file and so, show the error message with the $_POST. Is this possible or it is another easy way for doing it?
Sorry for not explaining so well, this is my code:
if (password_verify($_POST['oldpassword'], $result['password'])) {
// Upload password to database
} else {
// Set the $_POST['error'] to an error message so I can show it in the error DIV.
}
Thanks!
You can define a $message athe beginning of your page then handle the errors you want to show
$message = '';
if (password_verify($_POST['oldpassword'], $result['password'])) {
// Upload password to database
} else {
//set a proper message ID which will be handled in your DIV
$message_id = 1;
header('location: /current_path.php?message='.$message_id);
}
Now in the div you can show it as
if (!empty($_GET['message'])) {
echo '<div id="error">';
if ($_GET['message'] == 1) { echo 'First message to show.'; }
elseif ($_GET['message'] == 2) { echo 'Second message to show.'; }
echo '</div>';
}

_e printed before layout WPML/Wordpress/PHP

I am using WPML to translate English to a different language.
Everything works fine except the mail form.
For some reason when is use the _e() function the string gets printed before the layout.
But still inside the body element. Please help here is the code:
if(trim($_POST['contactSubject']) === '') {
$subjectError = _e('Please enter a subject.', 'wpml_contact');
$hasError = true;
} else {
$subject = trim($_POST['contactSubject']);
}
You should use the __() function (codex link). This function returns the translated string:
if(trim($_POST['contactSubject']) === '') {
$subjectError = __('Please enter a subject.', 'wpml_contact');
$hasError = true;
} else {
$subject = trim($_POST['contactSubject']);
}
The _e() function returns and displays the translated string.

Categories