invisible recaptcha v2 not checking required input fields - javascript

I am adding an invisible recaptcha; for some reason, it doesn't check for required fields anymore. Previously, I would get a notification from Chrome stating that the fields can't be empty. Now, it's just ignoring this and letting me submit empty forms.
I am submitting requests using ajax. My guess is that the data-callback is not meant to be used to send ajax requests.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Submit a quote</title>
<link rel="stylesheet" href="../css/style.css">
<link rel="stylesheet" href="../css/forms.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="../js/quotes/ajax.js"></script>
<meta name="description" content="Submit your awesome quote today!">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#0aff0a">
<meta name="msapplication-navbutton-color" content="#0aff0a">
<meta name="apple-mobile-web-app-status-bar-style" content="#0aff0a">
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<div id="status-message"></div>
<div class="container">
<form id="form" action="../php/quoteSubmit.php" method="post">
<h3>Submit your quote</h3>
<fieldset>
<textarea rows="20" name="quote" title="quotes" placeholder="Type your quote here...." tabindex="5" required></textarea>
</fieldset>
<fieldset>
<input placeholder="Author" name="author" title="quotes" type="text" tabindex="1" required>
</fieldset>
<fieldset>
<!--<button name="submit" type="submit" id="contact-submit">Submit</button>-->
<button name="submit" type="submit" id="contact-submit" class="g-recaptcha" data-callback="onSubmit" data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI">Submit</button>
</fieldset>
</form>
</div>
<script>
function onSubmit(e) {
//$("#form").submit(function (e) {
var url = $("#form").attr('action'); // the script where you handle the form input.
ajaxSendData(url, $("#form").serialize());
//});
}
</script>
</body>
</html>
It seems the submit action is cancelled as well.
$("#form").submit(function (e) {
var url = $("#form").attr('action');
ajaxSendData(url, $("#form").serialize());
e.preventDefault();
});
The above snippet only triggers when not using the recaptcha API.
How would I properly send an ajax request to a PHP page?
My full code (if needed):
<?php
include_once "connect.php";
session_start();
if(isset($_POST["quote"], $_POST["author"], $_POST["g-recaptcha-response"])){
if(!isValid()){
http_response_code(400);
exit();
}
$stmt = $conn->prepare("INSERT INTO pending (quote, author) VALUES (?, ?)");
$stmt->bind_param("ss", $quote, $author);
$quote = htmlspecialchars($_POST["quote"]);
$author = htmlspecialchars($_POST["author"]);
$stmt->execute();
echo"Added to pending! Thank you for submitting";
$stmt->close();
$conn->close();
//$_SESSION["lastRequest"] = time();
}else{
http_response_code(400);
exit();
}
function isValid()
{
try {
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = ['secret' => '6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe',
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']];
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if($decoded = json_decode($result, true)){
return $decoded['success'];
}
}
catch (Exception $e) {
return null;
}
}

Try to put the recaptcha in separate div
<div class="g-recaptcha" data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"></div>
function onSubmit(e) {
//$("#form").submit(function (e) {
var url = $("#form").attr('action'); // the script where you handle the form input.
ajaxSendData(url, $("#form").serialize());
//});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js"></script>
<div id="status-message"></div>
<div class="container">
<form id="form" action="../php/quoteSubmit.php" method="post">
<h3>Submit your quote</h3>
<fieldset>
<textarea rows="20" name="quote" title="quotes" placeholder="Type your quote here...." tabindex="5" required></textarea>
</fieldset>
<fieldset>
<input placeholder="Author" name="author" title="quotes" type="text" tabindex="1" required>
</fieldset>
<fieldset>
<!--<button name="submit" type="submit" id="contact-submit">Submit</button>-->
<div class="g-recaptcha" data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"></div>
<button name="submit" type="submit" id="contact-submit" data-callback="onSubmit">Submit</button>
</fieldset>
</form>
</div>

Related

HTML alert gets displayed before hitting the submit button [duplicate]

This question already has answers here:
Checking if form has been submitted - PHP
(9 answers)
Closed 7 months ago.
i have been trying to create a login page linked to a database . I have created an alert which is supposed to be displayed after invalid login or empty login but it gets displayed
right after the login page is loader(i.e. before any submission) .For example as soon as the page loads it displays an alert which says"Username password cannot be empty" .I want this alert to be shown after the user hits the submit button.Please Help.Here's the
image
Here's the code:
<?php
//error
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once "config.php";
session_start();
if (isset($_SESSION['username'])) {
header('location: home.php');
exit;
}
$username = "";
$password = $err = "";
if (isset($_POST)) {
if (empty(trim($_POST['username'])) || empty(trim($_POST['password']))) {
$err = "Username or Password cannot be blank";
} else {
$username = trim($_POST['username']);
$password = trim($_POST['password']);
}
if (empty($err)) {
echo "in";
$sql = "SELECT id,username,password FROM users where username=?";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "s", $param_username);
$param_username = $username;
if (mysqli_stmt_execute($stmt)) {
mysqli_stmt_store_result($stmt);
//if username exists
if (mysqli_stmt_num_rows($stmt) == 1) {
mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
if (mysqli_stmt_fetch($stmt)) {
if (password_verify($password, $hashed_password)) {
//password correct
session_start();
$_SESSION['username'] = $username;
$_SESSION['id'] = $id;
$_SESSION['loggedin'] = true;
header("location: home.php");
}
}
} else {
$err = "Invalid Username or Password";
}
}
}
}
?>
Here's HTML:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Spotify</title>
<link rel="stylesheet" href="style1.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Varela+Round&display=swap" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
</head>
<body class="bds">
<nav>
<ul>
<a>
<li class="brand"><img class="hello" src="./images/logo.png" alt="Spotify">Spotify</li>
<div class="buttons">
<button class="home">Home</button>
<button class="home">About</button>
</div>
<div class="logbutton">
<button class="loginbutt">Register</button>
</div>
</ul>
</nav>
<div class="container mt-4">
<h3>Login Here</h3>
<hr>
<form action="" method="post">
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="text" name="username" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter Username">
<small id="emailHelp" class="form-text text-muted">We'll never share your details with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" name="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<br>
<?php
if (!empty(trim($err))) {
echo "<div id='warningus' class='alert alert-warning alert-dismissible fade show' role='alert'>
<strong>Holy guacamole!</strong> " . $err . "
<button type='button' class='btn-close' data-bs-dismiss='alert' aria-label='Close'></button>
</div>";
$err="";
}
?>
<br>
<button type="submit" class="btn btn-primary">Log in</button>
</form>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
</body>
</html>
Create an input with type="hidden" and give it a name and value. Then check for that input to determine if the page is loaded after a submit.

Why image is not saved to the database?

I am trying to do a register page where a user must fill up its details and upload a picture of its choice. When i pressed the registered button, i have the following errors : "( ! ) Notice: Undefined index: image in /strath-cis/2018/SmartCommute/php/register.php " and "( ! ) Warning: file_get_contents(): Filename cannot be empty in /strath-cis/2018/SmartCommute/php/register.php "
On my database I do have a field called "image" of type BLOB.
I am sure that my details to connect with my database are correct.
Do anyone have a clue why this is happening?
Bellow is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<meta name="mobile-web-app-capable" content="yes"/>
<meta name="apple-mobile-web-app-capable" content="yes"/>
<link rel="stylesheet" type="text/css" href="../css/normalize.css"/>
<link rel="stylesheet" type="text/css" href="../css/register_css.css"/>
<title>Smart Commute</title>
</head>
<body>
<header id="headerBar">Smart Commute - Register</header>
<form class="needs-validation" novalidate action="" method="post">
<p><input type="file" accept="image/*" name="image" id="file" onchange="loadFile(event)" style="display: none;"></p>
<p><label for="file" style="cursor: pointer;">Upload Image</label></p>
<p><img id="output" width="200" /></p>
<script>
var loadFile = function(event) {
var image = document.getElementById('output');
image.src = URL.createObjectURL(event.target.files[0]);
};
</script>
<p>Name: <input type="text" class="form-control" name="name" id="name" placeholder="John Doe" autocomplete="off" value="<?php if(isset($_POST['Register'])){echo $_POST['name'];} ?>" required></p>
<p>Email: <input type="text" class="form-control" name="email" id="email" placeholder="fake#mail.com" autocomplete="off" value="<?php if(isset($_POST['Register'])){echo $_POST['email'];} ?>" required></p>
<p>Password: <input type="password" class="form-control" name="password" id="password" placeholder="Enter password" autocomplete="off" value="<?php if(isset($_POST['Register'])){echo $_POST['password'];} ?>" required></p>
<br><br>
<!-- <input type="submit" value="Submit" name="Register">-->
<button name="Register">Register</button>
</form>
</body>
</html>
<?php
session_start();
if (isset($_POST['Register']) && isset($_POST["image"]) ) {
if (empty($_POST['password']) || preg_match('/\s/', $_POST['password'])) {
echo "No spaces allowed in new password!";
} else {
include("../include/db_config.php");
include("../include/db_connect.php");
// image file directory
$image = addslashes(file_get_contents($_FILES['image']['tmp_name'])); //SQL I
$name = mysqli_real_escape_string($db, $_POST['name']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password = mysqli_real_escape_string($db, $_POST['password']);
$encryptedPassword = md5($password);
$sql = "SELECT * FROM `cs317madt`.`useracc` WHERE `email` = '$email'";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$result = $db->query($sql);
if (mysqli_num_rows($result) == 1) {
echo "User already exists";
} else {
$sql2 = "INSERT INTO `cs317madt`.`useracc` (`id`,`name`,`password`,`email`, `image`) VALUES (NULL, '$name', '$encryptedPassword', '$email','$image');";
if ($result2 = $db->query($sql2)) {
header("location: ../php/home.php");
$_SESSION['logged-in'] = true;
$_SESSION['name'] = $name;
} else {
echo "Something went wrong with creating your account!";
}
}
} else {
echo "Invalid email! Please enter a valid email";
}
}
}
?>
When you are uploading a file, you need to include an enctype="multipart/form-data" attribute to the <form> tag. Have a quick read on the php's manual about file uploads.. You'll notice there is a Note section that explicitly mentions this.
So, for example:
<form enctype="multipart/form-data" class="needs-validation" novalidate action="" method="post">

Having trouble using AJAX to POST to a database

I'm currently building a mobile app using Cordova and I'm having trouble getting a basic test login function working with my code. I have no clue why this isn't working, and I'm unfamiliar with the convoluted way I have to use php so I'm not even sure how to get proper error reporting from that part of the code. If anyone could help me out, I'd be really grateful.
Code below (I've blanked out some details with asterisks.
HTML
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Hello World</title>
</head>
<body>
<div class="app">
<form id="Loginform">
<p><label>username:</label>
<input type="text" id="unl" /></p>
<p>
<label>Password:</label>
<input type="text" id="pwl" /></p><p>
</p>
<p><input type="submit" id="login" value="Login" onClick="logIn();" />
</p></form>
<form id="Registerform">
<p><label>username:</label>
<input type="text" id="unr" /></p>
<p>
<label>Password:</label>
<input type="text" id="pwr" /></p><p>
<label>Re-type Password
:</label>
<input type="text" id="pw2r" />
</p>
<p>
<input type="submit" id="register" value="Register" onClick="regisTer();" /></p>
</form>
<input type="button" id="check" value="check" onClick ="checkUn();">
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/localstorage.js"></script>
<script type="text/javascript" src="js/logreg.js"></script>
<script type="text/javascript" src="js/camera.js"></script>
<script type="text/javascript" src="js/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="js/plugins/LaunchMyApp.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</body>
</html>
logreg.js
function logIn() {
alert("1");
}
function regisTer() {
var un = $("#unr").val();
var pw = $("#pwr").val();
var pw2 = $("#pw2r").val();
if (pw!='' && pw2!='' && un!='') {
if (pw == pw2) {
alert("run post");
$.post("http://cs12ars.icsnewmedia.net/Media/register.php",
{
name:un, pass:pw
}, function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
} else {
alert("both passwords must match");
}
} else {
alert("Please fill in all fields.");
}
}
register.php (on the server, same server as the database)
<?php
//clean input
function clean_string($db_server = null, $string){
$string = trim($string);
$string = utf8_decode($string);
$string = str_replace("#", "&#35", $string);
$string = str_replace("%", "&#37", $string);
if (mysqli_real_escape_string($db_server, $string)) {
$string = mysqli_real_escape_string($db_server, $string);
}
if (get_magic_quotes_gpc()) {
$string = stripslashes($string);
}
return htmlentities($string);
}
//encrypt data
function salt ($string) {
$salt1 = 'gds54d';
$salt2 = '54h6';
$salted = md5 ("$salt1$string$salt2");
return $salted;
}
?>
<?php
$db_hostname = 'localhost';
$db_database = '****';
$db_username = '****';
$db_password = '****';
$db_status = 'not initialised';
$str_result = '';
$str_options = '';
$db_server = mysqli_connect($db_hostname, $db_username, $db_password);
$db_status = "connected";
//connect to the database
mysqli_select_db($db_server, $db_database);
$name = $_POST['name'];
$pw = $_POST['pass'];
$password = salt($pw);
$query = "INSERT INTO `bla` (`bla`, `test`) VALUES (NULL, '$name');";
mysqli_query($db_server, $query);
mysqli_close($db_server);
?>
I have absolutely no idea why, but changing from using $.post to $.ajax and setting asnyc to false made it start working.
$.ajax({
type: "POST",
url: "http://cs12ars.icsnewmedia.net/Media/register.php",
data: {name:un, pass:pw},
async: false
});

Contact form using php inside phonegap gives success alert but cant find mail

basically the question is mirror of previous one in stack overflow. This form works but after a success alert, I don't find mail sent to a designated email id.
after i click the send button if i get success alert that means mail has been sent successfully, but when i check name#example.com (dummy) i should see mail in inbox but cant find one. What may be the problem. Am i doing wrong?
contact.html
<html>
<head>
<link rel = "stylesheet" href="css/theme.min.css"/>
<link rel="stylesheet" href="css/jquery.mobile-1.2.1.css"/>
<script type="text/javascript" charset="utf-8" src="js/jquery-1.6.1.min.js"></script>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="js/jquery.mobile-1.2.1.min.js"></script>
<script type="text/javascript">
// When the document has loaded...
$(document).ready(function() {
// Bind this action as a function to be executed when the button is clicked...
$('input[type="button"][value="send"]').click(function() {
$.post('http://www.techmagzine.com/contact_us.php', {
// These are the names of the form values
// EDIT: You have the wrong ids on these...
FirstName: $('#txtfullname').val(),
LastName: $('#txtemail').val(),
Email: $('#txtcontact').val(),
MessageText: $('#txtmessage').val()
// HTML function
}, function (html) {
// Place the HTML in a astring
var response=html;
// PHP was done and email sent
if (response=="success") {
alert("Message sent!");
clear();
} else {
// Error postback
alert("Please fill all fields!");
return false;
}
});
});
});
</script>
</head>
<body>
<div data-role="page" id="front" data-theme="b">
<div class="header" id="header" data-role="header">
<h3>Contact-Us</h3>
</div>
<div data-role="content">
<label for="txtfullname">Firstname</label>
<input id="txtfullname" name="FirstName" type="text" placeholder="required" required />
<label for="txtemail">Lastname</label>
<input id="txtemail" name="LastName" type="text" placeholder="required" required />
<label for="txtcontact">Email</label>
<input id="txtcontact" name="Email" type="email" placeholder="required" required />
<label for="txtmessage">Message</label>
<textarea id="txtmessage" name="MessageText" placeholder="required" rows="10" required ></textarea>
<input type="button" value="send"/>
</div>
</div>
</body>
</html>
contact_us.php
<?php
// VARS
$FirstName=$_POST["FirstName"];
$LastName=$_POST["LastName"];
$Email=$_POST["Email"];
$MessageText=$_POST["MessageText"];
$Headers = "From:" . $Email;
//VALIDATION
if(
$FirstName=="" ||
$LastName=="" ||
$Email=="" ||
$MessageText==""
) {
echo "Error";
} else {
mail("name#example.com","mobile app message",$MessageText, $Headers);
echo "success";
}
?>

How do I validate CSV file format using onclick function?

How can I validate my CSV format and I am using "required" in my html form to validate null value. I try to use onclick function to validate using alert box but alert box not function after I add php code inside javascript. Below is my code. Can anyone suggest a solution to me?
<?php
require_once "lib/base.inc.php";
?>
<script>
function storeQueEmail(){
<?php
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
$record['contact_first'] = $data[0];
$record['contact_last'] = $data[1];
$record['contact_email'] = $data[2];
$record['subject'] = $_REQUEST['subject'];
$record['message'] = $_REQUEST['message'];
$record['status'] = 0;
$oAdminEmail->insertQueEmail($record);
}
} while ($data = fgetcsv($handle,1000,",","'"));
?>;
alert('jyfkyugu');
window.location.href="cronjob_sendemail.php";
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Import a CSV File with PHP & MySQL</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1" >
Subject : <br/>
<input type="text" name="subject" id="subject" required/> <br/>
Choose your file: <br />
<input name="csv" type="file"id="csv" required/> <br/>
Content : <br/>
<textarea name="message" cols="50" rows="10" required></textarea><br/>
<input type="submit" name="submit" value="Submit" onclick="storeQueEmail()"/>
</form>
</body>
</html>

Categories

Resources