I am confused about the php involving reCAPTCHA - javascript

i'm trying to make a very basic website that includes reCAPTCHA. i've obtained my site key and secret key and followed 2 tutorials so far with no luck
the sites goal is to use a form to obtain a number from the user as input and display a string once the reCAPTCHA is successful and the submit button is pressed
here is my code so far
<!DOCTYPE HTML>
<html> <!-- template-->
<head>
<title>template</title>
<script src="lib/jquery-2.1.4.min.js"></script>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<form action="/verify.php" method="get">
Number:<br>
<input type="text" name="firstname"><br>
<div class="g-recaptcha" data-sitekey="6LcKeGwUAAAAAOdDqu2CzJxZdgYUXEUEPQKZBOtn"></div>
<input type="submit" value="Submit" />
</form>
</body>
</html>
and here is my php
<html>
<body>
The number is <?php echo $_GET["number"]; ?><br>
<?php
if ($_GET["number"] == 42)
echo "42 is the right answer!";
?>
</body>
</html>
as of now the site works fine... except i don't know how to add the reCAPTCHA code and googles documentation confused me because i know very little about php.
any code samples or links to simple documentation is greatly appreciated. this is my first post on stackoverflow... i hope i followed to rules well enough

this would be your verify.php
$post_data = http_build_query(
array(
'secret' => CAPTCHA_SECRET, //as provided from google
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $post_data
)
);
$context = stream_context_create($opts);
$response = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
$result = json_decode($response);
if ($result->success) {
//success,
echo $_GET["firstname"]; //your input field name was 'firstname' not 'number'
}else{
echo 'we think you are a bot';
//fail
}

I would suggest changing your HTML code to this:
<form method="post" action="verify.php">
Number:<br>
<input type="text" name="number"><br>
<?php
require_once('recaptchalib.php');
$publickey = "your_public_key"; // you got this from the signup page
echo recaptcha_get_html($publickey);
?>
<input type="submit" />
</form>
<!-- more of your HTML content -->
</body>
and in verify.php add this:
<?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
if (isset($_POST['number']) && $_POST['number'] == '42') {
echo "42 is the right answer!";
}
}
?>

Related

Fix/modernize website log in that queries another site for authentication

First, please look at https://staging.upstatetoday.com/letmein
I have inherited a very old log in mechanism that has begun to not work lately - Firefox refuses to log users in, other browsers can be iffy, too. The site is wordpress, but the login is a different server (paywall).
Correct behavior is: insert username and password, click login button, page refreshes and sends user to the homepage if authentication is valid; alert drops that the username/password is incorrect if invalid.
This only seems to happen corectly in Chrome on the desktop, and sometimes in Edge. Firefox just refreshes the page. There are no js errors.
The login button is supposed to call a JS function that stores the current url (not needed in this implementation) then calls a function (in the wordpress functions.php file) that queries a separate site with the username and password and receives an XML response. That response is evaluated for a Yes and the user is allowed in or not, based on that xml response. If the user is allowed, the JS function returns the user to the page where they last were. If they are not allowed, the JS function alerts with bad user or pass msg.
Anyone can go to any post or page, but the single.php template is modified to check for authentication. If they are authenticated, they see the post. If not, they see a notice to subscribe or log in.
But, There's more going on in the code that is not needed (?) and I think there is unnecessary duplication of the process.
You can see the dialog at the link on top. Please ignore the styling (coming later).
I have moved code, tried snippets, php sessions, but nothing is working in Firefox at all, and with no error messages, I do not know how to proceed.
This is the code for the login dialog:
<?php if(!isset($_SESSION['auth']) ) { ?>
Forgot user name/password? Click Here
<form>
<div class="form-group">
<label for="pwd">User name:</label>
<input type="text" autocomplete="user-name" class="form-control" id="user-name" placeholder="Enter user name" style="width:200px; margin-bottom:5px;"/></div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" autocomplete="current-password" class="form-control" id="pwd" placeholder="Enter password" style="width: 200px;margin-bottom:5px;"/> <button type="submit" class="btn btn-primary" id="sub-sign-in" style="color:blue;font-size:1.0em">Log in to Upstate Today</button> </div>
</form>
<button class="btn btn-default">Register or Renew Subscription </button>
<?php } else { ?>
"<script type="text/javascript">
function Redirect()
{
window.location="https://staging.upstatetoday.com";
}
document.write("You will be redirected to the homepage in 5 seconds");
setTimeout('Redirect()', 5000);
</script>"
<?php } ?>
This is the js that is called by "sub-sign-in" :
jQuery(document).ready(function( $ ){
var pageURL = $(location).attr("href");
localStorage.setItem("page_url", pageURL);
console.log('ready');
$('#sub-sign-in').click(function(){
console.log('enter');
var user_name=$('#user-name').val();
var password=$('#pwd').val();
$.ajax({
type: "POST",
url: '/wp-admin/admin-ajax.php',
data: ({
action: "check_address",
name: user_name,
pass:password
}),
success: function (response){
console.log(response);
var pg_url = localStorage.getItem("page_url");
if(response == 'Yes0'){
window.location.replace(pg_url);
}
else{
alert('wrong username or password');
}
},
error: function(error){
console.log(error);
}
});
});
});
This is the code from the child theme functions.php
function register_my_session()
{
if( !session_id() )
{
session_start();
}
}
add_action('init', 'register_my_session');
/* session_write_close(); */
function check_address()
{
$name = $_POST["name"];
$password = $_POST["pass"];
/*$edition = $_POST["edition"];
$subdate = $_POST["subscriptiondate"]*/
$response = wp_remote_get( 'https://seneca.newzware.com/authentication/auth70_xml.jsp?site=seneca&login_id='.$name.'&password='.$password);
$xml = simplexml_load_string($response['body']);
$isValid = (string) $xml->authenticated;
if(!session_id()) {
session_start();
}
if($isValid == 'Yes'){
$_SESSION['auth'] = '1';
}
echo $isValid;
}
add_action( 'wp_ajax_check_address', 'check_address' );
add_action( 'wp_ajax_nopriv_check_address', 'check_address' );
add_action( 'wp_enqueue_scripts', 'hello_elementor_child_enqueue_scripts', 20 );
function wpb_widgets_init() {
register_sidebar( array(
'name' => 'Custom Header Widget Area',
'id' => 'newzware-widget',
'before_widget' => '<div class="newzware-widget">',
'after_widget' => '</div>',
'before_title' => '<h2 class="newzware-title">',
'after_title' => '</h2>',
) );
}
add_action( 'widgets_init', 'wpb_widgets_init' );
This is the single post content that includes whether the user can read that post or not (ie, is authenticated):
<?php
/**
* The template for displaying singular post-types: posts, pages and user-defined custom post types.
*
* #package HelloElementor
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
?>
<?php
while ( have_posts() ) :
the_post();
?>
<main id="content" <?php post_class( 'site-main' ); ?> role="main">
<?php if ( apply_filters( 'hello_elementor_page_title', true ) ) : ?>
<header class="page-header">
<?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
</header>
<?php endif; ?>
<!-- Newzware Protection Code -->
<?php
$key = 'Free Story';
$themeta = get_post_meta($post->ID, $key, TRUE);
if($themeta != '') {
$free_story = 1;
}
?>
<?php if($_SESSION['auth'] == '1' OR current_user_can( 'read_post' ) OR $free_story == '1' ) { ?>
<!-- end part 1Newzware Protection Code -->
<div class="page-content">
<?php the_content(); ?>
<!-- beginpart 2 Newzware Protection Code -->
<?php } else { ?>
<div class='ifsub-panel'> <div class='ifsubpanel-heading' style='background:#2318A4; color:#fff; text-align:center;'><b>Subscribe To The Journal</b></div><div class='ifsubpanel-body'> <p style='text-align:center'>
If you are already registered with UpstateToday.com, please click the LOGIN button in the upper left corner of this window to log in and continue reading.<br><br>
If you'd like to subscribe,<br>
Please click here for options. We'd love for you to join our family.</b></p>
</div></div>
<?php } ?>
<!-- End Newzware Protection Code -->
<div class="post-tags">
<?php the_tags( '<span class="tag-links">' . __( 'Tagged ', 'hello-elementor' ), null, '</span>' ); ?>
</div>
<?php wp_link_pages(); ?>
</div>
<?php comments_template(); ?>
</main>
<?php
endwhile;
I want to make this work reliably in desktop and mobile browsers. I'd love to have a user tap a login button, go to a page with the dialog, log in, then return to the home page.
Thanks for your time and pointers.

How to submit data using ajax and display result without refreshing

EDIT:
SOLVED. Thank you all for help. :)
EDIT:
Your suggestions worked. The problem now is that after the first find and displaying the found result, the found set stays the same no matter what i try to find next. Even after restarting the browser. Is it possible that the found data stays somewhere in server cache and is displayed as a result?
I'm trying to send data from the form using jquery to php file process it there and then display the result from it.
After pressing the submit nothing happens. There are no errors in the console.
Everything worked before i added jquery but after that i don't see any result.
My HTML:
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
</head>
<body>
<form id="my_form">
Imie: <br/> <input name="name" id="firstname" type="text" /><br />
<input id="submit_form" type="submit" value="Submit">
</form>
<div id="update_div"></div>
<script>
var submit_button = $('#submit_form');
submit_button.click(function() {
var var_name = $('firstname').val();
var update_div = $('#update_div');
console.log('zmienna var_name ' + var_name);
console.log('zmienna update_div ' + update_div);
$.ajax({
type: 'GET',
url: 'test.php',
data: var_name,
success: function(response){
update_div.html(response);
}
});
});
</script>
</body>
</html>
My PHP:
<?php
require 'db_handler.php';
$criterion_name = $_GET['name'];
$query = $fm->newFindCommand("OFERTY tabela");
$query->addFindCriterion('kontrahent_opiekun', "=" . $criterion_name);
$result = $query->execute();
if(FileMaker::isError($result)){
echo($result->getMessage());
return;
}
$i = 0;
// Get array of found records
$records = $result->getRecords();
foreach ($records as $record) {
echo $record->getField('_kp_oferta') . " - ";
echo $record->getField('kontrahent_Skrot') . " - ";
echo $record->getField('kontrahent_opiekun') . '</br>';
$i++;
}
echo $i . " Pozycje";
?>

Php post form without refresh page

I try to post my form to Mysql without refreshing page. I did these with looiking sources but not working. Could you help me?
<script>
$('#submit').click(function() {
$.ajax({
url: 'submit.php',
type: 'POST',
data: {
message: '*I couldnt find this partwhat should i write*'
}
}
});
});
</script>
<form method="post">
<textarea name="message" rows="3" cols="30">
</textarea><br><br>
<input type="submit" value="Submit">
</form>
Submit.php
<?php
include "connect.php";
if(isset($_POST['message'])) {
header('Location: ' . $_SERVER['HTTP_REFERER']);
$post = $_POST['message'];
$date = date("y-m-d G:i:s");
$query = $db->prepare("INSERT INTO chat_messages SET senderid = ?, receiverid = ?, message = ?, mod_time = ?");
$insert = $query->execute(array( $a, $b, $post, $date));
}?>
In jQuery, the click event is being triggered on an element that has an id of submit (it is id because it is represented by #)
$('#submit').click(function() {
Your submit button does not have the ID of "submit"
Change the input tag as follows:
<input id="submit" type="submit" value="Submit" />
Another problem, as #Rajan in comments pointed out, you have an extra brace. So, change:
data: {
message: '*I couldnt find this partwhat should i write*'
}
}
to:
data: {
message: '*I couldnt find this partwhat should i write*'
}
Also, I recommend that you show return some kind of message from submit.php page, for example:
echo 'Entry Added';
The above is just an example output to get you going... you really should be doing checks such as: did the entry get inserted without any errors, etc.
Edit
Also note: you are using type as one of the settings. Per the official jQuery documentation of jQuery.ajax(), type is:
An alias for method. You should use type if you're using versions of jQuery prior to 1.9.0.
(i.e. use method instead, if using jQuery version >1.9.0)
Lastly, take a look at the answer provided by #Faisal as well...
You are submitting form data through Ajax query, hence you do not need to include header('Location: ' . $_SERVER['HTTP_REFERER']); in your submit.php file.
<form>
<textarea name="message" rows="3" cols="30"></textarea>
<br>
<input type="submit" value="Submit">
</form>
<script>
$(document).ready( function() {
$("form").on("submit", function(e) {
e.preventDefault(); // Prevent default form submission action
$.post("submit.php", $("form").serialize()); // Post the data
$('textarea[name=message]').val(''); // Clear the textarea
});
});
</script>
Also, are the variables $a and $b defined in submit.php file?
$.post('../submit.php',{message:message}, function(data) {
$('.results').html(data);
});
use a div where you want to display the result
<div class="results"></div>
to finish your submit.php have to send something at the end so try this
<?php
include "connect.php";
if(isset($_POST['message'])) {
header('Location: ' . $_SERVER['HTTP_REFERER']);
$post = $_POST['message'];
$date = date("y-m-d G:i:s");
$query = $db->prepare("INSERT INTO chat_messages SET senderid = ?, receiverid = ?, message = ?, mod_time = ?");
$insert = $query->execute(array( $a, $b, $post, $date));
}
echo "it works";
?>

How to give authentication to load pages?

I have created some pages using html and php. In home page I have links of all pages. Now I want to add authentication to each page. The page should not get open without the authentication.
For this I have created one login page which will check authentication.
Now from home page I want to open the login page if any page's link is clicked, and if the login is successful I want to open the page which link is clicked.
Home Page:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Questions</title>
</head>
<body>
Add a chapter<br><br>
Upload a file<br><br>
Upload a video<br><br>
Add a question<br><br>
Delete chapters<br><br>
Delete Files<br><br>
Delete video Files<br><br>
Delete questions
</body>
</html>
Login page:
<!DOCTYPE html>
<html>
<head>
<body>
<form action="Login.php" method="post" enctype="multipart/form-data">
Enter Username : <input name = "userName" type = "text"><br><br>
Enter Password : <input name = "pass" type = "text"><br><br>
<input name="submit" type="submit" value = "Submit"><br><br>
<?php
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
header("Pragma: no-cache"); // HTTP 1.0.
header("Expires: 0"); // Proxies.
ini_set('display_errors', 1);
error_reporting(1);
ini_set('error_reporting', E_ALL);
$dbh = new PDO('mysql:host=174.138.74;dbname=_pro','rpro', 'ro12345');
if(isset($_POST['submit'])) {
if (!empty($_POST['userName']) && !empty($_POST['pass'])) {
$stmt = $dbh->prepare("select * FROM `users` WHERE `username`= :uName and `pass` = :pass");
$stmt->bindParam("uName", $_POST['userName']);
$stmt->bindParam("pass", $_POST['pass']);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
if ($count > 0) {
echo 'Login Successful.';
?>
<?php
} else {
echo 'Please enter correct username and password.';
}
}
else{
echo 'Please enter username and password.';
}
}
?>
</form>
</body>
</head>
</html>
How can I achieve this? Please help. Thank you..
You can make your all links like these...
Add a chapter<br><br>
Upload a file<br><br>
Upload a video<br><br>
Add a question<br><br>
Delete chapters<br><br>
Delete Files<br><br>
Delete video Files<br><br>
Delete questions
Then when user will click on any link, it'll redirect them to login.php page. At there make all kind of validation of user credentials & if validation is found out as TRUE then get redirect part of URL from the previous link & reconstruct the destination page once again by
$destination_page = $_GET['redirect'];
& redirect the user to that page else ask the user for login again.
You can authenticate using sessions as:
After successfully logged in, create $_SESSION[]
Create common file where you can check is session set
if session is not set then you can redirect to login page
include this file in all pages
Set a session variable. Note that you should put headers at the top, before any output.
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
header("Pragma: no-cache"); // HTTP 1.0.
header("Expires: 0"); // Proxies.
ini_set('display_errors', 1);
error_reporting(1);
ini_set('error_reporting', E_ALL);
$dbh = new PDO('mysql:host=174.138.74;dbname=_pro','rpro', 'ro12345');
if(isset($_POST['submit'])) {
if (!empty($_POST['userName']) && !empty($_POST['pass'])) {
$stmt = $dbh->prepare("select * FROM `users` WHERE `username`= :uName and `pass` = :pass");
$stmt->bindParam("uName", $_POST['userName']);
$stmt->bindParam("pass", $_POST['pass']);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$count = $stmt->rowCount();
if ($count > 0) {
$_SESSION['authenticated_user'] = $_POST['userName'];
header("Location: http://www.example.com/loginsuccess.php");
?>
<?php
} else {
echo 'Please enter correct username and password.';
}
}
else{
echo 'Please enter username and password.';
}
}else{
?><!DOCTYPE html>
<html>
<head>
<body>
<form action="Login.php" method="post" enctype="multipart/form-data">
Enter Username : <input name = "userName" type = "text"><br><br>
Enter Password : <input name = "pass" type = "text"><br><br>
<input name="submit" type="submit" value = "Submit"><br><br>
</form>
</body>
</head>
</html>
<?php
}
?>
Now on the other pages check if they are authenticated by checking the session.
<?php
if (!isset($_SESSION['authenticated_user'])){
header("Location: http://www.example.com/noaccess.php");
}
?>

Passing Variable From JavaScript to PHP without Page Refresh [duplicate]

This question already has answers here:
Passing javascript variable to php without refreshing the page
(2 answers)
Closed 8 years ago.
I'm writing some code that has a variable in JavaScript that must be passed into the PHP script in the same document. The user input will be used to be scraped from some external site.
The JavaScript variable is HtmlLink, and it needs to be passed to the PHP code where it says INSERT HTMLLINK VARIABLE HERE without reloading the page.
<!DOCTYPE HTML>
<HEAD>
<TITLE>Test Input</TITLE>
<SCRIPT>
type = "text/javascript"
function testResults (form) {
var TestVar = form.inputbox.value + ".html";
var HtmlLink = "www.mp3skull.com/mp3/" + TestVar;
document.write(HtmlLink);
}
</SCRIPT>
<?php
$contents = file_get_contents('INSERT HTMLLINK VARIABLE HERE');
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($contents);
libxml_clear_errors();
$xpath = new DOMXpath($dom);
$element = $xpath->query('//div[#id="right_song"]/div[3]/div[1]/div[1]/a')->item(0)-
echo $element;
?>
</HEAD>
<BODY>
<FORM NAME="myform" ACTION="" METHOD="GET"> Song Name <BR>
<INPUT TYPE="text" NAME="inputbox" VALUE=""><P>
<INPUT TYPE="button" NAME="button" Value="Search" onClick="testResults(this.form)">
</FORM>
</BODY>
</HTML>
If you want to do some searching, first of course build the proper URL first, then from there search/scrape the site, actually the base code is already working so its time to build on that. You can do something like this: Sample Demo
$main_url = 'http://www.mp3skull.com/mp3/';
$results = array();
if(isset($_POST['submit'])) {
// handle input (sample: hot mallets)
$input = preg_replace('/[\s]+/', '_', strtolower(trim($_POST['input'])));
$main_url .= $input . '.html'; // turns to hot_mallets.html
$contents = #file_get_contents($main_url);
if($contents !== false) { // simple error checking
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($contents);
libxml_clear_errors();
$xpath = new DOMXpath($dom);
$search_results = $xpath->query('//div[#id="song_html"]');
if($search_results->length > 0) {
foreach($search_results as $result) {
// each row result, put it inside the array
$results[] = $xpath->query('//div[#id="right_song"]/div[3]/div[1]/div[1]/a', $result)->item(0)->getAttribute('href');
}
} else {
echo 'Zero results';
}
} else {
echo 'Some error on getting results from external site.';
exit;
}
}
?>
<form method="POST">
<label for="inputbox">Song Name: <input type="text" id="inputbox" name="input"/ ></label>
<input type="submit" name="submit" />
</form>
<?php if(!empty($results)): ?>
<h3>Search Results:</h3>
<ul>
<?php foreach($results as $result): ?>
<li><?php echo $result; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
Because of the way that pages are loaded on the web this doesn't really make sense in most setups. The PHP runs on the server, sends the javascript and HTML to the client and then the javascript executes on the client. At that point in the process it's too late for javascript to set a variable in php because php is already finished loading. You could use ajax to send the request from javascript. If you did that the page would load like this:
(Server gives initial HTML/javascript/CSS to client)->(Client runs javascript which makes request to server (after the user has entered the data))->(Result of external request returns and is now usable by javascript).
You don't really need to do that for what you're trying to do though - fetch a link off of another page. What you should really do is write your javascript stuff in php and then echo out the link. Then, set the form to submit back to the same page. Here's an example:
<!doctype html>
<head>
<title>Fetch Link</title>
</head>
<body>
<?php
ini_set('display_errors', 0);
if (isset ($_GET['search_term']))
{
$searchTerm = $_GET['search_term'];
$searchPage = "http://www.example.com/".$searchTerm.'.html';
$searchPageContents = file_get_contents($searchPage);
$feedBack = '';
$failedMessage = 'Sorry, we couldn\'t match your search =(';
if ($searchPageContents !== FALSE)
{
$searchPageDom = new DOMDocument();
if (!$searchPageDom->loadHTML($searchPageContents))
$feedBack = $failedMessage;
else
{
$searchPageXpathWrapper = new DOMXpath($searchPageDom);
$searchLinkNode = $searchPageXpathWrapper
->query('SOME QUERY HERE')
->item(0);
$searchLink = $searchPageDom->saveHTML ($searchLinkNode);
$feedBack = $searchLink;
}
}
else
$feedBack = $failedMessage;
}
else
$feedBack = 'Please enter a search term';
echo $feedBack.'<br>';
?>
<form name="myform" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="GET">
<label for='search_name' for='search_term'>Search Term</label>
<input type="text" name="search_term">
<input type='submit' value='Search'>
</form>
</body>
</html>
Of course, unless you have a particularly good reason to be fetching the link from the page instead of just generating the link yourself - you can generate the link yourself with minimal javascript and save the round trip to the server and guard against the possibility of the page formatting changing on the other side.

Categories

Resources