reCaptcha isnt working as intended in php - php

I'm trying to add reCaptcha to my registration page, but i cant seem to get it to work, it keeps displaying the message that the data was entered incorrectly, the code is below:
<div align="center">
<?PHP
if (isset($_POST['submit']))
{
$username = $_POST["username"];
$password = $_POST["password"];
$password1 = $_POST["password1"];
if(empty($username)) die(print '<script> alert ("Enter Username"); window.location="registration.php"; </script>');
if(empty($password)) die(print '<script> alert ("Enter Password"); window.location="registration.php"; </script>');
if($password != $password1) die(print '<script> alert ("Password doesn\'t match"); window.location="registration.php"; </script>');
require_once('recaptchalib.php'); // reCAPTCHA Library
$privkey = "6Ld27usSAAAAAKiYor8lnBs9fb6HOd1IK5JnTCyL"; // Private API Key
$verify = recaptcha_check_answer($privkey, $_SERVER['REMOTE_ADDR'], $_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field']);
if ($verify!=is_valid) {
echo "You did not enter the correct Captcha. Please try again.";
}
else {
$file = file_get_contents("data.txt");
$string = "$username||$password";
if(!strstr($file, "$string"))
{
$myFile = "data.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "$username||$password\n";
fwrite($fh, $stringData);
print '<script> alert ("Registration Complete"); window.location="index.php"; </script>';
fclose($fh);
}
else
{
echo "Sorry the username: <b>$username</b> is already registered. Please use diferent username.";
}
}
}
?>
</div>
<!doctype html>
<html>
<head>
<title>Registration</title>
</head>
<body>
<div id="container" style="width:500px; height:500px; border: 2px solid black; margin:auto">
<?php include "header.php"; ?>
<div id="content" style="background-color:#EEEEEE; width:500px; height:400px; float: left">
<br>
<form align="center" method="post" action="registration.php" >
Username:
<input type="text" name="username" />
<br/>
<br/>
Password:
<input type="password" name="password" />
<br/>
<br/>
Confirm:
<input type="password" name="password1" />
<br/>
<br/>
<?php
require_once('recaptchalib.php'); // reCAPTCHA Library
$pubkey = "6Ld27usSAAAAAB9Zq67L28CqywwEn9RZ_7bFthm7"; // Public API Key
echo recaptcha_get_html($pubkey); // Display reCAPTCHA
?>
<input type="submit" value="Register" name="submit" />
</form>
</div>
<?php include "footer.php"; ?>
</div>
</body>
</html>
I have a feeling that my problem is in ($verify!=is_valid) but i am not sure. Would appreciate any help.

Per the docs found here, it looks like you're not using the return value of recaptcha_check_answer() properly:
recaptcha_check_answer returns an object that represents whether the
user successfully completed the challenge.
If $resp->is_valid is true then the captcha challenge was correctly completed and you should
continue with form processing.
Instead of $verify != is_valid, you should use the is_valid value on the returned object:
if ($verify->is_valid) {
echo "You did not enter the correct Captcha. Please try again.";
} else {
...

Related

php script generating new pw to PlayFab

This is my first php script ever and I have googled a lot to try to get the script to work.
I am working on this tutorial: https://learn.microsoft.com/en-us/gaming/playfab/features/engagement/emails/using-email-templates-to-send-an-account-recovery-email
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$emailErr = $pw1Err = $pw2Err = "";
$email = $pw1 = $pw2 = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["email"]))
{
$emailErr = "Email is required";
}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["pw1"]))
{
$pw1Err = "Password is required";
}
if (empty($_POST["pw2"])) {
$pw2Err = "Confirm Password is required";
}
//$str1 = "Hello";
//$str2 = "Hello World";
//echo strcasecmp($pw11, $pw2); // Outputs: -6
//$check = strcasecmp($pw11, $pw2)
$check = strcasecmp($pw1, $pw2); // Outputs: -6
/*
if ($check == 0)
{
<br><br>
echo Passwords are the same!;
<br><br>
}
else
{
<br><br>
echo Passwords are NOT the same!;
<br><br>
}
*/
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Password Recovery</h2>
<p><span class="error">* required field</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
New Password: <input type="test_input" name=pw1 valur="<?php echo $pw1;?>">
<span class="error">* <?php echo $pw1Err;?></span>
<br><br>
Confirm Password: <input type="test_input" name=pw2 valur="<? php echo $pw2;?>">
<span class="error">* <?php echo $pw2Err;?></span>
<br><br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<br>";
echo "<h3>Your Input:</h3>";
echo $email;
echo "<br>";
echo $check;
?>
</body>
</html>
What I am trying to accomplish is the callback URL. I first tried to create it in WordPress, which was also a first, and now try with php code.
Here is what I try to accomplish:
A form with the following fields:
email
New pasword (currently a text_input during test but will be real pw)
Confirm password (currently a text_input during test but will be real pw)
Submit button
Currently I am focus on trying to echo the result but I just can't get this to work.
The ultimate target is to send back a confirmation with this API including the new checked password and the token.
https://learn.microsoft.com/en-us/rest/api/playfab/admin/account-management/reset-password?view=playfab-rest
I have been trying for quite a long time now so I reach out for help.

setting up ajax validation response

My PHP code for a login form [this part located at the very top on my index.php where I have the login form] looks something like this:
if(isset($_POST['submit'])){
if (!isset($_POST['username'])) $error[] = "Please fill out all fields";
if (!isset($_POST['password'])) $error[] = "Please fill out all fields";
$username = $_POST['username'];
if ( $user->isValidUsername($username)){
if (!isset($_POST['password'])){
$error[] = 'A password must be entered';
}
$password = $_POST['password'];
if($user->login($username,$password)){
$_SESSION['username'] = $username;
header('Location: welcome.php');
exit;
} else {
$error[] = '<div style = "text-align:center">Wrong username/password or your account have not been activated </span>';
}
}else{
$error[] = '<div style = "text-align:center">Username required</span>';
}
and the HTML for the login form is like this:
<form role="form" method="post" action="" >
<?php
//check for any errors
if(isset($error)){
foreach($error as $error){
echo '<p class="bg-danger">'.$error.'</p>';
}
}
if(isset($_GET['action'])){
//check the action
switch ($_GET['action']) {
case 'active':
echo "<h2 class='bg-success'>Your account is now active you may now log in.</h2>";
break;
case 'reset':
echo "<h2 class='bg-success'>Please check your inbox for a reset link.</h2>";
break;
case 'resetAccount':
echo "<h2 class='bg-success'>Password changed, you may now login.</h2>";
break;
}
}
?>
<div class="form-group">
<p align="center">
<font face="Tahoma">Username:</font><font color="#FFFFFF">
</font>
<input type="text" name="username" id="username" class="form-control input-lg" value="<?php if(isset($error)){ echo htmlspecialchars($_POST['username'], ENT_QUOTES); } ?>" tabindex="1">
</div>
<br>
<div class="form-group">
<p align="center">
<font face="Tahoma">Password: </font><font color="#FFFFFF">
</font><input type="password" name="password" id="password" class="form-control input-lg" tabindex="3">
</div>
<br>
<div align="center">
<input type="submit" name="submit" value="Login" class="btn1" tabindex="5">
</div>
</form>
Now, as this form in submitted if there are ERRORS , it will refresh the whole page and back with error messages on right on top of the form fields. How would I be able to use AJAX / jQuery response to validate for ERRORS without refreshing the whole page. ONLY of there are ERRORS I want it pop the error messages without refreshing. And if it's SUCCESS, then it would log the user in. Can someone help me with this ?
I also have a errors.php file that has only this code in it:
<?php if (count($errors) > 0) : ?>
<div class="error">
<?php foreach ($errors as $error) : ?>
<p><?php echo $error ?></p>
<?php endforeach ?>
</div>
<?php endif ?>
I get the concept behind setting up the AJAX method, but IDK how to use it on this code and form. Hope you guys can help.
This is a very broad question with many possible answers, but here's one way to do it.
1. Post your login with AJAX
$.post("loginScript.php", {
username: "username goes here",
password: "password goes here"
}, function(data){
});
2. Echo your results
Your login script should echo out a JSON response that indicates whether the login was successful and if not, what the errors were.
<?php
if(//login conditions)
{
echo json_encode(array(
"success" => true
));
}
else
{
echo json_encode(array(
"success" => false,
"errors" => $errors
));
}
3. Handle the response
$.post("loginScript.php", {
username: "username goes here",
password: "password goes here"
}, function(data){
var json = JSON.parse(data);
if(json.success)
{
//Login was successful
}
else
{
var errors = json.errors;
//Display errors on your page.
}
});

Unable to call PHP function in HTML file, tried using the same code in different code its working fine but not here

When I press the Login button it refreshes the page and doesn't do anything. I tried entering wrong Server IP just to check the error, but I guess it's not responding to the login button and directly refreshing the page.
Unable to call a PHP function in the HTML file, tried using the same code in a different code and it's working fine there but not here:
<title> Database Login </title>
<body>
</head>
<body>
<span>
<div class="heading">
<h3><img src="http://zicom.com/img/ilayashop-1482233381.jpg" alt="Zicom Logo" >
<h1><b>MAaaS Login<b></h1><br>
</span>
</div>
<div class='admin'>
<form method='post' action=''>
<p class='main'> Enter your Details </p>
<p> Enter User Name <input type="text" name="name" id="userInput"></p>
<p> Enter password <input type="password" name="pass" id="userInput"> </p>
<br>
<input id="login" type="submit" name="submit" value="Login">
</form>
</div>
<?php
if($_POST){
$UN = $_POST['name'];
$PS = $_POST['pass'];
$scon=odbc_connect("Driver={SQL Server};Server=XXXXXXX; Database=Sampledata;","XX","XXXXX");
$query="SELECT [password] FROM [Simcarddata].[dbo].[MasterUser] Where username='$UN'";
$rs=odbc_exec($scon,$query);
if (!$rs)
{
$msg="SQL statement failed with error:\n";
$msg.=odbc_error($scon).": ".odbc_errormsg($scon)."\n";
} else {
$number_of_rows = odbc_num_rows($rs);
$msg="$number_of_rows records found.\n";
}
while(odbc_fetch_row($rs))
{
$field1 = odbc_result($rs,1);
// print ("$PS and $field1");
if ($PS == $field1){
print ("TRUE");
header("Location: /test.php");
}
else {
print ("Incorrect Username or password");
}
}
odbc_close($scon);
header("Refresh:2");
}
?>
</body>
</html>
I just tidied up the HTML tags a little and used a better method of checking for POST data - but I think the issue was the badly formed HTML was confusing the form
<html>
</head>
<title> Database Login </title>
</head>
<body>
<span>
<div class="heading">
<h3><img src="http://zicom.com/img/ilayashop-1482233381.jpg" alt="Zicom Logo" ></h3>
<h1><b>MAaaS Login<b></h1>
<br>
</div>
</span>
<div class='admin'>
<form method='post'>
<p class='main'> Enter your Details </p>
<p>Enter User Name <input type="text" name="name" id="userInput"></p>
<p>Enter password <input type="password" name="pass" id="userInput"></p>
<br>
<input id="login" type="submit" name="submit" value="Login">
</form>
</div>
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['name'], $_POST['pass'] ) ){
$UN = $_POST['name'];
$PS = $_POST['pass'];
$scon=odbc_connect("Driver={SQL Server};Server=XXXXXXX;Database=Sampledata;","XX","XXXXX");
$query="SELECT [password] FROM [Simcarddata].[dbo].[MasterUser] Where username='$UN'";
$rs=odbc_exec( $scon, $query );
if (!$rs) {
$msg="SQL statement failed with error:\n";
$msg.=odbc_error($scon).": ".odbc_errormsg($scon)."\n";
} else {
$number_of_rows = odbc_num_rows($rs);
$msg="$number_of_rows records found.\n";
}
while( odbc_fetch_row( $rs ) ) {
$field1 = odbc_result($rs,1);
if ($PS == $field1){
print ("TRUE");
header("Location: /test.php");
} else {
print ("Incorrect Username or password");
}
}
odbc_close($scon);
header("Refresh:2");
}
?>
</body>
</html>
if ($_SERVER['REQUEST_METHOD'] === 'POST') use this please instead of if($_POST) or use if(isset($_POST))

Retrieving username and password from Mongodb using php with angular js

I have created a simple login page using mongodb , angular js and php. when the user login from the database by retrieving username and password from the database, it goes to the admin page. But the login from database is not responding as unable to fetch data from db
index.php:
This is the homepage of the website.
<?php
include('login.php'); // Includes Login Script
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>LoginIN</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
<link href="styles/bootstrap.min.css" rel="stylesheet">
<link href="styles/signin.css" rel="stylesheet">
</head>
<body>
<?php
if(isset($error) and count($error) > 0){
?>
<div class="errorContainer"> <ul>
<?php foreach($error as $err) echo '<li>'.$err.'</li>'; ?>
</ul></div>
<?php
}
if(!empty($success)){
echo '<p class="text-success">'.$success.'</p>';
}
?>
<div id="wrapper">
<header id="top">
<center><h1>Leave Reporting System</h1></center>
<div class="container">
<div ng-app ='angularPost' ng-controller='loginCtrl'>
<form class="form-signin" role="form" action ="" method="post">
<h2 class="form-signin-heading">Please sign in</h2>
<input type="email" name="username" class="form-control" ng-model="username" placeholder="Email address" required autofocus>
<input type="password" name="password" class="form-control" ng-model="password" placeholder="Password" required>
<br>
<div class="checkbox">
<label>
<input type="checkbox" value="remember" name ="remember">Remember me
<br>
</label>
</div>
<input name="submit"button class="btn btn-lg btn-primary btn-block" ng-click=login() type="submit" value=" Sign in">
<span>{{responseMessage}}</span>
<br>
Forgot your password?
</form>
</div>
</body>
</html>
login.php
<?php
$succss = "";
if(isset($_POST['submitForm'] )){
$usr_email = $_POST['username'];
$usr_password = $_POST['password'];
$error = array();
if(empty($usr_email) or !filter_var($usr_email,FILTER_SANITIZE_EMAIL)){
$error[] = "Empty or invalid email address";
}
if(empty($usr_password)){
$error[] = "Enter your password";
}
if(count($error) == 0){
$con = new MongoClient();
if($con){
// Select Database
$db = $con->lrs;
// Select Collection
$Login = $db->Login;
$qry = array("username" => $usr_email,"password" => md5($usr_password));
$result = $Login->findOne($qry);
if($result){
$success = "You are successully loggedIn";
// Rest of code up to you....
}
} else {
die("Mongo DB not installed");
}
}
}
?>
app.js
var app = angular.module('angularPost',[]);
app.controller('loginCtrl', function($scope, $http)
{
$scope.login = function() {
var request = $http({
method : "post",
url : "login.php",
data : {
email : $scope.username,
password: $scope.password
},
});
request.success(function(data)
{
if(data == "1"){
$scope.responseMessage = "Successfully Logged in";
}
else{
$scope.responseMessage= "Username or Password is invalid"
}
});
}
});

use on div at a time using $_SESSION

I want to use one div at a time using an echo and $_SESSION. When I put this on the web it only shows $form. Can you see if I'm doing anything wrong?
$signedIn ='<h3 id="throughHeader"> Account options</h3><br/>
<p id="throughP"> <a href="convenientaccountinfo.php> Account Info </a></p><br/>
<p id="throughP"><a href="convenientaddaddress.php> Add Address </a></p><br/>
<p id="throughP"> <a href="convenientaddcreditcard.php> Add C. Card </a></p><br/>
<p id="throughP"> <a href="convenientsignout.php> Sign Out </a></p>';
$form='<form id="signInForm" method="POST" action=""><h3 id="formHeader">Sign Into Account</h3><br/>
<p id="pRegister"><a id="register" href="convenientregisterpage.php"> Register </a></p><br/>
<label>Email Addr:</label><input type="text" name="userEmail" id="email" size="15"/><br/>
<label>Password:</label><input type="password" name="password" id="password" size="15"/><br/>
<input type="submit" value="Sign In" id="formSubmit" name="submit"/> </form>';
$username = $_SESSION['userEmail'];
if(!$username){
$signedInForm="$form";
}
else{
$signedInForm="$signedIn";
}
}
This is the form POST with validating until it sets the $_SESSION. Thanks for looking at it again.
$email=$_POST['userEmail'];
$password=$_POST['password'];
if(isset($_POST['submit'])){
if(empty($email) || empty($password)){
$msg_to_user3="Fill in both fields";
}
else{
$results=mysql_query("SELECT * FROM register WHERE userEmail='$email'");
if (mysql_num_rows($results)==0)
$msg_to_user3 ="No such User";
else
{
while ($login_row = mysql_fetch_assoc($results))
{
$password_db = $login_row['password'];
if ($password!=$password_db){
$msg_to_user3 ="Password doesn't match";
}
if ($password_db!=$password){
$msg_to_user2="<a id='forgetpassword' href='convenientforgotpassword.php'>Forget Password</a>";
}
else
{
$active = $login_row['active'];
$userEmail = $login_row['userEmail'];
if ($active==0){
$msg_to_user3= "Activate account at ($userEmail) </p>";
}
else
{
$_SESSION['userEmail']=$username;//assign session
}
}
}
}
}
}
<html>
<body>
<div id="formSignIn">
<?php echo $signedInForm ;?>
</div>
</body>
</htmo>
Ok, I got the $_SESSION working which switched in between the $form and $signedIn variables. And as far as two only showing with the p s I took the ids off and in the a href the quotes weren't closed so it didn't shut each link. Thanks for all your help!!

Categories