I have the code from below, once the form is sended I want to check in it if the user passed the recaptcha test. How do i do it? Searched many things and i can't find a way that works for me ..
<html>
<head>
<script type="text/javascript">
var verifyCallback = function(response) {
alert(response);
};
var onloadCallback = function() {
grecaptcha.render('example3', {
'sitekey' : '6LdlRIgaAAAAAJXOu3EsuGVnKVjmSaWfSbuwSHLI',
'callback' : verifyCallback,
'theme' : 'dark'
});
};
</script>
</head>
<body>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
// here I want to verify if the use user passed the recaptcha
{
some code
}
}
?>
<form method="POST">
<div id="example3"></div>
<br>
<input type="submit" value="Submit">
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer>
</script>
</body>
</html>
You should lookup the Server side validation docs for reCAPTCHA:
https://developers.google.com/recaptcha/docs/verify
You have to send an API request via PHP CURL, as stated in the docs:
URL: https://www.google.com/recaptcha/api/siteverify METHOD: POST
So something like this:
function validate_captcha($secret, $response, $remoteip) {
$captcha_url = "https://www.google.com/recaptcha/api/siteverify";
$captcha_url .= "?secret=".$secret;
$captcha_url .= "&response=".$response;
$captcha_url .= "&remoteip=".$remoteip;
$ch = curl_init($captcha_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
$response=json_decode($data,true);
if ($response["success"]) {
return true;
}
else {
return false;
}
}
And you call the function like this:
$captcha_is_ok = validate_captcha(
"......mySecret.....",
$_POST['g-recaptcha-response'],
$_SERVER['REMOTE_ADDR']);
if ($captcha_is_ok) {
... do something cool ...
} else {
... don't do something cool ...
}
Related
I am trying to figure out how to send back a value to the Ajax popup box. Currently, the value that gets returned is just the JSON that comes back from the API call. I would much rather use jsondecode to pull out a specific value and have that return, or... lets not even get that complex. I just want to set a variable equal to some message such as "API GET complete" and return that to the Ajax box. This will also help with troubleshooting so I can return a variable to see if things are working. As I said, currently the Ajax popup just displays the JSON that comes back from the API call. This is my first time working with both Ajax and curl_setopt so if you can please make recommendations with examples, that would be fantastic! Thank you!
test.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'auto.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
alert(response);
});
});
});
</script>
</head>
<body>
<input type="submit" class="button" name="test" value="Test" />
</body>
</html>
auto.php
<?php
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'Test':
Test();
break;
case 'to_the_n':
to_the_n();
break;
}
}
function Test() {
$ch = curl_init('https://api.digitalocean.com/v2/droplets?tag_name=MYTAG');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer MYTOKEN','Content-Type: application/json'));
$result = curl_exec($ch);
$message = "Yay it worked" //Send this message back to Ajax popup, not the API reply
exit;
}
?>
* UPDATE *
* UPDATE *
You can just echo the value from php and it will be alerted in the Ajax success function.
echo 'Yay it worked!! ';
<?php
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'Test':
if(Test() == true) {
echo('yay it worked!! ');
exit;
}
break;
case 'to_the_n':
to_the_n();
break;
}
}
function Test() {
$ch = curl_init('https://api.digitalocean.com/v2/droplets?tag_name=MYTAG');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer MYTOKEN','Content-Type: application/json'));
$result = curl_exec($ch);
return true;
}
?>
I am using Facebook AccountKit to login users with SMS and Emails. SMS Login is simple user have to enter the OTP and then he can login to our website. But in case of Login with Email. AccountKit sends a verification link to users email and after verifying he can login to account. Now in this case if a user wants to login he will have to verify his email id everytime. Is there any way where we can skip the verification part everytime and just match the Id and email ID to login ?
I am using Elaniin code for the Account Kit API.
<?php
// function to verify session status
function is_session_started()
{
if ( php_sapi_name() !== 'cli' ) {
if ( version_compare(phpversion(), '5.4.0', '>=') ) {
return session_status() === PHP_SESSION_ACTIVE ? TRUE : FALSE;
} else {
return session_id() === '' ? FALSE : TRUE;
}
}
return FALSE;
}
// verifying POST data and adding the values to session variables
if(isset($_POST["code"])){
session_start();
$_SESSION["code"] = $_POST["code"];
$_SESSION["csrf_nonce"] = $_POST["csrf_nonce"];
$ch = curl_init();
// Set url elements
$fb_app_id = '465871913602533';
$ak_secret = 'eab92d7c75f08c6e95a48341c80b3ffc';
$token = 'AA|'.$fb_app_id.'|'.$ak_secret;
// Get access token
$url = 'https://graph.accountkit.com/v1.0/access_token?grant_type=authorization_code&code='.$_POST["code"].'&access_token='.$token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
$info = json_decode($result);
// Get account information
$url = 'https://graph.accountkit.com/v1.0/me/?access_token='.$info->access_token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
$final = json_decode($result);
}
?>
<html>
<head>
<title>Login with Account Kit</title>
<link rel="shortcut icon" href="ak-icon.png">
<link rel="stylesheet" href="css.css">
<!--Hotlinked Account Kit SDK-->
<script src="https://sdk.accountkit.com/en_EN/sdk.js"></script>
</head>
<body>
<?php
// verifying if the session exists
if(is_session_started() === FALSE && !isset($_SESSION)){
?>
<h1 class="ac">Login with Account Kit</h1>
<p class="ac">This example shows you how to implement<br>Facebook Account Kit for web using PHP.</p>
<div class="buttons">
<button onclick="phone_btn_onclick();">Login with SMS</button>
<button onclick="email_btn_onclick();">Login with Email</button>
</div>
<form action="" method="POST" id="my_form">
<input type="hidden" name="code" id="code">
<input type="hidden" name="csrf_nonce" id="csrf_nonce">
</form>
<?php
}else{
?>
<h1 class="ac">Login with Account Kit</h1>
<p class="ac">The session with Facebook Account Kit is already started.</p>
<h3 class="ac">Your Information</h3>
<p class="ac">
<!-- show account information -->
<strong>ID:</strong> <?=$final->id?> <br>
<?php
if(isset($final->email)){
?>
<strong>Email:</strong> <?=$final->email->address?>
<?php
}else{
?>
<strong>Country Code:</strong> +<?=$final->phone->country_prefix?> <br>
<strong>Phone Number:</strong> <?=$final->phone->national_number?>
<?php
}
?>
</p>
<div class="buttons">
<button onclick="logout();">Logout</button>
</div>
<?php
}
?>
</body>
<script>
// initialize Account Kit with CSRF protection
AccountKit_OnInteractive = function(){
AccountKit.init(
{
appId:465871913602533,
state:"abcd",
version:"v1.0"
}
//If your Account Kit configuration requires app_secret, you have to include ir above
);
};
// login callback
function loginCallback(response) {
console.log(response);
if (response.status === "PARTIALLY_AUTHENTICATED") {
document.getElementById("code").value = response.code;
document.getElementById("csrf_nonce").value = response.state;
document.getElementById("my_form").submit();
}
else if (response.status === "NOT_AUTHENTICATED") {
// handle authentication failure
console.log("Authentication failure");
}
else if (response.status === "BAD_PARAMS") {
// handle bad parameters
console.log("Bad parameters");
}
}
// phone form submission handler
function phone_btn_onclick() {
// you can add countryCode and phoneNumber to set values
AccountKit.login('PHONE', {}, // will use default values if this is not specified
loginCallback);
}
// email form submission handler
function email_btn_onclick() {
// you can add emailAddress to set value
AccountKit.login('EMAIL', {}, loginCallback);
}
// destroying session
function logout() {
document.location = 'logout.php';
}
</script>
</html>
I have been stuck on this for over a week and I think I am long overdue for asking on here.. I am trying to get my users to upload their video files using the jQuery File Upload Plugin. We do not want to save the file on our server. The final result is having the file saved in our Backlot using the Ooyala API. I have tried various approaches and I am successful in creating the asset in Backlot and getting my upload URLs, but I do not know how to upload the file chunks using the URLs into Backlot. I have tried FileReader(), FormData(), etc. I am pasting the last code I had that created the asset, and gave me the upload URLs, but did not save any chunks into Backlot. I assume I may be getting stuck in one of my AJAX calls, but I am not very sure.
I keep getting:
Uncaught InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable.
Here is my page with the JS for the jQuery File Upload widget by BlueImp:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="<?php print base_path() . path_to_theme() ?>/res/js/jQuery-File-Upload/js/vendor/jquery.ui.widget.js"></script>
<script type="text/javascript" src="<?php print base_path() . path_to_theme() ?>/res/js/jQuery-File-Upload/js/jquery.iframe-transport.js"></script>
<script type="text/javascript" src="<?php print base_path() . path_to_theme() ?>/res/js/jQuery-File-Upload/js/jquery.fileupload.js"></script>
</head>
<body>
<input id="fileupload" type="file" accept="video/*">
<script>
//var reader = FileReader();
var blob;
$('#fileupload').fileupload({
forceIframeTransport: true,
maxChunkSize: 500000,
type: 'POST',
add: function (e, data) {
var goUpload = true;
var ext = ['avi','flv','mkv','mov','mp4','mpg','ogm','ogv','rm','wma','wmv'];
var uploadFile = data.files[0];
var fileName = uploadFile.name;
var fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);
if ($.inArray( fileExtension, ext ) == -1) {
alert('You must upload a video file only');
goUpload = false;
}
if (goUpload == true) {
$.post('../sites/all/themes/episcopal/parseUploadJSON.php', 'json=' + JSON.stringify(data.files[0]), function (result) {
var returnJSON = $.parseJSON(result);
data.filechunk = data.files[0].slice(0, 500000);
data.url = returnJSON[0];
//reader.onloadend = function(e) {
//if (e.target.readyState == FileReader.DONE) { // DONE == 2
//data.url = returnJSON[0];
// }
//}
//$.each(returnJSON, function(i, item) {
//data.url = returnJSON[0];
//blob = data.files[0].slice(0, 500000);
//console.log(blob);
//reader.readAsArrayBuffer(blob);
//data.submit();
//});
data.submit();
});
}
},//end add
submit: function (e, data) {
console.log(data); //Seems fine
//console.log($.active);
$.post('../sites/all/themes/episcopal/curlTransfer.php', data, function (result) { //fails
console.log(result);
});
return false;
}
});
</script>
</body></html>
Then there is the parseUploadJSON.php code, please keep in mind that my real code has the right Backlot keys. I am sure of this:
<?php
if(isset($_POST['json'])){
include_once('OoyalaAPI.php');
$OoyalaObj = new OoyalaApi("key", "secret",array("baseUrl"=>"https://api.ooyala.com"));
$expires = time()+15*60; //Adding 15 minutes in seconds to the current time
$file = json_decode($_POST['json']);
$responseBody = array("name" => $file->name,"file_name"=> $file->name,"asset_type" => "video","file_size" => $file->size,"chunk_size" => 500000);
$response = $OoyalaObj->post("/v2/assets",$responseBody);
$upload_urls = $OoyalaObj->get("/v2/assets/".$response->embed_code."/uploading_urls");
$url_json_string = "{";
foreach($upload_urls as $key => $url){
if($key+1 != count($upload_urls)){
$url_json_string .= '"' . $key . '":"' . $url . '",';
}else {
$url_json_string .= '"' . $key . '":"' . $url . '"';
}
}
$url_json_string .= "}";
echo $url_json_string;
}
?>
Then I have the curlTransfer.php:
<?php
echo "starting curl transfer";
echo $_POST['filechunk'] . " is the blob";
if(isset($_FILES['filechunk']) && isset($_POST['url'])){
echo "first test passed";
$url = $_POST['url'];
//print_r(file_get_contents($_FILES['filechunk']));
$content = file_get_contents($_FILES['filechunk']);
print_r($content);
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt ($ch, CURLOPT_HTTPHEADER, Array("Content-Type: multipart/mixed"));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
try {
//echo 'success';
return httpRequest($ch);
}catch (Exception $e){
throw $e;
}
}
/****Code from Ooyala****/
function httpRequest($ch){
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($ch);
if(curl_error($ch)){
curl_close($ch);
return curl_error($ch);
}
$head=curl_getinfo($ch);
$content = $head["content_type"];
$code = $head["http_code"];
curl_close($ch);
}
?>
And the OoyalaApi.php is here (I saved a copy on my server):
https://github.com/ooyala/php-v2-sdk/blob/master/OoyalaApi.php
I apologize in advance if the code is messy and there's a lot of parts commented out. I have changed this code so much and I cannot get it. I appreciate all of your time and effort.
EDIT
I went back to trying FileReader out as this post Send ArrayBuffer with other string in one Ajax call through jQuery kinda worked for me, but I think it would be safer to read it using readAsArrayBuffer and now I am having trouble saving the array buffer chunks in some sort of array...
We have implemented ooyala file chunk upload in Ruby On Rails by referring this.
We have used the entire JS file as it is from this link.
https://github.com/ooyala/backlot-ingestion-library
I am using google currency converter.All is doing fine but on page refresh I can't get the input value set to its original value.Below is my code.
<script src = "js/CurrencyConverter.js" type="text/javascript"></script>
<select id="FromCurrency" class="CurrencyDropDown"></select>
<input type = "text" id = "UnitPrice" value="enter amount"/>
</br>
<select id="ToCurrency" class = "CurrencyDropDown"></select>
<input type = "text" id = "destinationPrice" value="result"/>
<script>
$(document).ready(function(){
$('select#ToCurrency').change(function(){
convertcurrency();
})
});
function convertcurrency(){
var url = $('input[type=hidden]').val();
var priceunit = $('input#UnitPrice').val();// alert(priceunit);
var fromcurrencycode = $('select#FromCurrency').val(); //alert(fromcurrencycode);
var tocurrencycode = $('select#ToCurrency').val();// alert(tocurrencycode);
ConvertCurrency(url, priceunit,fromcurrencycode,tocurrencycode);
}
function ConvertCurrency(Url , PriceUnit,fromCurrencyCode,toCurrencyCode){
$.ajax({
url: '<?php echo site_url('curchange')?>',
type : 'POST',
dataType: "html",
data : {unitprice : PriceUnit, fromcode : fromCurrencyCode, tocode : toCurrencyCode},
success: function (data) {
if(data != '')
$('input#destinationPrice').val(data);
else
alert('Cannot convert');
},
error : function(){
alert('Error in Loading Data');
}
});
return false;
}
</script>
in CurrencyConverter.js I have list of countries which on window load is loaded to dropdown.
curchange.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Curchange extends CI_Controller{
function __construct() {
parent::__construct();
}
function index(){
$unit = $this->input->post('unitprice');
$from = $this->input->post('fromcode');
$to = $this->input->post('tocode');
$url = 'http://www.google.com/ig/calculator?hl=en&q='.$unit.$from.'=?'.$to;
$ch = curl_init();
$timeout = 0;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$rawdata = curl_exec($ch);
curl_close($ch);
$data = explode('"', $rawdata);
$error = explode(' ', $data[5]);
if(empty($error[0])){
$data = explode(' ', $data[3]);
$var = round($data[0], 3);
}else{
$var = '';
}
echo $var;
}
}
?>
The code is working fine.Currency is being converted but when I change the currency and then refresh the page instead of showing input value as 'enter amount' and 'result' the input html tag is showing the initial values.Why?
any help/suggestions are welcome.
Write two statements after $(document).ready(function(){
like:
$(document).ready(function(){
$("#UnitPrice").val("enter amount");
$("#destinationPrice").val("result");
});
It will set default value on page refresh
I'm using CURL to scrape a website like this:
<?php
$url = "http://www.bbc.com/news/";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$curl_scraped_page = curl_exec($ch);
curl_close($ch);
$curl_scraped_page = preg_replace("#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"'>]+)#",'$1http://www.bbc.com/news/$2$3', $curl_scraped_page);
echo $curl_scraped_page;
?>
As you can see the URL is set for BBC news. However, I would like the URL to be a variable instead. The variable would have to be the value of parent.document. In JQuery for example I would do this:
var value = $("input", parent.document.body).val();
How do I set something like that in PHP? I have Googled but I couldn't find anything about parent.document in PHP.
PHP is a server-side scripting language and therefore has no access to the current HTML page. It is processed before the HTML is sent to the client's browser, therefore parent.document doesn't even exist at the time the script is being processed.
If you would like to pass data from an HTML page to a PHP script, you can do so using an HTML <form> or through JavaScript/JQuery AJAX requests.
For example, the following code will pass the value of input to the PHP script:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function pass(){
var value = $("input", parent.document.body).val();
$.ajax({
type: "POST",
url: "myscript.php",
data: { mydata: value }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
</script>
</head>
<body>
<input type="text" />
<button onclick="pass();return false;">Pass Value</button>
</body>
</html>
And the revised script (myscript.php):
<?php
$url = isset($_POST['mydata']) ? $_POST['mydata'] : '';
$curl_scraped_page = '';
if(!empty($url)){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$curl_scraped_page = curl_exec($ch);
curl_close($ch);
$curl_scraped_page = preg_replace("#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"'>]+)#",'$1'.$url.'$2$3', $curl_scraped_page);
}
echo $curl_scraped_page;
?>
I would recommend using $(id) to retrieve the value of an <input> instead of $("input",context).
E.g.
var value = $('#txt').val();
And in the HTML:
<input type="text" id="txt" />
For more info on JQuery.ajax see here.