php error message does not display on blank field - php

I have a form where a user is required to enter their full name, contact number and best time to call details. I would like to validate these fields on my web form so that users cannot submit the form without those fields being filled. I have used if(empty($...)) and echoed my error message however, when i try to submit the blank form it doesn't display any of the error messages. How could i resolve this?
CODE
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/inc/bootstrap.php');
include("config/cn.php");
$template['template'] = "page";
if($_POST)
{
// Data pulled from input form
$full_name = $_POST['full_name'];
if (empty($_POST['full_name']))
{
// Set error and return to form
echo "Field cannot be left blank";
header('Location: /call-back-form.php');
exit;
}
$contact_number = $_POST['contact_number'];
if (empty($_POST['contact_number']))
{
// Set error and return to form
echo "Field cannot be left blank";
header('Location: /call-back-form.php');
exit;
}
$best_time_to_call = $_POST['best_time_to_call'];
if (empty($_POST['best_time_to_call']))
{
// Set error and return to form
echo "Field cannot be left blank";
header('Location: /call-back-form.php');
exit;
}
$enter_sql = "INSERT INTO contact (full_name, contact_number, best_time_to_call)
VALUES('$full_name' , '$contact_number' , '$best_time_to_call')";
/*print($enter_sql);*/
$enter_query = mysql_query($enter_sql) or die(mysql_error());
header('Location: /thankyou.php');
exit;
}
?>

Well, there is an error in logic. You are doing an echo then header. Which means it shows the message and returns them to the previous page faster than they can see the message. Is this really what you wanted to do?
You should probably either post the form to itself and just just echo without the header where you want the errors displayed, or implement javascript form validation.
Also, you could use
<?
header('Location: /call-back-form.php?message=Error');
?>
And then in call-back-form.php user
<?
echo $_GET['message'];
?>
where needed

Related

How to use $_SESSION to display messages

if(isset($_SESSION['contactstatus'])&& $_SESSION['contactstatus']){
echo ' <p>Your request has sent successfully.</p>';
unset($_SESSION['contactstatus']);
}
I want to use session to display messages after the validation of input in the form is done. How to do it or there still need to write any codes in the form?
At first, you have to fill the Session after pass the validation condition.
session_start();
if($validationCondition){
$_SESSION['contactstatus'] = 'Success';
}
Your code is all right, and you only need to print the content of Session
if(isset($_SESSION['contactstatus'])&& $_SESSION['contactstatus']){
echo ' <p>Your request has sent successfully.</p>';
echo 'Content of your SESSION:' . $_SESSION['contactstatus'];
unset($_SESSION['contactstatus']);
}

Make PHP form do nothing if field is empty

At this moment I have a small contact-box on my page that ask for telephone number.
If no number is entered the form should do nothing. Instead of sending a empty email to my client.
It is not necessary that the form creates a message or something else if the field is empty.
I just want to have extra php code, that makes sure nothings happening if somebody clicks the send button while the field is left empty.
This is my code:
<?php
$EmailFrom = Trim(stripslashes($_POST['email']));
$EmailTo = "INFO#EPIMMO.BE";
$Subject = "Vraagt om hem te bellen - Website Epimmo";
$free = Trim(stripslashes($_POST['free']));
// validation
$validationOK=true;
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
exit;
}
// prepare email body text
$Body = "";
$Body .= "Volgend telefoonnummer werd ingevoerd via uw website:";
$Body .= $free;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
// redirect to success page
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=http://www.epimmo.be/hire-us-phone.php\">";
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
?>
Thanks for reading and a hopefully a solution ;-)
Kristof
First you can add if condition that will check email or phone number is not blank
and in its not blank then execute next code of sending an email.
if(isset($_POST['email']) && $_POST['email']!="")
{
//write here your code to send an email
}
You can do this with HTML like this:
<input type="number" required></input>
Just after <?php you could add the following code:
if(!isset($_POST['free']) || empty($_POST['free']) {
header('location: /hire-us-phone.php');
exit;
}
header('location: /hire-us-phone.php'); will do a header redirect to /hire-us-phone.php (which is much better than using a meta refresh) and exit; will ensure no code after the header redirect will be run.
To redirect, you should be using:
header("Location: your-url.php");
exit;
This code would need to go before anything is echoed, including whitespace.
Also, what is this code?
// validation
$validationOK=true;
if (!$validationOK) {
Clearly, the if statement will never be false.
You could validate the easy way, such as one big if statement. But a better way is to do something like this:
if($_POST['email'] == ''){
$_SESSION['my_form']['errors']['email'] = 'The email was left blank';
}
if(!empty($_SESSION['my_form']['errors'])){
// redirect & exit here
}
And then on your form page, you can use this session data to display a relevant error to the user:
if(isset($_SESSION['my_form']['errors']['email'])){
// output $_SESSION['my_form']['errors']['email'] here to the user
}
Here, we're presented with the action page, which means something has already happened: The form was submitted, and redirected to the action page.
As #Mohini pointed out, you can test the condition of an empty field on the action page.
But after the submit button is pressed, you can easily use javascript on the form page to test if the required fields are populated.
(plain vanilla javascript)
if(! document.forms['formname']['email'].value == "" ){
document.forms['formname'].sumit();
} else {
// do nohing. Or do something. I don't really care!
}

How to redirect to another page in php?

Here is the code for registration. Values are inserted properly but page is not redirected to another page:
if(isset($_POST['submit'])){
$company_name = $_POST['company_name'];//check whether form is submitted or not
$email = filter_var($_POST['email'],FILTER_SANITIZE_EMAIL);//email validation
$password = sha1($_POST['password']);
$phone = $_POST['phone'];
$city = $_POST['city'];
$profession = $_POST['profession'];
check validation of email
if(!filter_var($email,FILTER_SANITIZE_EMAIL)){
echo 'invalid email';
}
else
{
$result = mysql_query("SELECT * FROM registerpro WHERE email = '$email'");selecting email from database
$data = mysql_num_rows($result);//check if there is result
if($data==0){
$qry = mysql_query("INSERT INTO registerpro (company_name,email,password,phone,city,profession) VALUES ('$company_name','$email','$password','$phone','$city','$profession')");
here i is the problem as page is not redirecting to another page so please tell me how to fix it
if($qry){
header("Location : company_info.php");//redirect to company_info
}
else`enter code here`
{
echo 'error';
}
}else{
echo 'invalid email';
}
}
}
?>
After registration page is not redirecting to company_info.
Remove extra space after Location
So, change
header("Location : company_info.php");//redirect to company_info
To:
header("Location: company_info.php");//redirect to company_info
// ^ here
I finally figured this out after struggling a bit. If you perform a web search on the PHP header() function you will find that it must be used at the very top of the file before any output is sent.
My first reaction was "well that doesn't help", but it does because when the submit button is clicked from the HTML input tag then the header() function will get run at the top.
To demonstrate this you can put a section of PHP code at the very top with the following line...
print_r($_POST);
When you then press the "Submit" button on your web page you will see the $_POST value change.
In my case I wanted a user to accept the Terms & Agreement before being redirected to another URL.
At the top of the file before the HTML tag I put the following code:
<?php
$chkboxwarn = 0;
/* Continue button was clicked */
if(!empty($_POST['continue']) && $_POST['continue']=='Continue'){
/* Agree button was checked */
if(!empty($_POST['agree']) && $_POST['agree']=='yes'){
header('Location: http://www.myurlhere.com');
}
/* Agree button wasn't checked */
else{
$chkboxwarn = 1;
}
}
?>
In the HTML body I put the following:
<form method="post">
<input type="checkbox" name="agree" value="yes" /> I understand and agree to the Terms above.<br/><br/>
<input type="submit" name="continue" value="Continue"/>
</form>
<?php
If($chkboxwarn == 1){
echo '<br/><span style="color:red;">To continue you must accept the terms by selecting the box then the button.</span>';
}
?>

PHP, display message if one or more fields is empty

What I want is to show the error (message), only if the user do a false action. For example, if the field is empty, it will show (Please fill all the fields). I've already done that, but the problem that I have is that it shows also if the user enter to the page for the first time, meaning it does NOT respects the (if condition) that I have written !
The question :
How to show the message only if one of the fields is empty ?
Any ideas on how I can solve it ?
Here is my code :
<?
$conn = mysqli_connect('localhost', 'db', 'db_pass', 'db_name') or die("Error " . mysqli_error($conn));
$email = filter_var(trim($_POST['email']), FILTER_VALIDATE_EMAIL);
$old_password = trim($_POST['old_pass']);
$new_password = trim($_POST['new_pass']);
$email = mysqli_real_escape_string($conn,$email);
$old_password = mysqli_real_escape_string($conn,$old_password);
$new_password = mysqli_real_escape_string($conn,$new_password);
if(empty($email) || empty($old_password) || empty($new_password)){
echo 'Please fill all the fields !<br>';
}
else{
$sql="UPDATE users SET pass='$new_password' WHERE email='$email' AND pass='$old_password'" or die("Error " . mysqli_error($conn));
$result = mysqli_query($conn,$sql);
mysqli_close($conn);
}
if($result){
echo'Password changed successfully !';
}
elseif(!$result) {
echo 'The email/password you provided is false !';
}
?>
Validation of any form happens in the "action" file within a condition i.e. the validation should be subjected to the event of user clicking the submit button. For this to work you should check that
1. Your form has a submit button with a name property set to say submit (can be anything)
eg: <input type="submit" name="submit" id="someid" value="Submit" />
2. The form must have action property pointing to a processor file
eg: <form action = "somefile.php" method = "post">
3. In the somefile.php file the validation code must be within a condition which checks for the event of form been submited
eg://somefile.php
<?php
if(isset($_POST['submit']{
//all the validation code goes here
}else{
//for a single page form and validation
// the code for displaying the form can go here
?>
I suggest you to do this:
First define a variable with plain $_POST[] for eg $name = $_POST['name'];
Then, check if all the vatiables you've define are empty or not.
Lastly, Use escape_string() or whatever you want.
The solution is to check for a variable that you know will always be set if the form is submitted, usually the submit button.
For example, if your form ends like this:
...
<input type="submit" name="change_password" value="Change password" />
</form>
then in the PHP code you could check
if(isset($_POST['change_password'])) {
// The submit button was in the POSTed data, so this is a form submit
} else {
// This is a new page load
}
Alternatively, if you are POSTing the data, you can check which HTTP method was used to call the form:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Form was posted
} else {
// $_SERVER['REQUEST_METHOD'] == 'GET'
}
The pattern I commonly use is:
$showForm = true;
if( is_form_postback() ) {
if( data_is_valid() ) {
redirect_to_thank_you_page();
} else {
show_validation_errors();
$showForm = false;
}
}
if($showForm) {
// Print the form, making sure to set the value of each input to the $_POSTed value when available.
}

Position PHP code with CSS

I have a form that is positioned on the page with HTML, if the user completes the form then they are thanked with a PHP message. Because the form is positioned with <form id="formIn"> CSS the PHP text is now in the wrong position, does anyone have an idea how this can be positioned so that the PHP echo text is nest to the form?
I have tried to include the code in PHP, i.e.
<div id=\"text\">
But no joy.
Code used so far is:
<?php
echo "* - All sections must be complete"."<br><br>";
$contact_name = $_POST['contact_name'];
$contact_name_slashes = htmlentities(addslashes($contact_name));
$contact_email = $_POST['contact_email'];
$contact_email_slashes = htmlentities(addslashes($contact_email));
$contact_text = $_POST['contact_text'];
$contact_text_slashes = htmlentities(addslashes($contact_text));
if (isset ($_POST['contact_name']) && isset ($_POST['contact_email']) && isset ($_POST['contact_text']))
{
if (!empty($contact_name) && !empty($contact_email) && !empty($contact_text)){
$to = '';
$subject = "Contact Form Submitted";
$body = $contact_name."\n".$contact_text;
$headers = 'From: '.$contact_email;
if (#mail($to,$subject,$body,$headers))
{
echo "Thank you for contacting us.";
}else{
echo 'Error, please try again later';
}
echo "";
}else{
echo "All sections must be completed.";
}
A good way for doing this is to create a div for displaying messages in the form page and return back from the php script to the form page including form.html?error=email or form.html?success to the url. Then with javascript you can identify when this happens and display a message or another.
Comment if you need some code examples.
EDIT:
Imagine your php script detects that email field is not filled, so it would return to the form webpage with a variable in the url:
<?php
if(!isset($_POST["email"]){
header("location:yourformfile.html?error=email")
}
?>
Then, in your form webpage you have to add some javascript that catches that variable in the URL and displays a message in the page:
Javascript:
function GetVars(variable){
var query = window.location.search.substring(1); //Gets the part after '?'
data = query.split("="); //Separates the var from the data
if (typeof data[0] == 'undefined') {
return false; // It means there isn't variable in the url and no message has to be shown
}else{
if(data[0] != variable){
return false; // It means there isn't the var you are looking for.
}else{
return data[1]; //The function returns the data and we can display a message
}
}
}
In this method we have that data[0] is the var name and data[1] is the var data. You should implement the method like this:
if(GetVars("error") == "email"){
//display message 'email error'
}else if(GetVars("error") == "phone"){
//dislpay message 'phone error'
}else{
// Display message 'Success!' or nothing
}
Finally, for displaying the message I would recommend creating a div with HTML and CSS and animate it to appear and disappear with jQuery. Or just displaying an alert alert("Email Error");
Just create a <div> before or after your form and put IF SUBMIT condition on it.
Like,
<?php
if(isset($_POST['submit']))
{ ?>
<div>
<!-- Your HTML message -->
</div>
<?php } ?>
<form>
</form>

Categories