Sanitize and send checkbox results in a form - php

I have a WordPress based website that includes a booking <form> on a 'Page Template'.
As I am unfamiliar with PHP, I'm not too sure exactly where I am going wrong.
I need to include some checkboxes for the services offered by the website in a <form> and have the following file to work with:
<?php
/*
* Template Name: Booking Page
*/
?>
<?php
// Sanitize data, or initialize if they don't exist.
$clientname = isset($_POST['ci_name']) ? esc_html(trim($_POST['ci_name'])) : '';
$email = isset($_POST['ci_email']) ? esc_html(trim($_POST['ci_email'])) : '';
$services = isset($_POST['services']) ? esc_html(trim(implode(",", $_POST['services']))) : ''; // My Edit
$message = isset($_POST['ci_comments']) ? sanitize_text_field(stripslashes($_POST['ci_comments'])) : '';
$errorString = '';
$emailSent = false;
if(isset($_POST['send_booking']))
{
// We are here because the form was submitted. Let's validate!
if(empty($clientname) or mb_strlen($clientname) < 2)
$errorString .= '<li><i class="fa fa-times"></i> '.__('Your name is required.', 'ci_theme').'</li>';
if(empty($email) or !is_email($email))
$errorString .= '<li><i class="fa fa-times"></i> '.__('A valid email is required.', 'ci_theme').'</li>';
// Services is optional, so, no check. // My Edit
// Message is optional, so, no check.
// Alright, lets send the email already!
if(empty($errorString))
{
$mailbody = __("Name:", 'ci_theme') . " " . $clientname . "\n";
$mailbody .= __("Email:", 'ci_theme') . " " . $email . "\n";
$mailbody .= __("Services Selected:", 'ci_theme') . " " . $services . "\n"; // My Edit
$mailbody .= __("Message:", 'ci_theme') . " " . $message . "\n";
// If you want to receive the email using the address of the sender, comment the next $emailSent = ... line
// and uncomment the one after it.
// Keep in mind the following comment from the wp_mail() function source:
/* If we don't have an email from the input headers default to wordpress#$sitename
* Some hosts will block outgoing mail from this address if it doesn't exist but
* there's no easy alternative. Defaulting to admin_email might appear to be another
* option but some hosts may refuse to relay mail from an unknown domain. See
* http://trac.wordpress.org/ticket/5007.
*/
$emailSent = wp_mail(ci_setting('booking_form_email'), get_option('blogname').' - '. __('Booking form', 'ci_theme'), $mailbody);
//$emailSent = wp_mail(ci_setting('contact_form_email'), get_option('blogname').' - '. __('Contact form', 'ci_theme'), $mailbody, 'From: "'.$clientname.'" <'.$email.'>');
}
}
?>
<?php get_header(); ?>
<main id="main">
<div class="container">
<div class="row">
<div class="col-lg-10 col-lg-offset-1">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<h2 class="page-title"><?php the_title(); ?></h2>
<div class="row">
<div class="col-sm-8">
<article <?php post_class('entry'); ?>>
<?php if(!empty($errorString)): ?>
<ul id="formerrors">
<?php echo $errorString; ?>
</ul>
<?php endif; ?>
<?php if($emailSent===true): ?>
<p id="formsuccess"><i class="fa fa-check"></i> <?php _e('Your booking request has been sent. We will contact you as soon as possible.', 'ci_theme'); ?></p>
<?php elseif($emailSent===false and isset($_POST['send_booking']) and $errorString==''): ?>
<p id="sendfail"><?php _e('There was a problem while sending the email. Please try again later.', 'ci_theme'); ?></p>
<?php endif; ?>
<?php the_content(); ?>
<?php if( !isset($_POST['send_booking']) or (isset($_POST['send_booking']) and !empty($errorString)) ): ?>
<form class="booking" action="<?php the_permalink(); ?>" method="post">
<div class="row">
<div class="col-md-6">
<input type="text" name="ci_name" id="ci_name" placeholder="<?php _e('your name', 'ci_theme'); ?>" value="<?php echo esc_attr($clientname); ?>">
</div>
<div class="col-md-6">
<input type="email" name="ci_email" id="ci_email" class="datepicker" placeholder="<?php _e('Your Email', 'ci_theme'); ?>" value="<?php echo esc_attr($email); ?>">
</div>
</div>
<!-- My Edits -->
<div class="row">
<div class="col-md-12">
<hr />
<p>Please tick any of the following services if you would like to include them in your package:</p>
</div>
<div class="col-md-6">
<p><input type="checkbox" name="services[]" <?php checked($services, 'Reiki'); ?> value="Reiki"> Reiki</p>
<p><input type="checkbox" name="services[]" <?php checked($services, 'Private Personal Training'); ?> value="Private Personal Training"> Private Personal Training</p>
<p><input type="checkbox" name="services[]" <?php checked($services, 'Walking'); ?> value="Walking"> Walking</p>
<p><input type="checkbox" name="services[]" <?php checked($services, 'Boot Camp'); ?> value="Boot Camp"> Boot Camp</p>
</div>
<div class="col-md-6">
<p><input type="checkbox" name="services[]" <?php checked($services, 'Relaxation Massage'); ?> value="Relaxation Massage"> Relaxation Massage</p>
<p><input type="checkbox" name="services[]" <?php checked($services, 'Meditation Circle'); ?> value="Meditation Circle"> Meditation Circle</p>
<p><input type="checkbox" name="services[]" <?php checked($services, 'Colour Workshop'); ?> value="Colour Workshop"> Colour Workshop</p>
</div>
</div>
<!-- End My Edits -->
<div class="row">
<div class="col-md-12">
<textarea name="ci_comments" id="ci_comments" cols="30" rows="10" placeholder="<?php _e('Message', 'ci_theme'); ?>"></textarea>
<button type="submit" name="send_booking"><?php _e('Submit', 'ci_theme'); ?></button>
</div>
</div>
</form>
<?php endif; ?>
</article>
</div>
<?php endwhile; endif; ?>
<?php get_sidebar(); ?>
</div>
</div>
</div>
</div>
</main>
<?php get_footer(); ?>
In the code above, I have placed the HTML markup for the checkboxes in, and it appears something similar to this on the front-end of the website:
However, it doesn't seem to include the checkbox information in the email that is sent off. The email for this simply reads Services Selected: without the names of the services ticked:
My edits which can be found in the code above are:
Sanitize:
$services = isset($_POST['services']) ? esc_html(trim(implode(",", $_POST['services']))) : '';
Message to be sent:
$mailbody .= __("Services Selected:", 'ci_theme') . " " . $services . "\n";
Checkboxes:
<input type="checkbox" name="services[]" <?php checked($services, 'Relaxation Massage'); ?> value="Relaxation Massage"> Relaxation Massage
How do I implement, sanitize, send and receive the results of the checkboxes using the <form> I currently have?
Any help would be greatly appreciated,
Thanks.

You didn't store any value in your $service variable.
Just put this code
$clientname = isset($_POST['ci_name']) ? esc_html(trim($_POST['ci_name'])) : '';
$email = isset($_POST['ci_email']) ? esc_html(trim($_POST['ci_email'])) : '';
$services = isset($_POST['services']) ? esc_html(trim(implode(",", $_POST['services']))) : ''; // My Edit
$message = isset($_POST['ci_comments']) ? sanitize_text_field(stripslashes($_POST['ci_comments'])) : '';
$errorString = '';
$emailSent = false;
if(isset($_POST['send_booking']))
{
print_r($_POST);exit; // You can see here your post variable value in array.
}
Instead of
$services = isset($_POST['services']); // My Edit
Read more about the ternary operator: http://php.net/ma...operators.comparison.php

Related

I'm struggling with integrating recaptcha in multipage form

Background info:
I have made a test form containing multiple pages. When recaptcha isn't intergrated I receive the info in my database. But when trying to integrate recaptcha (checkbox v2) it keeps failing and the info isn't sent to the database no more. I have tried to intergrate recaptcha on page2.php because it's the last page of the form the user has to fill in. I left my recaptcha keys in because it's just made as test.
Question:
How can I make it work? How can I integrate recaptch in a correct way?
Thanks!
The included pages are:
footer.php
<!-- Bootstrap Javascript-->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script>function goBack() {window.history.back();}</script>
<!-- recaptcha -->
<script src='https://www.google.com/recaptcha/api.js'></script>
</body>
</html>
header.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('config.php');
require_once('functions.php');
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Multi-Page Form</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<!-- recaptcha -->
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container">
</div>
</nav>
index.php
<?php include_once('header.php'); ?>
<section id="form">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="form-container">
<h3 class="heading">Questionnaire</h3>
<p> Beste user,</p>
<p> Please fill in form A or B</p>
<br>
<p>Form A</p>
<br>
<p>Form B</p>
</div>
</div>
</div>
</div>
<section>
<?php include_once('footer.php'); ?>
page1.php
<?php include_once('header.php');?>
<section id="form">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="form-container">
<h3 class="heading">Step 1/2</h3>
<form action="page2.php" method="post">
<?php
echo "<br>";
email('Email', 'Email', '<b>Email</b>', ' ');
echo "<br>";
text('Firstname', 'Firstname', '<b>Firstname</b>', ' ');
echo "<br>";
?>
<br>
<br>
<center>
<div class="btn-group">
<button class="btn btn-dark" onclick="goBack()">« Go back</button>
<button class="btn btn-dark" type="reset" value="reset">Reset</button>
<button class="btn btn-dark" type="submit">Continue »</button>
</div>
</center>
</form>
</div>
</div>
</div>
</div>
<section>
<?php include_once('footer.php'); ?>
page2.php
<?php
include_once('header.php');
// Store data from page 1 in SESSION
if ( ! empty( $_POST ) ) {
$_SESSION['Email'] = $_POST['Email'];
$_SESSION['Firstname'] = $_POST['Firstname'];
}
// recaptcha
$public_key = "6LdojMIUAAAAAH8uQNeM8lW5pmP_T_NlWlb5_-9S";
$private_key = "6LdojMIUAAAAALhEfrQFR3jExbPLubKjys6CZL_9";
$url = "https://www.google.com/recaptcha/api/siteverify";
?>
<section id="form">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="form-container">
<h3 class="heading">Step 2/2</h3>
<form action="page3.php" method="post">
<?php
// choices for checkbox
$options = array(
'No ' => 'No ',
'Neutral ' => 'Neutral ',
'Yes ' => 'Yes ',
);
// choices for checkbox2
$options2 = array(
'Internet ' => 'Internet ',
'Friends ' => 'Friends ',
'Work ' => 'Work ',
'Other' => 'Other' ,
);
echo "<br>";
checkbox2( 'Info_media', 'Info_media', '<b>How do you know this?</b>', $options2 );
echo "<br>";
text_non_required('Other', 'Other', 'Explain "Other"?', ' ');
echo "<br>";
checkbox( 'Question_1', 'Question_1', '<b>Do you agree with the answer?</b>', $options );
echo "<br>";
text('Remark', 'Remark', 'Do you have remarks?', ' ');
?>
<br>
<br>
<center>
<!-- recaptcha -->
<div class="g-recaptcha" data-sitekey="<?php print $public_key; ?>"></div>
<br>
<div class="btn-group">
<button class="btn btn-dark" onclick="goBack()">« Go back</button>
<button class="btn btn-dark" type="reset" value="reset">Reset</button>
<button class="btn btn-dark" name="submit_form" type="submit">Continue »</button>
<!-- recaptcha -->
<?php
/* Check if the form has been submitted */
if(array_key_exists('submit_form',$_POST))
{
$response_key = $_POST['g-recaptcha-response'];
$response = file_get_contents($url.'?secret='.$private_key.'&response='.$response_key.'&remoteip='.$_SERVER['REMOTE_ADDR']);
/* json decode the response to an object */
$response = json_decode($response);
/* if success */
if($response->success == 1)
{
header("Location: http://localhost/recaptcha_test/page3.php");
}
else
{
echo "You are a robot.";
}
}
?>
</div>
</center>
</form>
</div>
</div>
</div>
</div>
<section>
<?php include_once('footer.php'); ?>
page3.php
<?php
include_once('header.php');
// Store data in session
if ( ! empty( $_POST ) ) {
$_SESSION['Info_media'] = $_POST['Info_media'];
$_SESSION['Other'] = $_POST['Other'];
$_SESSION['Question_1'] = $_POST['Question_1'];
$_SESSION['Remark'] = $_POST['Remark'];
}
?>
<section id="form">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="form-container">
<h3 class="heading">You are done.</h3>
<br>
<br>
<center>Thank you.</center>
<br>
<?php
whitelist_convert_send ();
?>
</div>
</div>
</div>
</div>
<section>
<?php include_once('footer.php'); ?>
functions.php
<?php
function __($text) {
return htmlspecialchars($text, ENT_COMPAT);
}
function checked($value, $array) {
if ( in_array( $value, $array ) ) {
echo 'checked="checked"';
}
}
function text( $name, $id, $label, $placeholder, $type = 'text' ) {?>
<div class="form-group">
<label for="<?php echo $id; ?>"><?php echo $label; ?></label>
<input type="<?php echo $type; ?>" required name="<?php echo $name; ?>" class="form-control"
id="<?php echo $id; ?>" placeholder="<?php echo $placeholder; ?>"
value="<?php echo isset($_SESSION[$name]) ? __($_SESSION[$name]) : ''; ?>">
</div>
<?php }
function text_non_required( $name, $id, $label, $placeholder, $type = 'text' ) {?>
<div class="form-group">
<label for="<?php echo $id; ?>"><?php echo $label; ?></label>
<input type="<?php echo $type; ?>" name="<?php echo $name; ?>" class="form-control"
id="<?php echo $id; ?>" placeholder="<?php echo $placeholder; ?>"
value="<?php echo isset($_SESSION[$name]) ? __($_SESSION[$name]) : ''; ?>">
</div>
<?php }
function email( $name, $id, $label, $placeholder, $type = 'email' ) {?>
<div class="form-group">
<label for="<?php echo $id; ?>"><?php echo $label; ?></label>
<input type="<?php echo $type; ?>" required name="<?php echo $name; ?>" class="form-control"
id="<?php echo $id; ?>" placeholder="<?php echo $placeholder; ?>"
value="<?php echo isset($_SESSION[$name]) ? __($_SESSION[$name]) : ''; ?>">
</div>
<?php }
function checkbox( $name, $id, $label, $options = array() ) {?>
<div class="form-group">
<p><?php echo $label; ?></p>
<?php foreach ($options as $value => $title ) : ?>
<label class="checkbox-inline" for="<?php echo $id; ?>">
<input type="radio" required name="<?php echo $name; ?>[]" value="<?php echo $value; ?>" <?php isset($_SESSION[$id]) ? checked($value, $_SESSION[$id]) : ''; ?>>
<span class="checkbox-title"><?php echo $title; ?></span>
</label>
<?php endforeach; ?>
</div>
<?php }
function checkbox2 ($name, $id, $label, $options2 = array() ) {?>
<div class="form-group">
<p><?php echo $label; ?></p>
<?php foreach ($options2 as $value => $title) :
?>
<label class="checkbox-inline" for="<?php echo $id; ?>">
<input type="radio" required name="<?php echo $name; ?>[]"
value="<?php echo $value; ?>"
<?php isset($_SESSION[$id]) ? checked($value, $_SESSION[$id]) : ''; ?>
>
<span class="checkbox-title"><?php echo $title; ?></span>
</label>
<?php endforeach; ?>
</div>
<?php
}
function whitelist_convert_send () {
//globalise variables
global $Email;
global $Firstname;
global $Info_media;
global $Other;
global $Question_1;
global $Remark;
global $MCQ_0;
global $MCQ_1;
// Whitelist
$Email = $_SESSION['Email'];
$Firstname = $_SESSION['Firstname'];
$Info_media = $_SESSION['Info_media'];
$Other = $_SESSION['Other'];
$Question_1 = $_SESSION['Question_1'];
$Remark = $_SESSION['Remark'];
// arrays to value in string for performing statistics
foreach ($Info_media as $value) {
$MCQ_0 = $value;}
foreach ($Question_1 as $value) {
$MCQ_1 = $value;}
// Connectie database (naam server, gebruikersnaam, wachtwoord, naam database)
$conn = new mysqli('localhost', 'root', '', 'Wolf');
/*Testing databaseconnection
if ($conn){
echo "we are connected";}
else {
die ('database connection failed');} */
if (!$conn){ die ('database connection failed' . msqli_error ());}
$stmt = $conn->prepare("INSERT INTO test_database (Email, Firstname, Info_media, Other, Question_1, Remark) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->bind_param("ssssss", $Email, $Firstname, $MCQ_0, $Other, $MCQ_1, $Remark);
// Execute
$insert = $stmt->execute();
// Einde sessie
session_destroy();
}
You probably misunderstood how recaptcha is working.
You integrate the recaptcha code (js + div) in your form
On the result page you check if the captcha check was sucessful (php)
Currently you are doing both things in page2.php. When this page is loading, it checks if recaptcha was successful, but the recaptcha was not even included and the user didn't had the opportunity to solve it yet :-)
So you should integrate it in page1 and check it in page2.
page1.php
Integrate the recaptcha div in your form
<form action="page2.php" method="post">
<div class="g-recaptcha" data-sitekey="6LdojMIUAAAAAH8uQNeM8lW5pmP_T_NlWlb5_-9S"></div>
<?php
echo "<br>";
email('Email', 'Email', '<b>Email</b>', ' ');
...
ofc you can integrate the site key with php too (like you have done it on page2.php) or change the position inside the form
page2.php
Remove the recaptcha div from this page.
The recaptcha success check should be somewhere in the beginning of this page. You should render the whole form only when $response->success == 1 succeed (see the attached code). This probably requires some additional restructuring of page2.php
<?php
//recaptcha check
$response_key = "";
//get submitted recaptcha "user response" from last page
if(array_key_exists('g-recaptcha-response',$_POST)){
$response_key = $_POST['g-recaptcha-response'];
}
$response = file_get_contents($url.'?secret='.$private_key.'&response='.$response_key.'&remoteip='.$_SERVER['REMOTE_ADDR']);
/* json decode the response to an object */
$response = json_decode($response);
if($response->success == 1){
//render form from page 2
?>
<form action="page3.php" method="post">
...
<?php
}
else{
echo "You are a robot.";
//
}
?>
As an alternative you could integrate recaptcha in page2.php and check the result in page3.php - it just depends in which step you want the recaptcha checkbox

Unable to connect the Database and Handle the POST request

Hello I am working with a predefined template and I am trying to fetch some data from the input space in form of POST/GET request using php. But I am unable to do so, How can I integrate the database and handle the php parameters?
<div class="w3_agileits_card_number_grids">
<div class="w3_agileits_card_number_grid_left">
<div class="controls">
<input type="text" placeholder="Adhaar" name="Adhaar" required="">
</div>
</div>
<div class="controls">
<input type="text" placeholder="Town/City" name="city" required="">
<?php
if(isset($_GET['Adhaar']) && $_GET ['Adhaar']!=NULL)
{
$x = $_GET['Adhaar'];
echo "Your Adhaar is $x";
?>
}
Hello change your code to this
<div class="w3_agileits_card_number_grids">
<div class="w3_agileits_card_number_grid_left">
<div class="controls">
<input type="text" placeholder="Adhaar" name="Adhaar" required="">
</div>
</div>
<div class="controls">
<input type="text" placeholder="Town/City" name="city" required="">
<?php
if(isset($_GET['Adhaar']) && $_GET ['Adhaar']!=NULL)
{
$x = $_GET['Adhaar'];
echo "Your Adhaar is $x";
//Connect to the database here
}
?>
</div>
</div>
For the database connection it depends on which database you are working with but you can start here. A simple Google query with provide you what you are looking for
I put together an example for you that may come in handy. This shows how you can use PHP to submit a form print some values that the user enters on the page. I also included some commented out code that you can copy and move to a seperate script and call by changing the action value to the file path.
The PHP script:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// try {
// Connect to the database:
// $db = mysqli_connect('localhost', 'username', 'password', 'database','port');
// Retrieve all records:
// $sql = 'SELECT * FROM categories';
// $result = $db->query($sql);
// } catch (Exception $e) {
// $error = $e->getMessage();
// }
// echo '<pre>';
// Pass MYSQLI_BOTH or MYSQLI_ASSOC as the argument to change the array type
// $all = $result->fetch_all();
// echo json_encode($all);
// echo '</pre>';
// $db->close();
$data = [
"BOB" => "AWESOME",
"JOE" => "AVERAGE",
"TOM" => "COOL"
];
}
?>
Next, we have the form. I added this form because you need it to submit to the page. (Well you don't "need" it but it makes life easy.)
<div class="container">
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="POST">
<div class="form-group">
<input class="form-control"
type="text"
placeholder="Adhaar"
name="adhaar"
required
value="<?= isset($_POST['adhaar']) ? $_POST['adhaar'] : '' ?>">
</div>
<div class="form-group">
<input class="form-control"
type="text"
placeholder="Town/City"
name="city"
required
value="<?= isset($_POST['city']) ? $_POST['city'] : '' ?>">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">CLICK ME!</button>
</div>
</form>
<?php if (isset($_POST['adhaar'])) : ?>
<p>Hi there <?= $_POST['adhaar'] ?></p>
<?php endif ?>
<?php if (isset($_POST['city'])) : ?>
<p><?= $_POST['city'] ?> is a great place to live!</p>
<?php endif ?>
<?php if (isset($data)) : ?>
<?php foreach ($data as $key => $value) : ?>
<p><?= $key ?> - <?= $value ?></p>
<?php endforeach ?>
<?php endif ?>
</div>
Last piece of the file simply outputs information onto the page if it finds it in the $_POST global array.
<?php if (isset($_POST['adhaar'])) : ?>
<p>Hi there <?= $_POST['adhaar'] ?></p>
<?php endif ?>
<?php if (isset($_POST['city'])) : ?>
<p><?= $_POST['city'] ?> is a great place to live!</p>
<?php endif ?>
<?php if (isset($data)) : ?>
<?php foreach ($data as $key => $value) : ?>
<p><?= $key ?> - <?= $value ?></p>
<?php endforeach ?>
<?php endif ?>
This commented out part here you can use to pull data from the database and pass it back to your page. If you are just starting it's cool to tinker but ideally you DO NOT want to make calls to the db on the same page as your view. It should live in it's own file.
// try {
// Connect to the database:
// $db = mysqli_connect('localhost', 'username', 'password', 'database','port');
// Retrieve all records:
// $sql = 'SELECT * FROM categories';
// $result = $db->query($sql);
// } catch (Exception $e) {
// $error = $e->getMessage();
// }
// echo '<pre>';
// Pass MYSQLI_BOTH or MYSQLI_ASSOC as the argument to change the array type
// $all = $result->fetch_all();
// echo json_encode($all);
// echo '</pre>';
// $db->close();
You should Try This Code ..This is working i Simply add a submit button to it
<div class="w3_agileits_card_number_grids">
<div class="w3_agileits_card_number_grid_left">
<div class="controls">
<form method="GET" action="xxx.php">
<input type="text" placeholder="Adhaar" name="Adhaar" required="" />
</div>
</div>
<div class="controls">
<input type="text" placeholder="Town/City" name="city" required="" />
<input type="submit" name="submit" value="show">
<?php
if(isset($_GET['submit']) && $_GET ['Adhaar']!=NULL)
{
$x = $_GET['Adhaar'];
echo "Your Adhaar is $x";
//Connect to the database here
}
?>
</div>
</form>
</div>

Where the heck do I put reCaptcha php on MY existing form?

I'm trying to implement reCaptcha into my existing contact form, and have hit a snag with where exactly (notice I used the word exactly) to place the server side PHP code within my page.
I've added the required PHP within the form with correct public key (and added the private key to the server side PHP).
I have the validation PHP for the form at the top of the same page as the form is on.
Existing validation code as follows:
<?php
// Set email variables
$email_to = 'myemailishere';
$email_subject = 'MY Enquiry TITLE IS HERE';
// Set required fields
$required_fields = array('fullname','email','comment');
// set error messages
$error_messages = array(
'fullname' => 'Please enter your Name.',
'email' => 'Please enter a valid Email.',
'comment' => 'Please enter a Message.'
);
// Set form status
$form_complete = FALSE;
// configure validation array
$validation = array();
// check form submittal
if(!empty($_POST)) {
// Sanitise POST array
foreach($_POST as $key => $value) $_POST[$key] = remove_email_injection(trim($value));
// Loop into required fields and make sure they match our needs
foreach($required_fields as $field) {
// the field has been submitted?
if(!array_key_exists($field, $_POST)) array_push($validation, $field);
// check there is information in the field?
if($_POST[$field] == '') array_push($validation, $field);
// validate the email address supplied
if($field == 'email') if(!validate_email_address($_POST[$field])) array_push($validation, $field);
}
// basic validation result
if(count($validation) == 0) {
// Prepare our content string
$email_content = 'New Website Comment: ' . "\n\n";
// simple email content
foreach($_POST as $key => $value) {
if($key != 'submit') $email_content .= $key . ': ' . $value . "\n";
}
// if validation passed ok then send the email
mail($email_to, $email_subject, $email_content);
// Update form switch
$form_complete = TRUE;
}
}
function validate_email_address($email = FALSE) {
return (preg_match('/^[^#\s]+#([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? TRUE : FALSE;
}
function remove_email_injection($field = FALSE) {
return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field));
}
?>
And my Form code is this:
<div id="mainform">
<?php if($form_complete === FALSE): ?>
<form autocomplete="off" action="index.php#contact" method="post" id="comments_form">
<div class="row">
<div class="label">Your full name</div><!---end label--->
<div class="input">
<input type="text" id="fullname" class="detail" name="fullname" value="<?php echo isset($_POST['fullname'])? $_POST['fullname'] : ''; ?>" /><?php if(in_array('fullname', $validation)): ?><span class="error"><?php echo $error_messages['fullname']; ?></span><?php endif; ?>
</div><!---end input--->
</div><!---end row--->
<div class="row">
<div class="label">Your email address</div><!---end label--->
<div class="input">
<input type="text" id="email" class="detail" name="email" value="<?php echo isset($_POST['email'])? $_POST['email'] : ''; ?>" /><?php if(in_array('email', $validation)): ?><span class="error"><?php echo $error_messages['email']; ?></span><?php endif; ?>
</div><!---end input--->
</div><!---end row--->
<div class="row">
<div class="label">Your number? (if you'd like a call)</div><!---end label--->
<div class="input">
<input type="text" id="telephone" class="detail" name="telephone" value="<?php echo isset($_POST['telephone'])? $_POST['telephone'] : ''; ?>" />
</div><!---end input--->
</div><!---end row--->
<div class="row">
<div class="label">Your message</div><!---end label--->
<div class="input">
<textarea id="comment" name="comment" class="mess"><?php echo isset($_POST['comment'])? $_POST['comment'] : ''; ?></textarea><?php if(in_array('comment', $validation)): ?><span class="error"><?php echo $error_messages['comment']; ?></span><?php endif; ?>
</div><!---end input--->
</div><!---end row--->
<div class="row">
<div class="label">Prove you're Human</div><!---end label--->
<?php
require_once('recaptchalib.php');
$publickey = "your_public_key"; // public key omitted for purpose of stackeroverflow
echo recaptcha_get_html($publickey);
?>
</div><!---end row--->
<div class="submit">
<input type="submit" id="submit" name="submit" value="SEND MESSAGE" />
</div><!---end submit--->
</form>
<?php else: ?>
<p>Thank you, we've received your message.</p>
<?php endif; ?>
</div><!---end mainform--->
So...where do I stick this code (as in integrate the code into my existing validation php)?????:
<?php
require_once('recaptchalib.php');
$privatekey = "your_private_key";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
} else {
// Your code here to handle a successful verification
}
?>
Hope that makes sense and someone can help?

Include from displayed file or folder that contains

When using php do you set your path in reference to the files directory or from the page it is displayed from.
For example:
index.php is the home page of course
Directory structure.
index.php
includes > footer.php, header.php
product > product.php [blueproduct] > blueproduct.php
storescripts > connect_to_mysql.php, more.php
=================================================
Inside of footer I have a script that is not working on every page. Its a newsletter script to collect info. This is the code I'm using within my included footer.php:
</div>
<div class="footer">
<div class="wideNewsletter">
<div class="wrapNewsletter">
<div class="newsletterIntro"><b>NEWSLETTER SIGN UP</b></div>
<div class="newsletterForm">
<?php
$name = "";
$email = "";
$msg_to_user = "";
if ($_POST['name'] != "") {
include "../storescripts/connect_to_mysql.php";
// Be sure to filter this data to deter SQL injection, filter before querying database
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$sql = mysql_query("SELECT * FROM newsletter WHERE email='$email'");
$numRows = mysql_num_rows($sql);
if (!$email) {
$msg_to_user = '<div class="warning"><ul><li>Please type an email address ' . $name . '.</li></ul></div><br /><br />';
} else if ($numRows > 0) {
$msg_to_user = '<div class="warning"><ul><li>' . $email . ' is already in the system.</li></ul></div><br /><br />';
} else {
$sql_insert = mysql_query("INSERT INTO newsletter (name, email, dateTime)
VALUES('$name','$email',now() )") or die (mysql_error());
$msg_to_user = '<div class="success"><ul><li>Thanks ' . $name . ', hope you find what you want!</li></ul></div><br /><br />';
$name = "";
$email = "";
}
$message = 'Name: ' . $_POST['name'] . ' Email: ' . $_POST['email'];
mail('newproducts#moniquetrinidadjewelry.com', 'New Newsletter Sign Up at Monique Trinidad Jewelry', $message);
}
?>
<form style="width:430px;" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<fieldset style="text-align:left;padding:0px;border:0px;">
Name:
<input name="name" type="text" maxlength="36" value="<?php echo $name; ?>" />
Email:
<input name="email" type="text" maxlength="36" value="<?php echo $email; ?>" />
<input type="image" src="https://www.moniquetrinidadjewelry.com/images/new-images/green-bullet.png" border="0" name="mySubmitBtn" type="submit" value="Submit">
</fieldset>
</form></div>
<div style="position:absolute;top:120px;"><?php echo $msg_to_user; ?></div>
<div class="newsletterExplain">Receive product updates. Remember only one of each!</div>
</div>
</div><!--wide newletter end-->
<div class="wrapFooter">
<div class="tearOneFooter">
<div class="footerColumnList">
<div class="footerTitles">Connect With Us</div>
<div class="footerLists">
<ul>
<li>Connect With Monique!</li>
</ul>
</div>
</div>
<!--Seperate Connect With us Column from Information Column-->
<div class="footerColumnList">
<div class="footerTitles">Information</div>
<div class="footerLists">
<ul>
<li>About Us</li>
<li>Packaging</li>
<li>Terms & Conditions</li>
</ul>
</div>
</div>
<!--Seperate Information Column from Shipping and Returns Column-->
<div class="footerColumnList">
<div class="footerTitles">Shipping and Returns</div>
<div class="footerLists">
<ul>
<li><a href="https://www.moniquetrinidadjewelry.com/return-policy.php">Orders and Returns<a/></li>
<li>Secure Shopping</li>
<li></li>
</ul>
</div>
</div>
<!--Seperate Shipping and Returns Column from Services & Support Column-->
<div class="footerColumnList">
<div class="footerTitles">Hours Of Operation</div>
<div class="footerLists">
<ul>
<li>We are a 24/7 <br />Online Establishment!<br />(US Based)</li>
</ul>
</div>
</div>
<!--Seperate Connect With us Column from Information Column-->
</div>
<!--Beging SecondTearFooterArea-->
<div class="tearTwoFooter">
<!--<div class="signUpNewsLetter"><img src="https://www.moniquetrinidadjewelry.com/images/news_letter_temp_IMG.png" alt="newsletter" /></div>-->
<div class="paymentOptions"><img src="https://www.moniquetrinidadjewelry.com/images/payment_options_temp.png" alt="payment options" /></div>
<div class="twitter"><img src="https://www.moniquetrinidadjewelry.com/images/twitter_temp.png" alt="twitterLink" /></div>
</div>
</div>
</div>
</div>
This is working within the [blueproduct] directory from the product directory, but not the index.php.
I have another issue as well, but I believe better practice would be to open another question after I've done research on the issue correct? If not let me know and I'll edit this original message.
================================================================================
Edits and Additions Below
I have everything configured and I believe I can elminiate this as the issue. I'm really stumped on this one. The link to give you a better idea of what I mean is http://www.moniquetrinidadjewerly.com . If you go there and try the form it doesn't process, but that same form if you select 'necklace' within the navigation you can see works fine and runs correctly. Here is the updated footer.php file below to include changes for abs path.
</div>
<div class="footer">
<div class="wideNewsletter">
<div class="wrapNewsletter">
<div class="newsletterIntro"><b>NEWSLETTER SIGN UP</b></div>
<div class="newsletterForm">
<?php
$name = "";
$email = "";
$msg_to_user = "";
if ($_POST['name'] != "") {
include_once(DOC-ROOT."/storescripts/connect_to_mysql.php");
// Be sure to filter this data to deter SQL injection, filter before querying database
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$sql = mysql_query("SELECT * FROM newsletter WHERE email='$email'");
$numRows = mysql_num_rows($sql);
if (!$email) {
$msg_to_user = '<div class="warning"><ul><li>Please type an email address ' . $name . '.</li></ul></div><br /><br />';
} else if ($numRows > 0) {
$msg_to_user = '<div class="warning"><ul><li>' . $email . ' is already in the system.</li></ul></div><br /><br />';
} else {
$sql_insert = mysql_query("INSERT INTO newsletter (name, email, dateTime)
VALUES('$name','$email',now() )") or die (mysql_error());
$msg_to_user = '<div class="success"><ul><li>Thanks ' . $name . ', hope you find what you want!</li></ul></div><br /><br />';
$name = "";
$email = "";
}
$message = 'Name: ' . $_POST['name'] . ' Email: ' . $_POST['email'];
mail('newproducts#moniquetrinidadjewelry.com', 'New Newsletter Sign Up at Monique Trinidad Jewelry', $message);
}
?>
<form style="width:430px;" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<fieldset style="text-align:left;padding:0px;border:0px;">
Name:
<input name="name" type="text" maxlength="36" value="<?php echo $name; ?>" />
Email:
<input name="email" type="text" maxlength="36" value="<?php echo $email; ?>" />
<input type="image" src="https://www.moniquetrinidadjewelry.com/images/new-images/green-bullet.png" border="0" name="mySubmitBtn" type="submit" value="Submit">
</fieldset>
</form></div>
<div style="position:absolute;top:120px;"><?php echo $msg_to_user; ?></div>
<div class="newsletterExplain">Receive product updates. Remember only one of each!</div>
</div>
</div><!--wide newletter end-->
<div class="wrapFooter">
<div class="tearOneFooter">
<div class="footerColumnList">
<div class="footerTitles">Connect With Us</div>
<div class="footerLists">
<ul>
<li>Connect With Monique!</li>
</ul>
</div>
</div>
<!--Seperate Connect With us Column from Information Column-->
<div class="footerColumnList">
<div class="footerTitles">Information</div>
<div class="footerLists">
<ul>
<li>About Us</li>
<li>Packaging</li>
<li>Terms & Conditions</li>
</ul>
</div>
</div>
<!--Seperate Information Column from Shipping and Returns Column-->
<div class="footerColumnList">
<div class="footerTitles">Shipping and Returns</div>
<div class="footerLists">
<ul>
<li><a href="https://www.moniquetrinidadjewelry.com/return-policy.php">Orders and Returns<a/></li>
<li>Secure Shopping</li>
<li></li>
</ul>
</div>
</div>
<!--Seperate Shipping and Returns Column from Services & Support Column-->
<div class="footerColumnList">
<div class="footerTitles">Hours Of Operation</div>
<div class="footerLists">
<ul>
<li>We are a 24/7 <br />Online Establishment!<br />(US Based)</li>
</ul>
</div>
</div>
<!--Seperate Connect With us Column from Information Column-->
</div>
<!--Beging SecondTearFooterArea-->
<div class="tearTwoFooter">
<!--<div class="signUpNewsLetter"><img src="https://www.moniquetrinidadjewelry.com/images/news_letter_temp_IMG.png" alt="newsletter" /></div>-->
<div class="paymentOptions"><img src="https://www.moniquetrinidadjewelry.com/images/payment_options_temp.png" alt="payment options" /></div>
<div class="twitter"><img src="https://www.moniquetrinidadjewelry.com/images/twitter_temp.png" alt="twitterLink" /></div>
</div>
</div>
</div>
</div>
The config.inc.php file is located within the main directory and it reads :
<?php
define("Monique trinidad Jewelry","My Website");
define("DOC_ROOT","/home3/onlinfr7/public_html");
define("URL","https://www.moniquetrinidadjewelry.com");
?>
I'm not sure where the issue is occurring or what exactly is happening with the homepage(index.php) newsletter form in the footer. Why it works in one page, but not the other. It seems that path may not be the issue as I first thought. Any advice?
there's the current working directory, which you can get with getcwd(). THAT'S the path that everything will be relative to in any file operations you perform. By default it will be the directory that your main script is executed from.
Whether you go relative to that, or relative to something else, or just absolute on everything is up to you. There's no right/wrong answer - just whatever's easiest for YOU to maintain.
What I like to do that makes things easier when including other files is create a config file and include that in the main file or header like index.php
So this might be my config file called config.inc.php
<?php
define("SITENAME","My Website");
define("DOC_ROOT","/home/username/webroot");
define("URL","http://www.example.com");
?>
I include this config file in my index.php like
include("/home/username/webroot/config.inc.php");
Then I can use DOC_ROOT whenever I want to include another file somewhere and it will always have the full absolute path so that you know it's included.
e.g. include_once(DOC_ROOT."/storescripts/connect_to_mysql.php");

Contact form with math captcha

I've successfully created a contact form with php that gives the various required messages. Now I would like to add a simple random arithmetic captcha (non-image). See the anonymised (working) html form and existing (working, but without arithmetic captcha) php below.
The idea is to show "Incorrect answer" in the same way as the other error messages, or to pass to the Thankyou page for a correctly filled out form with correct answer. I've had a good go at this but can't quite get it to work. Any assistance much appreciated.
HTML:
<p>Area of interest:
<input type="radio" name="likeit" value="A" checked="checked" /> A
<input type="radio" name="likeit" value="B" /> B
<input type="radio" name="likeit" value="C" /> C</p>
<p>How did you hear about us?
<select name="how">
<option value=""> -- Please select -- </option>
<option>Recommendation</option>
<option>Internet</option>
<option>Advertisement</option>
<option>Other</option>
</select></p>
<p><strong>Your message subject:</strong><br /><input type="text" name="subject" size="35"/></p>
<p><strong>Your message:</strong><br />
<textarea name="comments" rows="10" cols="40"></textarea></p>
<p>Please answer the following arithmetic question: What is <?php echo $digit1;?> + <?php echo $digit2;?>?
<input name="captcha" type="text" size="2" id="captcha"/></p>
<p><input type="submit" value="Send" /></p>
</form>
PHP:
<?php
/* Contact form with arithmetic captcha */
$myemail = "enquiries#X.co.uk";
/* Check all form inputs using check_input function */
$yourname = check_input($_POST['yourname'], "Enter your name");
$email = check_input($_POST['email']);
$telephone = check_input($_POST['telephone']);
$website = check_input($_POST['website']);
$likeit = check_input($_POST['likeit']);
$how_find = check_input($_POST['how']);
$subject = check_input($_POST['subject'], "Add a subject");
$comments = check_input($_POST['comments'], "Add your message");
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("Email address is not valid");
}
/* If URL is not valid set $website to empty */
if (!preg_match("/^(https?:\/\/+[\w\-]+\.[\w\-]+)/i", $website))
{
$website = '';
}
/* Message for the email */
$message = "Hello!
Your contact form has been submitted by:
Name: $yourname
Email: $email
Telephone: $telephone
URL: $website
Area of interest? $likeit
How did they find us? $how_find
Comments:
$comments
End of message
";
/* Send the message using mail() function */
mail($myemail, $subject, $message);
/* Redirect visitor to the thankyou page */
header('Location: thankyou.html');
exit();
/* Functions used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!--
Head data in here
-->
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<div id="mainheader">
<div id="mainlogo">
<h1><a href="http://www.X.co.uk/" title="X">
<img style="border:0;width: 260px; height: 160px;" src="images/X.jpg" alt="X" /></a></h1>
</div>
</div>
<div id="content">
<div class="content">
<h2 class="title">Error!</h2>
<p><strong>Please correct the following error:</strong></p>
<p><?php echo $myError; ?></p>
</div>
</div>
<div id="panel">
<div id="main" class="boxed">
<h2 class="heading">Main</h2>
<ul>
<li>Home </li>
<li>About </li>
<li>Contact </li>
</ul>
</div>
<div id="services" class="boxed">
<h2 class="heading">Services</h2>
<ul>
<li>Services </li>
<li>Recent projects </li>
</ul>
</div>
<div id="pricing" class="boxed">
<h2 class="heading">Pricing</h2>
<ul>
<li>Pricing </li>
</ul>
</div>
<div id="info" class="boxed">
<h2 class="heading">Info</h2>
<ul>
<li>Tips and tricks </li>
<li>Useful links </li>
<li>Frequently asked questions </li>
<li>Site map </li>
</ul>
</div>
<div id="contact" class="boxed">
<h2 class="heading">Contact</h2>
<ul>
<li>Contact by email </li>
<li><strong>Telephone:<br />X</strong> </li>
</ul>
</div>
</div>
<div id="mainfooter">
<p> &#169; 2011 X<br />Designed by <strong>X</strong> </p>
<a href="http://validator.w3.org/check?uri=referer" title="Valid XHTML 1.0">
<img style="border:0;width:88px;height:31px" src="images/valid-xhtml10.png" alt="Valid XHTML 1.0" />
</a>
<a href="http://jigsaw.w3.org/css-validator/check/referer" title="Valid CSS!">
<img style="border:0;width:88px;height:31px" src="images/vcss.gif" alt="Valid CSS!" />
</a>
</div>
</body>
</html>
<?php
exit();
}
?>
Generally, the idea of captcha is to prevent automated form processing. Any non-image comparisons will be easily solved.
Regardless, I would use sessions to solve this issue.
Simply store the expected result in a session variable on the first page, and make sure it matches on the second
page1.php:
<?php
session_start();
$digit1 = mt_rand(1,20);
$digit2 = mt_rand(1,20);
if( mt_rand(0,1) === 1 ) {
$math = "$digit1 + $digit2";
$_SESSION['answer'] = $digit1 + $digit2;
} else {
$math = "$digit1 - $digit2";
$_SESSION['answer'] = $digit1 - $digit2;
}
?>
<form method="POST" action="page2.php">
What's <?php echo $math; ?> = <input name="answer" type="text" /><br />
<input type="submit" />
</form>
page2.php
session_start();
echo "You entered ".htmlentities($_POST['answer'])." which is ";
if ($_SESSION['answer'] == $_POST['answer'] )
echo 'correct';
else
echo 'wrong. We expected '.$_SESSION['answer'];
?>
Use a Simple PHP Math Captcha
https://github.com/kmlpandey77/MathCaptcha
MathCaptcha
A Simple PHP Math Captcha
Usage
composer require kmlpandey77/math-captcha
Math in Image
It will return Math in image
Create captcha.php
<?php
require_once 'vendor/autoload.php'; // link to vendor's autoload.php
use Kmlpandey77\MathCaptcha\Captcha;
$captcha = new Captcha();
$captcha->image();
Create form.php
<form action="check.php" method="post">
<p>
Answer it <img src="./captcha.php" alt="" valign="middle"> <input type="text" name="captcha">
</p>
<p><button type="submit" name="submit">Submit</button></p>
</form>
Math in Text
It will return Math in text
Create form.php
Place this code to top of form.php
<?php
require_once 'vendor/autoload.php'; // link to vendor's autoload.php
use Kmlpandey77\MathCaptcha\Captcha;
?>
And place this code in body
<form action="check.php" method="post">
<p>
Answer it <?php echo new Captcha; ?> <input type="text" name="captcha">
</p>
<p><button type="submit" name="submit">Submit</button></p>
</form>
Check
Checks to see if the user entered the correct captcha key
Create check.php
<?php
require_once 'vendor/autoload.php'; // link to vendor's autoload.php
use Kmlpandey77\MathCaptcha\Captcha;
if(isset($_POST['submit'])){
if(Captcha::check()){
//valid action
echo('<font color="green">Answer is valid</font>');
}else{
echo('<font color="red">Answer is invalid</font>');
}
}

Categories