I want make protection on form, if user after using form want send another message in less than a minute he should get refuse. Other way every thing should pass.
For now I got something like this on view:
<!-- If Success form message send display this -->
<?php if (isset($_GET['msgSuccessSent']) == 1) { ?>
<h1 class="page-title text-center">Dziękujemy za wysłanie wiadomości</h1>
<div class="text-center">
Wyślij kolejną wiadomość
</div>
<?php } else { ?>
<?php if (isset($_GET['msgTimerError']) == 1) { ?>
<div id="errorMessage" class="alert alert-danger" role="alert">Przed wysłaniem kolejnej wiadomości musisz odczekać conajmniej minutę.</div>
<?php } ?>
<!-- If message isn't sent display form -->
<h1 class="page-title text-center">Formularz kontaktowy</h1>
<!-- Contact form -->
<form action="contact_send.php" method="post">
<!-- First name input -->
<div class="form-group">
<label for="firstName">Imię</label>
<input type="text" class="form-control" id="firstName" name="firstName" placeholder="Wpisz swoje imię">
</div>
<!-- Second name input -->
<div class="form-group">
<label for="secondName">Nazwisko</label>
<input type="text" class="form-control" id="secondName" name="secondName" placeholder="Wpisz swoje nazwisko">
</div>
<!-- Phone number input -->
<div class="form-group">
<label for="phoneNumber">Telefon kontaktowy</label>
<input type="tel" class="form-control" id="phoneNumber" name="phoneNumber" placeholder="Wpisz swój numer telefonu">
</div>
<!-- Email address input -->
<div class="form-group">
<label for="email">Adres e-mail</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Wpisz swój adres e-mail">
</div>
<!-- Message textarea -->
<div class="form-group">
<label for="message">Treść wiadomości</label>
<textarea type="text" class="form-control" id="message" name="message" rows="3"></textarea>
</div>
<!-- Send message button -->
<button type="reset" class="btn btn-default">Wyczyść formularz</button>
<button type="submit" class="btn btn-default pull-right">Wyślij</button>
</form>
<!-- Contact form end -->
<!-- End of If message isn't sent display form -->
<?php } ?>
And this is my contact_send.php file:
<?php
// Uncomment if you want to use session to check last form send
session_start();
$_SESSION['time'] = date('H:i:s');
header('Content-type: text/plain; charset=utf-8');
# Database connection settings
$dbHost = 'localhost'; // database hostname
$dbName = 'contactForm'; // database name
$dbUser = 'root'; // database user name
$dbPswd = ''; // database password
// Set connection
$connectionDb = new mysqli($dbHost, $dbUser, $dbPswd, $dbName);
// Check connection
if ($connectionDb->connect_error) {
die("Connection failed: " . $connectionDb->connect_error);
}
mysqli_set_charset( $connectionDb, 'utf8'); // change charset for mysqli to utf8
# Require ContactSend and DatabaseQuery class
require 'contact.class.php';
# Get ContactSend class
$sendEmail = new ContactSend();
$ipAddress = $_SERVER['REMOTE_ADDR']; // get user ip address
$currentDate = date('Y-m-d H:i:s'); // get Date time when user send form
# ***
# Here I check if time of last form send is greater than minute
# ***
$sqlCheck = "SELECT * FROM contactForm WHERE ipAddress = '$_SERVER[REMOTE_ADDR]' AND dateSend > DATE_SUB(NOW(),INTERVAL 1 MINUTE)";
if ($connectionDb->query($sqlCheck) === TRUE) {
$sendEmail->redirectToForm('form.php?msgTimerError=1');
} else {
// insert form values into database
$sqlQueryInsert =
"INSERT INTO contactForm (
firstName,
secondName,
phoneNumber,
email,
message,
dateSend,
ipAddress)
VALUES (
'$_POST[firstName]',
'$_POST[secondName]',
'$_POST[phoneNumber]',
'$_POST[email]',
'$_POST[message]',
'$currentDate',
'$ipAddress'
)";
// if data was save send mail and redirect to form
if ($connectionDb->query($sqlQueryInsert) === TRUE) {
# Get Parametrs from form
$sendEmail->sendTo = "kuchar.rafal#gmail.com"; // here insert your email address that you want get mails
$sendEmail->subject = "Tytuł wiadomości"; // here insert Subject of email
$sendEmail->firstName = $_POST['firstName']; // get user first name
$sendEmail->secondName = $_POST['secondName']; // get user second name
$sendEmail->phoneNumber = $_POST['phoneNumber']; // get user phone number
$sendEmail->email = $_POST['email']; // get user email address
// make mail content and insert form values into it
$sendEmail->message = "
Imię: " . $_POST['firstName'] . "
Nazwisko: " . $_POST['secondName'] . "
Numer telefonu: " . $_POST['phoneNumber'] . "
Adres email: " . $_POST['email'] . "
Wiadomość: " . $_POST['message'];
$sendEmail->mailSender(); // send mail
} else {
echo "Error: " . $sqlQueryInsert . "<br>" . $connectionDb->error; // display error if database connection or query has error
}
// close connection to database
$connectionDb->close();
// redirect to form
$sendEmail->redirectToForm('form.php?msgSuccessSent=1');
}
?>
$msgTimerError should display if in database exist row with user IP and date of create is less than minute other ways it should just display form.
$sqlCheck is for check in database if time of last form send is greater than minute if its not it redirect user to form.php with msgTimerError=1 with method get, otherwise it will add new form values to database and send mail.
Ok i changed line in contact_send.php so it works... (im so ashamed...)
# Check if user send form less than minute, if true return to form with error
$sqlCheck = "SELECT * FROM contactForm WHERE ipAddress = '$ipAddress' AND dateSend > DATE_SUB(NOW(),INTERVAL 1 MINUTE) LIMIT 1";
$result = $connectionDb->query($sqlCheck);
if (mysqli_fetch_row($result)) {
$sendEmail->redirectToForm('form.php?msgTimerError=1'); // return to form page
} else {
Related
I am fairly new to PHP and a new student and so I will ask in advance to please forgive me if I have made errors that will be clearly obvious to someone experienced.
I am working on a page submission form that connects to a mysql database to either check for an existing value and if it does not exist then logs a string value of the datetime picker and also appends an id number to make a unique value to a table whenever someone was to press submit, and after form validation is accepted. Submitting if the record does not exist works and is ok.
However, whenever a record already exists, rather than displaying in the error message that the time is unavailable, the entire page just goes blank.
Initially, I had a button that would check to see if the record existed in the mysql table but I then decided it would be more efficient to try to include the date validation check of mysql table while completing the form validation and this is where I have trouble and of course the page breaks and nothing is displayed.
If someone could please guide me I would be most grateful.
it seems I am unable to add more code, but I will add what was wrong.
I did need to initialize $error=''; also $DateTime, and $id at the top of the script, I had it below but had forgotten to place it above and that was causing my problem.
<?php
$userid = "1";
$strid = strval($id);
$DateTimeCheck = $DateTime . $strid;
$con = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
$con->exec("SET CHARACTER SET utf8");
$sql = "SELECT booked FROM user_booking WHERE `booked` = :booked";
$sqlprep = $con->prepare($sql);
$ar_val = array(':booked' => $DateTimeCheck);
if (isset($_POST['datetime'])){
if (!$_POST['name']) {
$error = "<br/>- Please enter your name";
}
if (!$_POST['email']) {
$error .= "<br/>- Please enter your email";
}
if (!$_POST['message']) {
$error .= "<br/>- Please enter a message";
}
if (!$_POST['check']) {
$error .= "<br/>- Please confirm you are human";
}
if ($sqlprep->execute($ar_val)) {
while ($row = $sqlprep->fetch(PDO::FETCH_OBJ)) {
$DateTimeExists = $row->booked;
}
}
if (isset($DateTimeExists) && $DateTimeExists != ''){
$error .= "<br/>- The time you have requested is unavailable";
}
if ($error) {
$result = '<div class="alert alert-danger" role="alert"><strong>Whoops, there is an error</strong>. Please correct the following: ' . $error . '</div>';
} else {
mail("#gmail.com", "Contact message", "Name: " . $_POST['name'] . "
Email: " . $_POST['email'] . "
When: " . $_POST['datetime'] . "
Message: " . $_POST['message']);
{
$result = '<div class="alert alert-success" role="alert">Thank you, someone will be in touch soon to confirm your appointment. </div>';
$id = "$userid";
$strid = strval($id);
$DateTime = $_POST['datetime'];
$DateTimeCheck = $DateTime . $strid;
$strid = strval($id);
$con = new PDO("mysql:host=$host;dbname=$dbname", $user, $password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO user_booking ( user_id, booked ) VALUES ( :id, :booked )";
$q = $con->prepare($sql);
$q->execute(array(':booked' => $DateTime . $strid,
':id' => $id));
$con = null;
}
}
}
?>
Here is the markup for the form.
<form method="post" role="form">
<div class="form-group">
<input type="text" name="name" class="form-control" placeholder="Your name"
value="<?php echo $_POST['name']; ?>">
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Your email"
value="<?php echo $_POST['email']; ?>">
</div>
<div class="form-group" align="left">
<label class="control-label">Date/Time</label>
<div class='input-group date' id='datetimepicker1'>
<input type='text' name="datetime" class="form-control" placeholder="desired time"
value="<?php echo $_POST['datetime']; ?>">
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<div class="form-group">
<textarea name="message" rows="5" class="form-control"
placeholder="message..."><?php echo $_POST['message']; ?></textarea>
</div>
<div class="checkbox" align="left">
<label class="readable" align="left">
<input type="checkbox" name="check"> I am human
</label>
</div>
<div align="left">
<input type="submit" name="submit" class="btn btn-success" value="Book Appointment!"/>
</div>
</form>
If you are using .= you need to first initialise the variable before .= will work on the variable.
You attempted to do that in this IF block
if (!$_POST['name']) {
$error = "<br/>- Please enter your name";
}
but if that error is not present you will never actually initialise the $error variable.
So the simple solution is to initialise $error before getting into this section of code
$error = '';
if (isset($_POST['datetime'])){
// So now you can change this test to use .=
if (!$_POST['name']) {
$error .= "<br/>- Please enter your name";
}
Now the variable will be testable later in the code
If this is in fact the problem here, you should have been getting errors reported. If you didnt see any then try adding these lines of code to any problem script while you test it
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
I feel this should be straight forward but the data isnt going in to the table.
When I try to save the data the code executes and displays this message:
$statusMsg1 = "A problem occurred, please try again.";
Which leads me to think the problem must be with the SQL, but nothing is standing out to me to highlight what the issue is.
I changed the SQL so that insert raw text, but this produces the same message.
postCodes.php
<?php
// Form saubmission script
include_once 'submit.php';
/* Attempt MySQL server connection. */
$mysqli = new mysqli("127.0.0.1", "root", "root", "bookingpage");
// Check connection
if($mysqli === false){
die("ERROR: Could not connect. " . $mysqli->connect_error);
}
// SQL query execution
$sql = "SELECT * FROM Postcodes";
?>
<!-- Status message -->
<?php if(!empty($statusMsg1)){ ?>
<p class="stmsg"><?php echo $statusMsg1; ?></p>
<?php } ?>
<!-- GENERAL TAB -->
<p style="color:RGB(0,70,135)">You can use the text editor below to display text on your home page</p>
<form action="" method="post">
<div class="form-group">
<label for="postcode1">Enter Postcode Area</label>
<input style="font-size:12px" name="postCodetext" id="postCodetext" class="form-control required" value="e.g CF11">
</div>
<div class="form-group">
<label for="deliveryCost">Delivery Charge</label>
<input style="font-size:12px" name="costtext" id="costtext" class="form-control required" value="e.g 5.00">
</div>
<button type="button" class="save-settings btn btn-primary btn-xs"
title="<?= lang('save') ?>">
<span class="glyphicon glyphicon-floppy-disk"></span>
<?= lang('save') ?>
</button>
<input type="submit" name="submitPostCode" value="Save Data">
</form>
submit.php
<?php
// Include the database configuration file
require_once 'dbConfig.php';
$editorContent = $statusMsg = '';
$postCodeString = $statusMsg1 = '';
// SAVE POSTCODE & DELIVERY COST
if(isset($_POST['submitPostCode'])){
// Get editor content
$postCodeString = $_POST['postCodetext'];
$costString = $_POST['costtext'];
// Check whether the editor content is empty
if(!empty($postCodeString)){
// Insert editor content in the database
$insert1 = $db->query("INSERT INTO PostCodes (postCode, Cost) VALUES ('".$postCodeString."', '".$costString."')");
// If database insertion is successful
if($insert1){
$statusMsg1 = "Succeddfully Saved.";
}else{
$statusMsg1 = "A problem occurred, please try again.";
}
}else{
$statusMsg1 = 'You cannot save a blank postcode or delivery charge';
}
}
I'm trying to input form data into the database. I'm using almost the same code as I did for my registration script, which works perfectly. I'm completely stumped at this point.
I have error reporting turned on for PHP and PDO, nothing is happening. When the form is sent, it appears to work (except without the confirmation messages appearing) but nothing is entered into the database.
I have two files, request.php (the form) and parseRequest.php (the backend to the form).
request.php
<form action="" method="post">
<div class="form-group">
<input type="hidden" class="form-control" name="username" id="usernameField" value="<?php echo $_SESSION['username'];?>">
</div>
<div class="form-group">
<label>Headlining Band/Artist</label>
<input type="text" class="form-control" name="artist" id="artistField" placeholder="Artist">
</div>
<div class="form-group">
<label>Date</label>
<input type="text" class="form-control" name="day" id="dateField" placeholder="MM/DD/YYYY">
</div>
<div class="form-group">
<label>Venue</label>
<input type="text" class="form-control" name="venue" id="venueField" placeholder="Venue">
</div>
<div class="form-group">
<label>City, State</label>
<input type="text" class="form-control" name="city" id="cityField" placeholder="City, State">
</div>
<input type="hidden" name="token" value="<?php if(function_exists('_token')) echo _token(); ?>">
<button type="submit" name="requestBtn" class="btn btn-primary pull-right">Submit</button>
parseRequest.php
<?php
include_once 'resource/Database.php';
include_once 'resource/utilities.php';
include_once 'resource/send-email.php';
// Processing the form
if(isset($_POST['requestBtn'], $_POST['token'])){
if(validate_token($_POST['token'])) {
//process form here
$form_errors = "";
// validation
$required_fields = array('artist', 'day', 'venue', 'city');
// check empty fieldset
$form_errors = check_empty_fields($required_fields);
// date check
$fields_to_check_length = array('day' => 10);
//call the function to check minimum required length and merge the return data into form_error array
$form_errors = array_merge($form_errors, check_min_length($fields_to_check_length));
// collect data
$username = $_POST['username'];
$artist = $_POST['artist'];
$day = $_POST['day'];
$venue = $_POST['venue'];
$city = $_POST['city'];
}
else if(empty($form_errors))
{
// preparing and inputting data
try
{
$sqlInsert = "INSERT INTO requests(username, artist, day, venue, city)
VALUES (:username, :artist, :day, :venue, :city)";
//use PDO prepared to sanitize data
$statement = $db->prepare($sqlInsert);
//add the data into the database
$statement->execute(array(':username' => $username, ':artist' => $artist, ':day' => $day, ':venue' => $venue, ':city' => $city));
// email confirmation
$addresses = array($_SESSION['email'], 'codylkaczynski#gmail.com');
//prepare email body
$mail_body = '<html>
<body style="font-family: Arial, Helvetica, sans-serif;
line-height:1.8em;">
<h2>Amped Sound Staff Portal: Request Received</h2>
<p>Dear '.$username.'<br><br>
Your request for the '.$artist.' show in '.$city.' on '.$date.' has been received!</p><br/>
<p>We will let you know if your request has been approved or denied ASAP.</p><br/>
<p>Thank you!</p><br/>
<p><strong>©2018 Amped Sound</strong></p>
</body>
</html>';
$namejeff = explode(',', $addresses);
foreach ($addresses as $address)
{
$mail->AddAddress($address);
$mail->Subject = "Request Received!";
$mail->Body = $mail_body;
}
//Error Handling for PHPMailer
if(!$mail->Send())
{
$result = "<script type=\"text/javascript\">swal(\"Error\",\" Email sending failed: $mail->ErrorInfo \",\"error\");</script>";
}
else
{
$result = "<script type=\"text/javascript\">
swal({
title: \"Request received!\",
text: \"We have received your request! Please check your email for confirmation.\",
type: 'success',
confirmButtonText: \"Thank You!\" });
</script>";
}
}
catch (PDOException $ex)
{
$result = flashMessage("An error occurred: " .$ex->getMessage());
}
}
}
I appreciate any help I can get. I've tried a bunch of solutions I found on StackOverflow already, to no avail.
I am working on a code right now that allows for the user to input their email and another user's email to add them as a "friend" into the table "friends"
So far my code works in terms of posting the form data into the DB / table "friends" however the message I would like to appear is not showing up at all.
My HTML form:
<form class="form-signin" action="FriendLookup.php" method = "POST" enctype="multipart/form-data">
<h2 class="form-signin-heading">Add a Friend</h2>
</br>
<label for="inputEmail" class="sr-only">Your Email</label>
<input type="text" id="inputEmail1" name = "self_email" class="form-control" placeholder="Friend's Username" >
</br>
<label class="sr-only">Your Friend's Email</label>
<input type="text" id="inputEmail2" name = "friend_email" class="form-control" placeholder="Your Username" >
</br>
<button class="btn btn-lg btn-primary btn-block" name = "submit" type="submit">Search</button>
</form>
PHP script:
<?php
include_once('support.php');
//connect_database.php contains your connection/creation of a PDO to connect to your MYSQL db on bmgt406.rhsmith.umd.edu/phpmyadmin
include_once('connect_database.php');
ini_set("display_errors","1");
error_reporting(E_ALL);
// Initialize $title and $body.
$title = "Add User";
$body = "<fieldset><legend> $title </legend>";
$name_of_table = "friends";
// Check if the table exists in the db.
if (tableExists($db, $name_of_table)) {
$inputemail1 = $_POST['self_email'];
$inputemail2 = $_POST['friend_email'];
// Prepare a SQL query and bind all 6 variables.
$sqlQuery = "INSERT INTO $name_of_table ( self_email, friend_email)
VALUES ( :self_email, :friend_email)";
$statement1 = $db->prepare($sqlQuery);
$statement1->bindValue(':self_email', $inputemail1, PDO::PARAM_STR);
$statement1->bindValue(':friend_email', $inputemail2, PDO::PARAM_STR);
// Execute the SQL query using $statement1->execute(); and assign the value
// that is returned to $result.
$result = $statement1->execute();
if(!$result) {
// Query fails.
$body .= "Inserting entry for friend failed.";
} else {
// Query is successful.
$body .= "Success";
}
// Closing query connection
$statement1->closeCursor();
}
$body .= "</fieldset>";
echo generatePage($title,$body);
?>
Any help is greatly appreciated. I am a novice programmer.
My function generatePage was wrong. I added HTML into the function and now it works!
Hi I am trying to validate email and username by using ajax but same code is not working for two different inupt fields.
HTML
<script>
//function to check username availability
function check_availability_username(){
//get the username
var username = $('.username').val();
//use ajax to run the check
$.post("check_username.php", { username: username },
function(result){
//if the result is 1
if(result == 1){
//show that the username is available
$('#username_availability_resul1').html('<span style="color:#0C0;">'+username + ' is available!</span>');
}else{
//show that the username is NOT available
$('#username_availability_result').html('<span style="color:#F00;">'+username +result+ ' already used!</span>');
}
});
}
function check_availability(){
//get the username
var email = $('.email').val();
//use ajax to run the check
$.post("check_email.php", { email: email },
function(result){
//if the result is 1
if(result == 1){
//show that the username is available
$('#email_availability_result').html('<span style="color:#0C0;">'+email + ' is available!</span>');
}else{
//show that the username is NOT available
$('#email_availability_result').html('<span style="color:#F00;">'+email + ' already used!</span>');
}
});
}
</script>
<form role="form" method="post" action="add-users.php?insert=ok" class="form-horizontal form-groups-bordered">
<div class="form-group">
<label for="field-1" class="col-sm-2 control-label">Username</label>
<div class="col-sm-6">
<input type="text" onkeyup="check_availability_username()" class="form-control" name="username" placeholder="Username1" required>
<div id='username_availability_result'></div>
</div>
</div>
<div class="form-group">
<label for="field-1" class="col-sm-2 control-label">Email Address</label>
<div class="col-sm-6">
<input type="email" onkeyup="check_availability()" class="form-control email" name="email" placeholder="Email Address" required>
<div id='email_availability_result'></div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-6">
<input type="submit" class="btn btn-primary" value="Add User">
<input class="btn btn-danger" type="reset" value="Reset">
</div>
</div>
</form>
check_username.php
<?php
//connect to database
$db = mysqli_connect('localhost', 'root', '123', 'mydb') or die('db not connected');
//get the username
$username = mysqli_real_escape_string($db, $_POST['username']);
//mysql query to select field username if it's equal to the username that we check '
$result = mysqli_query($db, 'select username from userinfo where username = "'. $username .'"');
//if number of rows fields is bigger them 0 that means it's NOT available '
if(mysqli_num_rows($result)>0){
//and we send 0 to the ajax request
echo 0;
}else{
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo 1;
}
?>
check_email.php
<?php
//connect to database
$db = mysqli_connect('localhost', 'root', '123', 'mydb') or die('db not connected');
//get the email
$email = mysqli_real_escape_string($db, $_POST['email']);
//mysql query to select field email if it's equal to the email that we check '
$result = mysqli_query($db, 'select email from userinfo where email = "'. $email .'"');
//if number of rows fields is bigger them 0 that means it's NOT available '
if(mysqli_num_rows($result)>0){
//and we send 0 to the ajax request
echo 0;
}else{
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo 1;
}
?>
code is working perfectly for EMAIL validation but not for USERNAME.
any suggestions