PHP, display message if one or more fields is empty - php

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

Related

ASK PHP : how to send form data to different .php file

I have a code like this:
<body>
<?php
// define variables and set to empty values
$namaErr = $nikErr = $shiftErr = "";
$nama = $nik = $shift = $keterangan = $tgl = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["nama"])) {
$namaErr = "<br><i>Nama tidak boleh kosong</i>";
} else {
$nama = test_input($_POST["nama"]);
// cek nama harus pake huruf tanpa simbol
if (!preg_match("/^[a-zA-Z ]*$/",$nama)) {
$namaErr = "<br><i>Nama harus diisi dengan Huruf dan tanpa karakter simbol</i>";
}
}
if (empty($_POST["nik"])) {
$nikErr = "<br><i>NIK tidak boleh kosong</i>";
} else {
$nik = test_input($_POST["nik"]);
// cek nik harus pake angka tanpa simbol
if (!preg_match("/^[0-9]*$/",$nik)) {
$nikErr = "<br><i>NIK harus diisi dengan Angka</i>";
}
}
if (empty($_POST["keterangan"])) {
$keterangan = "";
} else {
$keterangan = test_input($_POST["keterangan"]);
}
if (empty($_POST["shift"])) {
$shiftErr = "<i>Pilih salah satu Shift Kerja</i>";
} else {
$shift = test_input($_POST["shift"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div class="container">
<form name="fmk" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
</html>
I want to send the form data to Proses.php to show the form data, but when I change the section form action from <form name="fmk" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post"> to
<form name="fmk" action="<?php echo htmlspecialchars(proses.php);?>" method="post"> or
<form name="fmk" action="proses.php" method="post">, it succeeds in submitting the form data to Proses.php, but the PHP code inside Proses.php fails to check the form data for validation. My objective is when I click the Submit button, it will go to another page and show the result from form data with PHP syntax when the input field is not empty. If some input fields are empty, it will show the red sign and not go to the other page (still on the first page).
Please help me to solve this problem.
Sorry for my bad english, Love from Indonesia :)
If you want the form validation on the client side to happen as (show the red sign if empty) you must add the required attribute to your input fields.In this way you can successfully check your form inputs and in addition if you want to set the input pattern for your input you can also use pattern attribute in your inputs.Both of these will validate your form on the client side.
Hope this might help you.
how to send form data to different .php file
There are a couple of ways to do this depending on how you want to process the information. You can use the form to send over post by setting your action attribute to the desired page. Setting the method attribute to post allows the name of the input fields to be carried over to that page through the server. On the target page you check the $_POST globals to make certain they are set and if they are set, you can then define them or call on their global variables in your code.
The way I do this on my target page is to first check if the submit button is set in the global POST array. If I have a button that submits my form and that name is name="submit" the $_POST will store that as a value in the global array.
if(isset($_POST['submit'])){
//submit is set, I can now check for the other values in the global $_POST array
if (empty($_POST["nama"])) {
$namaErr = "<br><i>Nama tidak boleh kosong</i>";
} else {
$nama = test_input($_POST["nama"]);
// cek nama harus pake huruf tanpa simbol
if (!preg_match("/^[a-zA-Z ]*$/",$nama)) {
$namaErr = "<br><i>Nama harus diisi dengan Huruf dan tanpa karakter simbol</i>";
}
}
}
If I have an issue here. For example I am testing and I know the things are set in the form, I can var_dump($_POST) and make certain that $_POST values are set by looking at the results of my $_POST array and checking the key/value pairs.
The other way to direct a user once they submit a form is by having the form action set to self or leaving your action attribute out completely. You can check if the submit button is set and then parse through the global $_POST array within the if(isset($_POST['submit])){ //form has been submitted check inputs, run validations and set errors, etc, etc... } conditional. You can do all the work on the same page the form is on using this method and then once all has been successfully completed use a header redirect to send the user to the desired page you wish for them to visit with a success url post.
It would be something to the effect:
if(isset($_POST['submit'])){
if(isset($_POST['name'])){
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$msg = "Success, thank you for submitting";
// maybe check validation of inputs and run other inputs through sanitation etc...
// once you finish your checks if all is good set your url params
$host = $_SERVER['HTTP_HOST']; // sets your server name
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); // PHP_SELF
$root = 'proses.php';
$urp = '?success';// adds a url post to your url and this can be checked on the other page
header("Location: http://$host$uri/$root$urp");
exit;
}else{
// run error code here
$error = true;
$msg = "Error please try again";
}
}

Form submission results in a blank page in PHP

I am trying to make a login system and i want to create a conditional statement that checks whether the global variable $_POST['submit-form'] is set.
If the global variable $_POST['submit-form'] is set then i want to echo out the fields of the submitted forms. This works fine..
The problem comes when i want to check whether the global variable $_POST['submit-form'] is empty, i get a blank page when i submit the form with nothing. It is supposed to echo out something like "You have entered nothing, please try again'.
I don't know what is wrong.
This is the code for the form.
<form action="test-form2.php" method="POST">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit" name="submit-form" value="submit">
</form>
..and this is the code for the form handler.
<?php
if(isset($_POST['submit-form'])) {
$name = $_POST['name'];
$email = $_POST['email'];
if(($_POST['name'] != "") && ($_POST['email']!= "")) {
echo "This is your name: ".$name."<br>";
echo "This is your email: ".$email;
// header('refresh=3;url = ../leden/index.php');
}
} else {
echo "You have entered nothing or your username and/or password is incorrect, please try again.";
// header('refresh=3;url = /test-form1.php');
}
?>
Your $_POST always have submit-form (and it's always not empty), so if statement always returns true. Try to check (for example) only that $_POST['name'] and $_POST['email'] are not empty.
The problem with your code is that checking if it's set isn't enough .. Because it may be set and be empty -- Realistically what you want is to check both isset and whether it's empty IE:
if (isset($_POST['submit-form'] && $_POST['submit-form'] != '' && $_POST['submit-form'] != null)
If the above if statement fails your value for $_POST['submit-form'] is most likely not being submitted.
UPDATE
Check for blank fields
if ($_POST['name'] != '' && $_POST['email'] != ''){
// Do stuff
}else{
if ($_POST['name'] == ''){
echo "name is empty";
}
if ($_POST['email'] == ''){
echo "email is empty";
}
}
That's because isset($_POST['submit-form']) returns true even if you don't input anything in Name and E-mail fields, it's value would be submit string when hit submit button to submit the form. This is the reason else part of below block is not getting executed.
if(isset($_POST['submit-form'])) {
} else {
echo "You have entered nothing or your username and/or password is incorrect, please try again.";
}
Use var_dump($_POST); to see the complete array structure. having said these, you can use the following snippet to achieve the desired result,
if(isset($_POST['submit-form'])) {
$name = $_POST['name'];
$email = $_POST['email'];
if(($_POST['name'] != "") && ($_POST['email']!= "")) {
echo "This is your name: ".$name."<br>";
echo "This is your email: ".$email;
// header('refresh=3;url = ../leden/index.php');
}else{
echo "You have entered nothing or your username and/or password is incorrect, please try again.";
}
}
Validation and scrutinization of user inputs should be your next action items in the list.

Form submission is not displaying or executing

Recently I built a form using HTML, CSS, and JavaScript. I then entered the PHP required to send the data that is inputted in the form, to my database. After I finished, what I thought was necessary for it to work, I ended up with a blank page when I executed the code. The form and everything disappeared. This is my PHP code:
<?php
require("$_SERVER[DOCUMENT_ROOT]/connect.php");
$email = $username = $type = $question = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if(!empty($_POST))
{
if(isset($_POST["email"], $_POST["username"], $_POST["type"], $_POST["question"])
{
$email = test_input($_POST["email"]);
$username = test_input($_POST["username"]);
$type = test_input($_POST["type"]);
$question = test_input($_POST["question"]);
$premium = ($_POST["premium"]);
$member = $_POST["member"];
$terms = $_POST["terms"];
if ($member != "NO")
{
$member = "YES";
}
}
if(!empty($email) && !empty($username) && !empty($type) && !empty($question) && !empty($terms))
{
$insert = $db->prepare("INSERT INTO QuestionSubmission (Email, Username, Type, Question, Member, Premium, Date) VALUES (?, ?, ?, ?, ?, ?, NOW())");
$insert->bind_param("ssssss", $email, $username, $type, $question, $member, $premium);
if($insert->execute())
{
header("Location: landing.php");
die();
}
}
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
The "member" part is a check box where the user can optionally select to become a member. It is unchecked initially, and i've set a value of "NO" for that. Also, there is a hidden check box that is already checked with a value of NO...this is the "premium" check box. Lastly, there is a check box for agreeing to the terms. This is initially unchecked, but the user has to check it so it won't be empty and for the form to process.
Could you please explain what I have to do in order for my form to work properly?
Also, the " require("$_SERVER[DOCUMENT_ROOT]/connect.php"); " part is where my connection to the database code is located. This code and the form code is located in the same page.
Replace require("$_SERVER[DOCUMENT_ROOT]/connect.php"); with require_once $_SERVER[DOCUMENT_ROOT]."/connect.php");, you're not using a variable - the $_SERVER can't be used like you're using it. This is why you're getting a "blank page of death", if you check your error_log you'd see that it has a syntax-error because of it.
Furthermore, you're checking if(!empty($_POST)) - this could really be any POST-form. You should remove this code
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if(!empty($_POST))
{
as you're checking if the inputs are set just below the above code.
As a final note, when you're using die();, you should use exit; instead. They really do the same thing, but usage of die() is more for error-checking, like "Script can't run any further - die now!", while exit; is more like "I would like to stop the script from running now, I'm done - thanks!".
Normally it’s easier to include the processing code inside the form page. That way, if you encounter errors, you can:
allow the code to fall through to the form again
persist old values by using the value="…" attribute
Roughly it looks like this:
<?php
$email=$username=''; // etc
if(isset($_POST['submit'])) { // or whatever you name the submit button
// validate data
if(!$errors) {
// process
// new location
}
// retain values from above
}
?>
<form>
<label>Name: <input type="text" name="username" value="<?php print $username; ?>"></label>
<label>Email: <input type="text" name="email" value="<?php print $email; ?>"></label>
<!-- etc -->
<button type="submit" name="submit">Send Message</button>
</form>
For ease and management, you can put the PHP code above into a separate file to be included.
The problem your sample above is that although you do redirect to a new page on success, you don’t go anywhere otherwise.
If you want to do it with a separate processing script, you will need to conclude by redirecting back to the original form on failure. However, you will find that persisting old data is more difficult that way.

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

Trying To Create A Javascript Alert Window That Doesn't Reload The Page When OK Is Clicked

I have a PHP form that I've set up with a POST method. When all the fields aren't filled out I have a Javascript alert box that pops up and states 'Please fill out all fields!' When I click 'OK' on the alert window it reloads the form behind it clearing all the data that was entered. Is there a function that can keep the alert box's OK button from reloading the entire page? Here's my code:
<?php
if (isset($_POST['brandname']) && isset($_POST['firstname']) && isset($_POST['lastname']) && isset($_POST['email']) && isset($_POST['website'])){
$brandname = $_POST['brandname'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$website = $_POST['website'];
if(!empty($brandname) && !empty($firstname) && !empty($lastname) && !empty($email)){
$to = 'matt#miller-media.com';
$subject = 'Submission Form';
$body = $firstname;
$headers = 'From: '.$email;
if (#mail($to, $subject, $body, $headers)){
}
}else{
echo '<script type="text/javascript">
window.alert("Please fill out all fields!")
</script>';
}
}
?>
You are alerting your user after posting response ... in this case I would re-post the whole form again with its values set to $_POST or variables that were set using it, for example :
<input type='text' name='brandname' value='<?php echo $_POST['brandname'];?>' />
or :
<input type='text' name='brandname' value='<?php echo $brandname; ?>' />
and so on
But in this case I recommend using client-side validation on the form (Using javascript)
Yeah i assume you need something like this:
<script type="text/javascript">
function do_some_validation(form) {
// Check fields
if (! /* Contition 1 */ ) return false;
if (! /* Contition 2 */ ) return false;
if (! /* Contition 3 */ ) return false;
form.submit();
}
</script>
<form onsubmit="do_some_validation(this) return false;" action="script.php" method="post">
// Fields
</form>
This will only submit the form once all JavaScript conditions in do_some_validation are met... Please note this is not advised over and above PHP validation, this should be used purely for comfort for the user not having to submit the page when there's something Javascript can validate against
For any further PHP validation messages, you can either pass variables into GET or SESSION, eg.
<?php
session_start();
if (count($_POST)) {
if (!/* Condition 1 */) $_SESSION['error'] = "Message";
if (!isset($_SESSION['error'])) {
// Proceed
} else header("Location: script.php");
}
?>
On the page:
<?php if (isset($_SESSION['errir'])) {
echo $_SESSION['error'];
unset($_SESSION['error']);
} ?>
Since your code sample is PHP-code, it seems that you are posting the form and validate it server-side, and then you show an alert if any field is empty? In that case, the page has already reloaded, before the alertbox is shown. You are mixing server-side and client-side code.
If you want to show an alert box if the user hasn't filled in all the fields (without reloading the page), you will have to do the validation with JavaScript. You should still keep your PHP-validation as well though!
If you use jQuery for instance, you could do something like this:
$("#your-form-id").submit(function(){
// Check all your fields here
if ($("#input-field-1").val() === "" || $("#input-field-2").val() === "")
{
alert("Please fill out all fields");
return false;
}
});
It can of course be done without jQuery as well. In that case you can use the onsubmit attribute of the form tag to call a JavaScript function when the form is posted, and within that function you do the validation of the form, show an alert box if any field is empty, and then return false from the function to prevent the form from being posted to the server.

Categories