I have a code which I know how to perform certain API call with a link, it looks like this
<a class="btn btn-default" href="https://testapi.internet.bs/Domain/Transfer/Initiate?ApiKey='.$user.'&Password='.$pass.'&Domain='.$domain.$ext.'" role="button">Restart Transfer</a>
This works, but on the page of course it will show ApiKey=(actualKey) and the User and the PASSWORD which is not what I want. I understand this is how it works in a Link, but How can I do this with a button instead.
<form method="post" action="">
<button type="submit" class="btn btn-warning btn-lg btn-block" name="restartTransfer">Restart Transfer</button>
</form>
and Im guessing PHP action such as (Not saying this is the way, any way is appreciated using php, jquery or javascript)
if(isset($_POST['restartTransfer'])) {
}
Right now I do have it done like this
$(document).ready(function(){
$("button[name = 'restartTransfer']").click(function(){
window.location = "https://testapi.internet.bs/Domain/Transfer/Initiate?ApiKey=<?php print $user;?>&Password=<?php print $pass;?>&Domain=<?php print $domain;?>";
});
});
But this doesn't hide it, this just launches web browser window showing the API key user and pass..
How can I hide the API information in a button push (in the same page if possible)
The idea would be
Click this button
It loads the API call url (not shown)
Returns with a message "Complete" in a Div container called #message for sake of example
Thank you.
This might hide the actual URL from user in browser address bar. It will not, however, protect the credentials from being viewed either through profiling network requests, or viewing the source of the web page. I suggest using a PHP proxy to make it more secure.
$("button[name='restartTransfer']").click(function() {
$.ajax({
url: "https://testapi.internet.bs/Domain/Transfer/Initiate?ApiKey=<?php print $user;?>&Password=<?php print $pass;?>&Domain=<?php print $domain;?>",
type: 'GET',
dataType: 'text/plain',
success: function(data) {
$('#message').text(data); // print results
},
error: function(xhr) {
console.log('Error', xhr);
}
});
});
Using curl you can do it secure with php
<?php
class EBCommon{
public function call($sessionId, $sessionInfo, $realUser, $url, $parameters)
{
$apiUrl = "http://mycompany.edubrite.com/oltpublish/site/";
$curl_request = curl_init();
curl_setopt($curl_request, CURLOPT_URL, $apiUrl . $url);
curl_setopt($curl_request, CURLOPT_HEADER, 1);
curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_request, CURLOPT_POSTFIELDS, $parameters);
if($sessionId != null){
$cookieStr = "SESSION_ID=" . $sessionId;
if($sessionInfo != null){
$cookieStr .= "; SESSION_INFO=" . $sessionInfo;
}
//print($cookieStr . "\n");
curl_setopt($curl_request, CURLOPT_COOKIE, $cookieStr);
if($realUser != null){
$headerStr = array("REAL_UNAME: ".$realUser);
curl_setopt($curl_request, CURLOPT_HTTPHEADER, $headerStr);
}
}
$response = curl_exec($curl_request);
//print($response);
$error = curl_error($curl_request);
$result = array(
'body' => '',
'error' => '',
'http_code' => '',
'session_info' => '',
'session_id' => ''
);
if ( $error != "" )
{
$result['error'] = $error;
return $result;
}
$header_size = curl_getinfo($curl_request,CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$result['body'] = substr( $response, $header_size );
$result['http_code'] = curl_getinfo($curl_request,CURLINFO_HTTP_CODE);
curl_close($curl_request);
preg_match_all('/Set-Cookie:\s{0,}(?P<name>[^=]*)=(?P<value>[^;]*).*?$/im', $header, $cookies, PREG_SET_ORDER);
foreach ($cookies as $match) {
if($match["name"] == "SESSION_ID"){
$result['session_id'] = $match["value"];
}
if($match["name"] == "SESSION_INFO"){
$result['session_info'] = $match["value"];
}
}
return $result;
}
}
?>
Related
I am working on a signup form with an integrated v2 reCAPTCHA and I ran into the issue that when submitting the form which includes the reCAPTCHA, it is reloading the page. I have a php function to validate the reCAPTCHA:
if (isset($_POST['g-recaptcha-response'])) {
function CheckCaptcha($userResponse) {
$fields_string = '';
$fields = array(
'secret' =>'secret_key',
'response' => $userResponse
);
foreach($fields as $key=>$value)
$fields_string .= $key . '=' . $value . '&';
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
$res = curl_exec($ch);
curl_close($ch);
return json_decode($res, true);
}
$result = CheckCaptcha($_POST['g-recaptcha-response']);
if ($result['success']) {
echo 'Success!';
} else {
echo 'Error';
}
}
When the form submits it gives a POST variable g-recaptcha-response to the page it's on as there is no action attribute to the form
So, I need to get the POST request but I can't let the page reload because that would get rid of other data on the page.
I tried using event.preventDefault(); when the form is submitted, but that also prevented the form from submitting the POST variable.
I have no idea how I would get the POST variable through javascript because the reCAPTCHA is not actually an input.
But if there was a way to get the value of the reCAPTCHA through javascript, then I could use ajax to send the POST request to the function.
If you include the query strings in the script url:
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"async defer></script>
then you can use grecaptcha.getResponse as it says in the google reCAPTCHA documentation:
https://developers.google.com/recaptcha/docs/display
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"async defer></script>
<script type="text/javascript">
var verifyCallBack = function(response) {
alert(response);
};
var widgetId;
var onloadCallback = function() {
widgetId = grecaptcha.render('recaptcha', {
'sitekey' : 's',
'theme' : 'light'
});
}
</script>
<form>
<div id="recaptcha"></div>
<input type="submit" name="submit" value="submit">
</form>
$('form').submit(function(e) {
e.preventDefault();
var response = grecaptcha.getResponse(widgetId);
$.ajax({
url: 'validate_captcha.php',
type: 'POST',
data: {'g-recaptcha-response': response},
success: function(data) {
alert(data);
},
error: function(error) {
alert(error);
}
});
});
And then in validate_captcha.php:
<?php
if (isset($_POST['g-recaptcha-response'])) {
function CheckCaptcha($userResponse) {
$fields_string = '';
$fields = array(
'secret' => 'secret_key',
'response' => $userResponse
);
foreach($fields as $key=>$value)
$fields_string .= $key . '=' . $value . '&';
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
$res = curl_exec($ch);
curl_close($ch);
return json_decode($res, true);
}
$result = CheckCaptcha($_POST['g-recaptcha-response']);
if ($result['success']) {
echo 'success';
} else {
echo 'error';
}
}
?>
So now in your javascript, you can use the data variable inside success:function(data) in an if statement:
if(data == 'success') {
registerUser(name, email, password); // not a real function, just an example
}
<?php
include_once('simple_html_dom.php');
$veri = file_get_html("http://apps.istanbulsaglik.gov.tr/Eczane");
preg_match_all('#<a href="(.*?)" class="ilce-link" data-value="(.*?)"
data-ilcename="(.*?)" data-title="(.*?)" id="ilce" title="(.*?)"><i
class="fa fa-dot-circle-o"></i>(.*?)</a>#si',$veri,$baslik);
$length = count($baslik[4]);
for ($i = 0; $i < $length; $i++) {
echo $baslik[4][$i];
echo "</br>";
}
preg_match_all('#<table class="table ilce-nobet-detay" id="ilce-nobet-detay">(.*?)</table>#si',$veri,$adres);
echo $adres[1][1];
?>
In this link;
http://apps.istanbulsaglik.gov.tr/Eczane I can not get the right side elements that will be listed under "Eczaneler".
Because I need to click any of left side elements then, I can see them. What I want to do is getting that elements in my web crawler.
The main problem is how can I make my crawler click? without clicking I can not see any data.
If I can make it click, then I can take the data from html source. If not my crawler will always return empty.
If you use any browser's inspector on http://apps.istanbulsaglik.gov.tr/Eczane link, you will see that each link in İlçeler column has a data-value and binded to a click event:
the page Javascript code:
$(function () {
$(".ilce-link").on("click", function (parameters) {
var title = $(this).data("title").toUpperCase();
var id = $(this).data("value");
var request = $.ajax({
url: "/Eczane/nobetci",
method: "POST",
data: { "id": id, "token": "aa416735d12fd44b" },
dataType: "html"
});
request.done(function (data) {
$("#nobet").empty(" ");
$("#nobet").html('<i class="fa fa-spinner fa-spin"></i>');
$("#nobet").html(data);
document.title = "06-11-2017 TARİHİNDEKİ " + title + " İLEÇSİNDEKİ NÖBETÇİ ECZANE LİSTESİ";
});
});
});
This code means that when you click on any link in the left column, the script will create a post request by AJAX to this url: http://apps.istanbulsaglik.gov.tr/Eczane/nobetci with an id and a token.
So the idea is to directly use this url and post data, you can get the id from the link element and the token from the js code on the first page, and then use CURL PHP to post these data.
Here is an example using CURL post:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://apps.istanbulsaglik.gov.tr/Eczane/nobetci");
curl_setopt($ch, CURLOPT_POST, 1);
// you can use preg_match_all to retrieve the id and the token from the first page
curl_setopt($ch, CURLOPT_POSTFIELDS, "id=$id&token=$token");
$output = curl_exec ($ch);
curl_close ($ch);
I want to protect my jquery button from bots without annoying the users, so i thought of adding google's invisible recaptcha to it. However implementation isn't as easy as i though and i can't seem to do it. If anyone can show me how it's done it would be great. PS: I am doing this on a wordpress theme.
This is the documentation:
https://developers.google.com/recaptcha/docs/invisible
Create invisible recaptcha:
https://www.google.com/recaptcha/admin#beta
And this is what i have:
HTML:
<button class="acf-get-content-button">Show Link</button>
<div class="fa" id="acf-content-wrapper" data-id="<?php echo $post_id; ?>"></div>
JS:
<script>
(function($) {
$('.acf-get-content-button').click(function(e) {
e.preventDefault();
$('.fa').addClass('fa-cog fa-spin fa-4x');
var $contentWrapper = $('#acf-content-wrapper');
var postId = $contentWrapper.data('id');
$.ajax({
url: "/public/ajax.php",
type: "POST",
data: {
'post_id': postId
},
})
.done(function(data) {
$('.fa').removeClass('fa-cog fa-spin fa-4x');
$contentWrapper.append(data);
$('.acf-get-content-button').removeClass().addClass('.acf-get-content-button')
});
});
$('.acf-get-content-button').mouseup(function() {
if (event.which == 1) {
$(".acf-get-content-button").hide();
}
});
})(jQuery);
</script>
ajax.php
<?php
define('WP_USE_THEMES', false);
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );
global $post;
$post_id = $_REQUEST["post_id"];
$content = get_field( 'ebook_link_pdf', $post_id );
echo ($content);
You can use Invisible reCaptcha for WordPress plugin to do it easily if you think coding from scratch is complicated for you. You can also dig into the source code of the plugin to get an idea about the implementation.
This plugin has actions and filters for custom use and these are documented on plugin homepage.
I went ahead to experiment with reCaptcha.
Turns out according to the API, you could use the grecaptcha.getResponse method to submit to your AJAX call. (But Note that this reCaptcha API is still in beta and could change...) Here is a short example:
HTML:
<div id="test-captcha" class="g-recaptcha" data-sitekey=[Your site key]></div>
<button id="load" onclick="go();">Load something</button>
Javascript:
function go()
{
$.ajax({
url: "/captchatest.php",
type: "POST",
data: {
'g-recaptcha-response': grecaptcha.getResponse()
}
}).done(function(data) {
alert(data);
});
}
captchatest.php
<?php
//Used http://stackoverflow.com/a/6609181/7344257
function do_post_request($url, $data)
{
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'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 ($result === FALSE) { /* Handle error */ }
return $result;
}
$error = "";
if ($_SERVER["REQUEST_METHOD"] === "POST")
{
if (!isset($_POST['g-recaptcha-response']))
{
echo "Please do reCaptcha";
exit(0);
}
$data = array("secret" => "6LeUGhYUAAAAABNS5OtOc9vonTlyrtgcQ5VdI7cV",
"response" => $_POST['g-recaptcha-response'],
"remoteip" => $_SERVER["REMOTE_ADDR"] //This is optional.
);
$resp = json_decode(do_post_request("https://www.google.com/recaptcha/api/siteverify", $data));
if (!$resp->success)
{
//use $resp->error-codes to debug error.
echo "Invalid reCaptcha";
exit(0);
}
echo "Received secret code.";
exit(0);
}
?>
I wasn't sure if you could use cURL. So I decided to just stick with the basic PHP code. You would also have to format the errors, but I think you should get the point.
I use ZfcUser in my Project. I have now got a link to be able to Bookmark an Advert. I use jQuery Ajax for this to jump into the Action of my Controller. To be able to set a Bookmark, I have to be logged in. If a User is not logged in, a re-direct to the Log-in Page happens.
This all works very well now, but I was wondering if it's possible to redirect to my Advert Page, after the User logs in, best would even be that the Bookmark gets automatically set, since this was the last the User tried to achieve. Right now I get redirected to the Page which is defined in the
zfcuser.global.php ('login_redirect_route'). And yes, I have set
'use_redirect_parameter_if_present' => true,
to true in the zfcuser.global.php file. but how would I use this now? I suppose it could be a problem because it goes through the Ajax Request and my re-direct is then achieved through
window.location.replace(response.redirect);
Is there any way to achieve this or do I expect too much?
$(document).on("click", "#add-bookmark-link",function () {
$.ajax({
dataType: 'json',
data: { id: <?php echo $advertId;?>},
url: '/add-bookmark',
success: function(response) {
if (response.status == false)
{
window.location.replace(response.redirect);
}
else{
$('.add-bookmark').replaceWith('<p class="text-right remove-bookmark"><span class="danger glyphicon glyphicon-minus-sign text-danger"></span> Remove Bookmark');
}
}
});
});
});
AdvertController.php
public function addBookmarkAction() {
$advertId = $this->params()->fromQuery('id',null);
if ($this->zfcUserAuthentication()->hasIdentity()) {
$this->getServiceLocator()->get('BookmarkAdvertService')->saveAdvertBookmark($advertId);
$result = new JsonModel(array(
'status' =>true,
));
}
else{
$result = new JsonModel(array(
'status' => false,
'redirect' => $this->url()->fromRoute('zfcuser/login')
));
}
return $result;
}
UPDATE
After receiving below answer, I have updated my Sourcecode. Not sure I have done it right. It now goes straight to the below URL without showing the Login. The URL is also wrong, since it shows me [object Object]. Why is it now going to the Log-in?
http://mywebsite.com/ad/thenameoftheadvert/[object Object]
In general my URL should look like this in the end
http://mywebsite.com/ad/thenameoftheadvert/articleId.htm
What have I done wrong? I suppose I implemented the solution wrong...
public function addBookmarkAction() {
$advertId = $this->params()->fromQuery('id',null);
if ($this->zfcUserAuthentication()->hasIdentity()) {
$this->getServiceLocator()->get('BookmarkAdvertService')->saveAdvertBookmark($advertId);
$result = new JsonModel(array(
'status' =>true,
));
}
else{
$name = '/add-bookmark';
$params = array('advertId' => $advertId);
$options = array();
$bookmarkRedirect = $this->url($name, $params, $options);
$name = 'zfcuser/login';
$params = array();
$options = array(
'query' => array(
'redirect' => $bookmarkRedirect
),
);
$loginRedirect = $this->url($name, $params, $options);
$result = new JsonModel(array(
'status' => false,
'redirect' => $loginRedirect
));
}
return $result;
}
Normally you have to pass the redirect parameter as a query param and then it is rendered in the url like this:
http://www.example.com/login?redirect=http://www.example.com/object/1/add/bookmark
You can achieve this as follows.
First create a redirect for adding the bookmark:
$name = 'add/bookmark';
$params = array('object_id' => $object_id);
$options = array();
$bookmarkRedirect = $this->url($name, $params, $options);
Now create a redirect for login and add the redirect to the bookmark as a query param:
$name = 'zfcuser/login';
$params = array();
$options = array(
'query' => array(
'redirect' => $addBookmark
),
);
$loginRedirect = $this->url($name, $params, $options);
Return this in your JsonModel:
$result = new JsonModel(array(
'status' => false,
'redirect' => $loginRedirect
));
I'm hacking away at some code in order to have it register a click on an invisible div element, which expands an article to reveal it's excerpt while adding a +1 to the number of time's it's been clicked by anyone. Afterwards it updates an element with ajax with the number of clicks it's received.
At least, that's the goal.
The following code ends up breaking Wordpress and gives me the white screen of doom. This is taken from a simple click counter with an Ajax callback to update the number.
Where my problem lies is hacking away at this for it to register clicks on a different element.
Without wasting too much of anyones time, here's my question:
Wouldn't I just need to rename all post_like to post_reader? Someone's been telling my in person that it should work so check your server but that is ridiculous... it seems.
Note, below where you see post_reader, it had said post_like previously.
// post click to expand button
$timebeforerevote = 1;
add_action('wp_ajax_nopriv_post-like', 'post_reader');
add_action('wp_ajax_post-like', 'post_reader');
wp_localize_script('like_post', 'ajax_var', array(
'url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('ajax-nonce')
));
function post_like()
{
$nonce = $_POST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'ajax-nonce' ) )
die ( 'Busted!');
if(isset($_POST['post_reader']))
{
$ip = $_SERVER['REMOTE_ADDR'];
$post_id = $_POST['post_id'];
$meta_IP = get_post_meta($post_id, "voted_IP");
$voted_IP = $meta_IP[0];
if(!is_array($voted_IP))
$voted_IP = array();
$meta_count = get_post_meta($post_id, "votes_count", true);
if(!hasAlreadyVoted($post_id))
{
$voted_IP[$ip] = time();
update_post_meta($post_id, "voted_IP", $voted_IP);
update_post_meta($post_id, "votes_count", ++$meta_count);
echo $meta_count;
}
else
echo "already";
}
exit;
}
function hasAlreadyVoted($post_id)
{
global $timebeforerevote;
$meta_IP = get_post_meta($post_id, "voted_IP");
$voted_IP = $meta_IP[0];
if(!is_array($voted_IP))
$voted_IP = array();
$ip = $_SERVER['REMOTE_ADDR'];
if(in_array($ip, array_keys($voted_IP)))
{
$time = $voted_IP[$ip];
$now = time();
if(round(($now - $time) / 60) > $timebeforerevote)
return false;
return true;
}
return false;
}
function getPostReadLink($post_id)
{
$themename = "toolbox";
$vote_count = get_post_meta($post_id, "votes_count", true);
$output = '<div class="post-read">';
if(hasAlreadyVoted($post_id))
$output .= ' <span title="'.__('I like this article', $themename).'" class="qtip like alreadyvoted"></span>';
else
$output .= '<a href="#" data-post_id="'.$post_id.'">
<span title="'.__('I like this article', $themename).'"class="qtip like"></span>
</a>';
$output .= '<span class="count">'.$vote_count.'</span></div>';
return $output;
}
The function called when clicked:
jQuery(".expand").click(function(e){
e.preventDefault();
readers = jQuery(this);
// Retrieve post ID from data attribute
post_id = readers.data("post_id");
// Ajax call
jQuery.ajax({
type: "post",
url: ajax_var.url,
data: "action=post-reader&nonce="+ajax_var.nonce+"&post_reader=&post_id="+post_id,
success: function(count){
// If vote successful
if(count != "already")
{
heart.addClass("readered");
heart.siblings(".count").text(count);
}
}
});
return false;
})
Invoking it within the appropriate div.
<?php echo getPostReadLink(get_the_ID());?>