Form submission is not displaying or executing - php

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.

Related

PHP single page form validation form not validating

Nothing happens when you click the submit button at the bottom of the page. I simply want it to validate user input and I am only focused on the name field at the moment and I cannot get it to validate any input in the name field. No error messages pop up or anything. Please review this and offer any suggestions, I cannot find my error.
PHP portion, where variables are initialized and set to empty. As well as the post methods and isset functions
<?php
//define variables and set them to empty values
$fname_error= $phone_error= $address1_error= $address2_error= $city_error= $state_error= $zipcode_error= "";
$fname= $phone= $address1= $address2= $city= $state= $zipcode= "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
$fname_error = "Missing";
}
else {
$fname = test_input($_POST["fname"]);
//now we check to see that the name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
$fname_error = "Please use letters and white space only";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
The Html portion:
<div class="userinput">
<label for="fname"><b>First Name</b></label>
<input type="text" name="fname" value="<?php
echo $fname ?>">
<span class="error">
<?php echo $fname_error;?></span>
</div>
Good day. This is just a hypothesis, I may be wrong as I couldn't check the entire code, but you cannot have more than 1 form on the same page. Because, you need a single opening and closing form tag that wraps ALL form elements on your page. Form fields are only counted as part of a form if they are contained within the form elements. And you do have more than 1 form on the same page.
Also, you should consider minimizing your code to only what's needed.
Hope this helps!!!

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

PHP Form must be submitted twice to update checkbox

I'm still relatively new to PHP. I'm trying to build a privacy settings page for members to opt out of automatic emails for triggered events (i.e. private message notification). I want the checkbox set automatically based on the database setting. As of now, the form does update the database correctly, but the checkbox status does not show the correct setting unless the Submit button is pressed twice, or the page is reloaded. Setting would be '0' for unchecked, '1' for checked. I'd love to use Ajax or jQuery to handle this, but I don't know those at all.
privacysettings.php
<?php
$id = "";
$pm_mail_able = "";
$pm_email = "";
if (isset($_GET['id'])) {
$id = preg_replace('#[^0-9]#i', '', $_GET['id']); // filter everything but numbers
} else if (isset($_SESSION['idx'])) {
$id = $logOptions_id;
} else {
header("location: index.php");
exit();
}
//query to get checkbox status
$sql = mysql_query("SELECT * FROM members WHERE id='$id'");
while($row = mysql_fetch_array($sql)){
$pm_mail_able = $row['pm_mail_able'];
}
switch ($pm_mail_able) {
case 0:
$pm_setting = NULL;
break;
case 1:
$pm_setting = "checked=\"checked\"";
break;
}
if(isset($_GET['pm_email']) && !empty($_GET['pm_email'])) {
$updateqry = mysql_query("UPDATE members SET pm_mail_able='1' WHERE id='$id'");
} else {
$updateqry = mysql_query("UPDATE members SET pm_mail_able='0' WHERE id='$id'");
}
?>
<html>
Email Notifications<br />
<form name="testform" method="get" action="PvResult.php">
When a friend sends me a private message
<input type="checkbox" name="pm_email" value="on"<?php echo $pm_setting;?> />
<br /><br />
<input type="submit" value="Submit" />
</form>
</html>
PvResult.php
<?php
$url = 'http://www.mywebsite.com';
//If the form isn't submitted, redirect to the form
if(!isset($_GET['Submit']))
header('Location: '.$url.'/privacysettings.php');
//Redirect to the correct location based on form input
$pm_email = $_GET['pm_email'];
$url .= '/privacysettings.php?pm_email='.$pm_email;
header('Location: '.$url);
?>
Okay, hopefully this won't just answer your question, but give you a few best practices you might want to consider.
You can combine these two scripts into one relatively easily. Also, I'd highly suggest using a POST instead of GET; GET is very limited and is not intended to submit data like you're using it. If you're going to be changing data in a back-end store, using GET will bite you. Maybe not today, maybe not tomorrow, but it will, trust me.
You really should consider moving to PDO instead of the mysql_ functions. PDO is a lot better in handling parameterized queries, which you really should have here for better security, and it's more portable if someday you want to move to a different database system.
I'm still a little hazy on how your app is getting the $id. Most apps get it from a $_SESSION variable, making sure that the user has successfully validated a login. If you're not doing that, please do. You might want to thoroughly digest this article, it's got a lot of juicy best practices regarding authentication and "remember me"-type functionality.
Here's a bit of a rewrite. I haven't actually tested it, but it should give you a pretty good idea on where to go with your immediate needs. If it throws any errors (remember the disclaimer: I haven't actually tested it!), let me know and I'll try to debug it.
<?php
$message = '';
$pm_setting = '';
$id = 0;
// Put your $id retrieval logic here. It should look something like:
if (isset($_SESSION['id'])) {
$id = $_SESSION['id'];
if (!preg_match('/^\\d{1,10}$/', $id) > 0) {
// Someone is trying to hack your site.
header("location: scum.php");
exit();
}
$id = intval($id);
}
// Quick security note: You might want to read up on a topic called
// session hijacking if you want to ensure your site is secure and
// this $id isn't spoofed.
if (isset($_POST['Submit'])) {
// The form is being submitted. We don't need to read the current
// pm_mail_able setting from the database because we're going to
// overwrite it anyway.
if ($id > 0) {
$pm_mail_able = 0;
if (isset($_POST['pm_email']) && $_POST['pm_email'] === 'on') {
$pm_mail_able = 1;
$pm_setting = 'checked ';
}
$query = 'UPDATE members SET pm_mail_able='.$pm_mail_able.
' WHERE id = '.$id;
mysql_query($query);
// Another quick security note: You REALLY need to consider
// updating to PDO so that you can bind these parameters
// instead. The mysql_ functions are probably going to be
// deprecated soon anyway.
if (mysql_affected_rows($query) > 0)
$message = '<p style="color: #00a000;">Settings saved!</p>';
else
$message = '<p style="color: #a00000;">User id not valid.</p>';
}
else
$message = '<p style="color: #a00000;">User id not valid.</p>';
}
else {
// This is the first load of the form, we need to just display it
// with the existing setting.
if ($id > 0) {
$query = mysql_query('SELECT * FROM members WHERE id = '.$id);
if (($row = mysql_fetch_array($query, MYSQL_ASSOC)) !== FALSE)
if ($row['pm_mail_able'] === 1) $pm_setting = 'checked ';
}
}
?>
<html>
<body>
<?= $message ?>
<!-- Without action parameter, form submitted to this script. -->
<form name="testform" method="post">
E-mail notifications<br />
<input type="checkbox" name="pm_email" value="on" <?= $pm_setting ?>/>
When a friend sends me a private message
<br /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Try to do these settings and see if it will work:
1) You need to add an space between "on" and "checked=checked"
<input type="checkbox" name="pm_email" value="on" <?php echo $pm_setting;?> />
2) You have to reference the submit button by its name, not its value
<input type="submit" name="Submit" value="Send" />
3) When the setting is "0", set $pm_setting as a empty string, instead of NULL
case 0:
$pm_setting = '';
4) Maybe there is some problem with $_GET['pm_email'] and the else is always being executed
5) If the things work when you press the Submit button twice, it means that the form is passing some GET var that make the code work, so try to discover what var is this

how to avoid Form Re submission in php

I have a form in dashboard.php to create invoice and this is submitted to invoice.php
Now my invoice.php inserts the Invoice and the customer into the database and then shows me a invoice order filling form.
if i refresh this page, it inserts a new invoice for the same customer, how do i avoid this.
I was reading that we could avoid it by redirection, but in my case how do i use it. Some thing like a PRG(post/redirect/get) how to use it?
Do i need to make an intermediate page before going to insert items to invoice
The pattern you've heard about is this: Post/Redirect/Get.
In general, POST is for actions, GET is for views. So you never show a user a page on a POST request. Instead, you redirect them to a page they'll request with GET, which will not cause any changes in your database.
after successful form submission do a redirect to the same page and optionally indicate that the submission was successful
Example: invoice.php
if (count($_POST)) {
if (/*post data is valid*/) {
/*do whatever is needed*/
header('Location: invoice.php?success');
}
} else if (isset($_GET['success'])) {
echo "Form successfuly submitted";
}
Let dashboard.php post the form data to insert.php, which will process the data and then forward to invoice.php. Use sessions to transport the data from one file to another. Here is insert.php:
<?php
session_start();
if (session_is_registered("invoiceVars"))
session_unregister("invoiceVars");
if (!session_is_registered("errors"))
session_register("errors");
$errors = array();
if (!session_is_registered("formVars"))
session_register("formVars");
foreach($_POST as $f_varname => $f_value)
$formVars[$varname] = trim(EscapeShellCmd(stripslashes($value)));
// process your data and write it to the database or return to dashboard.php with errors, then:
session_unregister("errors");
session_register("invoiceVars");
$invoiceVars = array();
foreach ($formVars as $i_varname => $i_value)
$invoiceVars[$i_varname] = $i_value;
session_unregister("formVars");
// add additional variables
$invoiceVars["coupon"] = 'unique_coupon_code';
// invoice.php will process the data and display it
// it has session_start(); at the top, to have $invoiceVars available
header('Location: invoice.php');
exit();
?>
header(); and exit(); will flush $_POST, so it is no longer available when the user hits back on his browser.
Here is an example code for you:
# database.php
$db = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
session_start();
# dashboard.php
require_once("database.php");
function getSavedValue() {
global $db;
$sql = "SELECT input_text FROM temp_table WHERE sess_key='?'";
$query = $db->prepare($sql);
$query->bindParam(session_id());
$query->execute();
if ($query->rowCount() == 1)
return $query->fetch();
else
return " ";
}
<form action="invoice.php" method="POST">
<input type="text" name="getThisInfo" value="<?php echo getSavedValue(); ?>"/>
<input type="submit" value="Send"/>
</form>
# invoice.php
if (isset($_POST["getThisInfo"]) && /* validation check */ 1) {
require_once("database.php");
$textInput = $_POST["getThisInfo"];
$sql = "INSERT INTO perm_table(invoice_info) VALUES('?');";
$query = $db->prepare($sql);
$query->bindParam($textInput);
$query->execute();
$rows = $query->rowCount();
echo "$rows invoices were inserted.";
unset($_POST["getThisInfo"]);
header("success.php");
} else {
header("dashboard.php");
}

Categories