How to handle PHP form validation errors using bootstrap alerts? - php

I'm developing a webapp using PHP and I have a form in which users can create an account. So I have some server-side validations like if the password is 8 characters or more. All I need is that I want to show the error message returning from PHP via bootstrap alert.
For example a user have entered an invalid password, like it's 6 characters instead of 8. I want it to return the error like this:
I want this alert box to show up
Here I've got two pages. register-action.php and footer.php
In the register-action.php I've got my PHP to validate the form in which the user enters data.
In the footer.php I've got my form which is in a bootstrap modal actually (as you can see in the photo above).
Here is the if condition in register-action.php which validates the password:
$uppercase = preg_match('#[A-Z]#', $password1);
$lowercase = preg_match('#[a-z]#', $password1);
$number = preg_match('#[0-9]#', $password1);
if(!$uppercase || !$lowercase || !$number || strlen($password1) < 8) {
$passwordNotGood = "Your password is not satisfying the requirements";
echo $passwordNotGood;
exit();
}
Here is the bootstrap alert in footer.php:
<!-- This alert will show up if password requirements are not satisfied -->
<div class="alert alert-danger" role="alert">
<p>Your password should be more than 8 character and should container ....</p>
</div>
I want the bootstrap alert to be hidden unless the error is needed to be showed up. So if the user has entered a short password I want the form not to submit and the alert show up.
So how can I return the error from PHP via bootstrap alert when the user submits the form?
I've tried to actually change the HTMLDOM from PHP using JS but it didn't turned out the way I wanted.

You can print php error with this code. for example:
<div class="alert alert-danger">
<?php echo $errorVariable ?>
</div>
My advice for you: use errors array and when the inputs have many errors you can do for loop to this errors and show them in one time like:
<?php
$errorsArr = [];
?>
<?php if(count($errors)){ ?>
<div class="alert alert-danger">
<ul>
<?php foreach($errors as $error){ ?>
<li><?php echo $error ?></li>
<?php?>
<ul>
</div>
<?php } ?>
I wish i have answerd your question.
regards.

The short answer is that you need to solve this in the front end by javascript.
Your logic in the php is good but your approach is not going to work. You can do this validation in php using SESSION variables but in your case that your form is in a pop up I think it is not the way to go. You have two options:
-doing a front end validation by javascript.
-making an AJAX request
I assume that you are not yet very experienced in web environnment so I recommend you the first option.
Good luck!

Related

How to show the validation error message on a form in php?

I'm trying to make a validation script in php for a register form. The problem that I have is that the error message doesn't show and I can't figure out the problem. I've tried different sources but something is escaping my eye
This is in the register-page.php file. The problem code is the php one in the tag
<form method="post" action="register-user.php" class="col-12" id="login-position">
<?php
if(!empty($_SESSION['errors'])){
echo $_SESSION['errors'];
}
?>
</form>
And this is in the register-user.php:
array_push($error, "User already exists");} ($error is the array where I put the error messages.
if (count($error) == 0)
{
//some code to insert into database, works fine
}
else {
$_SESSION['errors'] = $error;
header("Location: register-page.php");
exit;
}
Nothing is printed on the screen. As a mention at the head of the file I have $session_start(). When I click on the submit button, I expect the page to refresh and show the error message. Can you please help?
As stated in the comments to your question:
echo $_SESSION['errors'];
will never work since you are trying to echo an array (as you stated before).
Try doing
print_r $_SESSION['errors'];
to see if the content is there. Then you can loop the array to print each item inside.
First you need to put a
session_start();
on top of the file where you want to access the $_SESSION values

How do i go about echoing back to a form from a form post action?

I have a form containing a textarea for inputing text into. The form also contains a submit button. After pressing the submit button it posts the text within the textarea into my php document. Within my php document the text is added to a database. Once it has been added to the database I would like it to echo back a response telling the user that it has added the text to the database successfully.
However, if i make it echo that response back to the home page, there is nowhere declared for it to display the echoed message. Has anyone got an idea of what i should be doing in order to get this working? Many Thanks.
Normally i wouldn't use a post straight from the form and i would use ajax and then display the data within a paragraph or something on it's return, however since the form is doing the post it's self i am not sure where to then declare where the response should show up.
The bellow displays my html form code and shows it's action to post to a php file.
<div id="userban2"><form id="bannable" action="/onlineusers.php" method="post"><p> Type username to ban bellow:</p>
<textarea name="banned" id="banned" maxlength="255"></textarea><br/>
<input type="submit" value="Send" class="extrabuttons" onclick="return false; preventDefault();">
<div id="cancelban" class="extrabuttons"><p> cancel</p></div>
</form>
However when in my php file i write ....
echo "the information has been added to the database successfully";
It might send the echo back however it isn't declared to display anywhere how can i change this to make it display the response within my form?
As requested return from my php
if(isset($_POST["banned"])){
$ban_name = $_POST["banned"];
bannedd($ban_name);
}
function bannedd($ban_name) {
$query1 = mysql_query("INSERT INTO banned_users (username,firstname,lastname,email,password,ip_address,sign_up_date,last_logged_in,about,sta rr,userpref) VALUES('$usernameb','$fnameb','$lnameb','$emailb','$passwordb','$ip_addressb','$sign_up_date b','$last_logged_inb','$aboutb','$starrb','$userprefb')") or die("Could not insert your informaion");
echo "This user has successfully been banned";
}
The form posts what is written in the form due to it having the action and method of post to my php. However should i then have any return i am not sure how i declare where the returned information should then show (The echoed message).
If I understand you correctly, your form is in some index.php file and sends the data to other file - onlineusers.php, and you want to display the message in the original page?
If this is the case, the most simple way I can think of is redirect back to the original page with a URL parameter, instead of echoing.
Do this at the end of onlineusers.php:
<?php
// insert text into DB ...
header("Location: index.php?result=ok");
?>
This redirects the browser back to the original page with the form. There you check if the status variable is set:
<html>
<head></head>
<body>
<?php if(isset($_GET["result"]) && $_GET["result"]=="ok") { ?>
<p>The information has been added to the database successfully</p>
<?php } ?>
<form> ... </form>
</body>
</html>
As you can probably see, you could set other results, such as "error" this way.
If you don't like the extra string in your URL, then create a cookie after processing the form in onlineusers.php and back at the original page, check if such cookie has been set. If you need more detail on that, let me know. And if you're asking something completely different, well, never mind :)
Your form is being submitted to /onlineusers.php
This is where you would want to add your echo statement.
If you require the info on the same page you technically return to the same page with the form action being $_SERVER['PHP_SELF'].
<form id="bannable" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Then you can put in a conditional statement prior to the load of your document, and include the PHP script.
<?php
$testVar = false;
$msg = '';
if($_POST) {
include '/onlineusers.php';
//... do something e.g post to database and return true.
}
if($testVar) {
$msg = 'Successful writing to DB!';
} ?>
<html>
<body>
<?php echo $msg; ?>
</body>
</html>
This will check to see if you have any post data, if you do, then it includes the script you specify. Maybe set $testVar to true if the writing to DB is successful, and then return $msg in your HTML.

post-redirect-get and posting double entries into Database

I am currently doing a web application project for my final year in school. I am more of a web designer than a web developer so I need as much help as I can get!
For my project, I am create a website very similar to a blogging site.
The first function I wanted to implement runs when the user is registering, I wanted signUp.php(html form) / doSignUp.php(php post data to database) to prevent the user from using a username that is already in the database.
For example, database has username="happy". User1 fill up the form at
signUp.php in the username fill "happy" and submit the form into
doSignUp.php. doSignUp.php checks the database whether
username="happy" is inside. If it is inside, it will NOT post the data
again inside to prevent double entry but instead REDIRECT back to
signUp.php and inform the user that with a message "the user name is
in used".
For the first function I have the idea of:
$selectUser = executeSelectQuery("SELECT username FROM user WHERE username="$username")
if ($selectUser==0) {
$doRegister = executeInsertQuery("INSERT INTO user (Name,Username, Email,
Password, DOB_Date, DOB_Month, DOB_Year, Gender,admin, Country) VALUES
('$Name','$Username','$Email',SHA1('$Password'),'$DOB1','$DOB2','$DOB3','$Gender','$role' ,
'$Country')");
} else {
<// redirect codes here to signUp.php with message "user name is in used">
}
Second function I want to implement involves login.php(login form), doLogin.php(check whether the posted data matches with the one entered in the login form) and memberPage.php(redirect the user to memberPage if he is the member and create a session for him, else redirect to login.php if he is not a member to show him some message).
As for the second function, I have really no idea how to implement the post-redirect-get method for my login. I tried google for demos to try but to no avail. Please help if you can! Thanks in advance :D
Code to redirect:
header("Location: signUp.php?message=" . urlencode("user name is in use"));
In signUp.php, to print the error, print $_GET['message'].
In your case, using the header() function to redirect back to your sign-up display page (signUp.php) with a message will work, however I often discourage this multi-file attempt at form processing.
Something much more appealing (at least to me) is placing the processing logic at the top of the file that displays the form. This logic would need to be wrapping in a check to make sure the form had been submitted. If anything goes wrong, it stores the error in a variable that could be displayed later in the file. Take a look at this example:
<?php
if($_POST['submit'] == 'Submit') {
if(!$userNameIsUnique) { //Mysql Processing - duplicate check here
$message = "Username has already been used.";
}
//Check other fields for duplicates or invalid data
if(!isset($message)) {
//Form submit successful send info to data
mail(); //Send confirmation email
die('Check your email to verify your account!'); //Display success message
}
}
?>
<html>
<head><title>Signup</title></head>
<body>
<?php if(isset($message)) echo '<p>'.$message.'</p>'; ?>
<form action="" method="post">
<input name="username" />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
In this situation, you can still separate views and controller logic (with file includes), but you avoid having two files and forcing two requests (one for the form submit and one to redirect back to the form) when there is an error with the input.

How to redirect and inform the user if his or her password is incorrect?

Assuming I have a block of code like this on a login page:
<form action="login_action.php" method="post">
<div id="account">
<div class="form-label">Username:</div>
<div class="form-input"><input name="username" type="text" /></div>
<div class="form-label">Password:</div>
<div class="form-input"><input name="password" type="password" /></div>
<div class="form-submit"><input type="submit" value="Submit" /></div>
</div>
</form>
The login_action file queries the database with the given credentials and if they are correct performs $_SESSION['username'] = $username;
This works fine. However, if the user provides incorrect credentials, ideally the page would not redirect and instead it would display an error message on the page on the line before username. This is the part I am confused on how to tackle.
Would I instead have to capture the submit button press with JQuery and post the user credentials to the php file with AJAX? This would then get rid of the form on the login page. I suppose then I could return a string specifying whether or not the credentials were valid and if not, it would append a message to the account div that the credentials were incorrect.
Would that be the standard approach to this sort of problem? Since recently discovering AJAX I am using it for almost everything and I'm not sure if in this case it is the ideal solution. Overriding the submit button's default behavior and removing the form seems kinda hacky to me but I'm not sure. Is this how SO would solve this?
What I normally do is, use condition statement & redirect back to form if the password is incorrect. Assume your form page is form.php, the redirect could be form.php?status=password.
Then you can display an error message in your form
if ($_GET['status'] == 'password')
echo "Incorrect Password";
You can do this almost anyway you like, the only advantage to the AJAX method (that I can see) is perhaps less bandwith hog.
$("form").submit(function(e){
e.preventDefault();
//AJAX & other code here
});
The method that most basic login forms use is to have the login form post back to itself. If there is a problem with the username or password, just echo an error message to the page with PHP.
If for some reason you really want a separate handler page, you can use "flashes" where you store an error message temporarily in the session. The login page can then display that error message and erase it from the session.
Sending the values from the form to a php script via ajax is pretty much the perfect solution. The page wont reload, and the user will get a response quickly from the server. Here's your jQuery:
$('#form').submit(function(e){
// there are many ways to assemble this input data array, this is an easy clunky way,
// you could also use $.each to iterate over all input elements, get their
// vals, and pop them into the inputVals array.
var inputVals = [$('#input_id1').val(), $('#input_id2').val()];
$.ajax({
url:"your_php_script.php",
type: 'POST',
data:inputVals,
success:function(data){
// data returned from php script as a 'json_encode' string
}
});
return false;
})
//`
if(isset($_GET['msg']))
{
$message=$_GET['msg'];
}
?>` add following to ur login form
// ----------------------
// add this code to display error message if password dont match
<p id="m2">
<?php
if(isset($_GET['msg']))
{
echo $message;
}else{
echo "enter password";
}
?>
</p>
//------------------
add this code to your login.php script
$message="password do not match";
header("Location:index.php?msg=$message");

Easiest way to give Javascript alert after PHP header() redirect

I have a page where users submit a form, and it goes to a separate PHP script. After the script is done, it header() redirects the user back to the page they were on. Now what I want to do is if there is an error or certain conditions in the script, redirect the user to the same page but display a Javascript alert once they get there as a warning message. I could append some variables to the URL and check for that with $_GET but I figure there is probably an easier way... perhaps with some POST data, or something like that?
Thanks
You can do this all on the server side by using the session:
"Show form" php script creates the form and returns it to the user.
User fills it out and submits it to another php script "receive script" which receives the form data, and notices an error, missing data, etc.
The "receive script" stores the error msg in the session (as item err) and redirects to the 'show form' script.
The "show form" script (same as in step 1) actually does more than create the form. It also:
looks in the session to see if it has an item 'err', an error msg. In step 1 there wasn't. But now there is. So the php script creates the form, along with a div that shows the error msg to the user.
Resets the session's 'err' item to nil.
The php script could also include javascript in the page which would make the error msg disappear after a while or be shown as a popup, etc.
ps. The above flow is how rails handles forms and redisplay of the form.
Update: Thanks to #zod for pointing out that I wasn't clearing the err item in the session.
If an error is encountered, store the error state to a $_SESSION array and then redirect the browser to the original page. Have a script on the original page to check if an error state is set. If yes, trigger a javascript alert or whatever handling you want to have.
And at the common footer template (or at the footer of original page), check and clear the errors array, so it doesn't persist when the user moves to other pages or reloads the current page.
Example:
processor.php
<?php
if($something == $iswrong){
$_SESSION['errors']['error5301'] = 1;
session_write_close();
header("Location: http://www.example.com/originalpage.php");
exit;
} ?>
originalpage.php
<!-- Header -->
<?php
if(isset($_SESSION['errors']['error5301']) && $_SESSION['errors']['error5301'] == 1){ ?>
<script type="text/javascript">
alert('Something is not correct!');
</script>
<?php } ?>
<!-- Some page content -->
....
.....
..
......
<!-- Footer -->
<?php
if(isset($_SESSION['errors'])){
unset($_SESSION['errors']);
} ?>
Hope that helps.
first page
<script>
onsubmitfunction()
{
document.getElementByid('errorid').value=1;
}
</script>
<form name='' id='' onsubmit="javascript:onsubmitfunction();">
<input type='hidden' id='errorid' value=''>
</form>
In destination.php
<?php
if($_POST['error']==1)
{
?>
<script language='javascript'>
alert('Errrrrorrrr');
</script>
<?
}
?>
This is enough for your question.
As per my understanding

Categories