Using PHP Ajax to query ssllabs api - javascript

After general advice, techniques or examples if possible.
I'm looking to integrate testing of URL's with SSLlabs API.
www.ssllabs.com/projects/ssllabs-apis/index.html
I've established the URL's that i need to execute to retrieve the info from this api.
e.g. Start analysis - https://api.ssllabs.com/api/v2/analyze?host=portal.testdomain.co.uk
Retrieve results - https://api.ssllabs.com/api/v2/getEndpointData?host=portal.testdomain.co.uk&s=10.111.222.234
My question is, how would i go about integrating into an Ajax/php site?
Or would this be better only executed on backend system and the results pumped into a DB?
So far, i have a button that simply grabs the contents of 2 hidden fields containing hostname and ip address to query.
function stateck()
{
if(httpxml.readyState==4 && httpxml.status == 200)
{
console.log(httpxml.responseText);
alert(httpxml.responseText);
}
}
var url="ssltest.php?commonname=" + commonname + "&s=" + ip;
url=url+"&sid="+Math.random();
httpxml.onreadystatechange=stateck;
httpxml.open("GET", url, true);
httpxml.send(null);
The ssltest.php contains the following cURL function to query then return the api page content. Browsing to this ssltest.php with the parameters in the url works a treat.
#$commonname=$_GET['commonname'];
#$ip=$_GET['ip'];
if(is_numeric($commonname)){
echo "Data Error";
exit;
}
$testurl = "https://api.ssllabs.com/api/v2/analyze?host=" . $commonname;
$resulturl = "https://api.ssllabs.com/api/v2/getEndpointData?host=" . $commonname . "&s=" . $ip;
function ssl_test_start($url,$useragent='cURL',$headers=false,
$follow_redirects=false,$debug=false) {
# initialise the CURL library
$ch = curl_init();
# specify the URL to be retrieved
curl_setopt($ch, CURLOPT_URL,$url);
# we want to get the contents of the URL and store it in a variable
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
# specify the useragent: this is a required courtesy to site owners
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
# ignore SSL errors
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
# return headers as requested
if ($headers==true){
curl_setopt($ch, CURLOPT_HEADER,1);
}
# only return headers
if ($headers=='headers only') {
curl_setopt($ch, CURLOPT_NOBODY ,1);
}
# follow redirects - note this is disabled by default in most PHP installs
from 4.4.4 up
if ($follow_redirects==true) {
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
}
# if debugging, return an array with CURL's debug info and the URL contents
if ($debug==true) {
$result['contents']=curl_exec($ch);
$result['info']=curl_getinfo($ch);
}
# otherwise just return the contents as a variable
else $result=curl_exec($ch);
# free resources
curl_close($ch);
# send back the data
return $result;
}
function ssl_test_results($url,$useragent='cURL',$headers=false,
$follow_redirects=false,$debug=false) {
# initialise the CURL library
$ch = curl_init();
# specify the URL to be retrieved
curl_setopt($ch, CURLOPT_URL,$url);
# we want to get the contents of the URL and store it in a variable
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
# specify the useragent: this is a required courtesy to site owners
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
# ignore SSL errors
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
# return headers as requested
if ($headers==true){
curl_setopt($ch, CURLOPT_HEADER,1);
}
# only return headers
if ($headers=='headers only') {
curl_setopt($ch, CURLOPT_NOBODY ,1);
}
# follow redirects - note this is disabled by default in most PHP installs
from 4.4.4 up
if ($follow_redirects==true) {
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
}
# if debugging, return an array with CURL's debug info and the URL contents
if ($debug==true) {
$result['contents']=curl_exec($ch);
$result['info']=curl_getinfo($ch);
}
# otherwise just return the contents as a variable
else $result=curl_exec($ch);
# free resources
curl_close($ch);
# send back the data
return $result;
}
if (!isset($ip)){
$result = ssl_test_start($testurl);
echo json_encode($result);
}
else {
$result = ssl_test_start($resulturl);
echo json_encode($result);
}
How do i then get the $result back into the original page and then access/display the result values? I am currently attempting to use XMLHttpRequest() but responseText does not seem to contain anything.

Got this worked out in the end.
In a nutshell i used jQuery GET method to pass to the backend php.
$.ajax({
type: "GET",
url: "ssltest.php",
data: dataString,
dataType: "json",
success: function(response) {
//Do something.
}
})
Works a treat and easy to traverse through the resulting array sent back.

Related

can't get json data with api

I am using below javascript and html to get the json data. But i can't make it work with this api.It just return blank result. I have checked the api link is working so i don't think is the server problem. Please help!
html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="balance"></div>
javascript
$(function() {
$.ajax({
type: "GET",
url:"https://xmg.minerclaim.net/index.php?page=api&action=public",
dataType: "json",
success: function(data) {
console.log(typeof data); // -- Object
var json = data;
$('#balance').html(json.hashrate);
}
});
});
json data
{"pool_name":"minerclaim.net","hashrate":60185.64096,"workers":1056,"shares_this_round":168700,"last_block":1531882,"network_hashrate":61752985,"fee":1,"payout":"prop"}
As I mentioned above, you are getting bool(true) in your PHP output, because the usage of var_dump().
An example of a PHP file you could use:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://xmg.minerclaim.net/index.php?page=api&action=public");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 0);
$headers = array();
$headers[] = "Content-Type: application/json; charset=utf-8";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Some error:' . curl_error($ch);
die();
}
// You want your browser to think it's JSON, as we return as JSON
header("Content-Type: application/json; charset=utf-8");
echo($result);
curl_close($ch);
?>
You can copy + paste this into a new PHP file, point the $.ajax-url to that new file and see the magic happen. The example above works for me as I'm getting results back.
As for your javascript, you could also try to add contentType: "application/json", after `dataType: "json",", as this will make sure the content-type of the headers that are returned are set.

Calling PHP wrapper on client side

I´m currently working on a school project, where we are using Apache cordova (HTML, CSS and JS side) and currently our school has a server, where our .php file is located.
In our project, (one of the HTML files) we use API key and an domain address, that we want to get rid off from source code (so other students cant see it). What would be easiest way to execute this?
We´ve been thinking following;
We use the php-file as a wrapper with the following code;
IE.
<?php
function getJson($data){
$decoded = json_decode($data);
if (isset($decoded)){
// Toteutusten haku
$url = "URL THAT WE DONT WANT TO BE SEEN";
$apiKey = "API KEY GOES HERE";
// curl
$ch = curl_init($url);
// curl_exec returnsanswer (not boolean)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Asets api key, ":"
curl_setopt($ch, CURLOPT_USERPWD, $apiKey.":");
// Setting message - JSON
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// Sets false if necessary
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Sends request
$responseJson = curl_exec($ch);
return $responseJson;
curl_close($ch); //close session
**}
}
?>
And in HTML file we have code snippets that looks like following;
// B building rooms
if (buildingcode.startsWith("B", 5)) {
var requestB = new XMLHttpRequest();
requestB.onreadystatechange = function () {
if (requestB.readyState === 4) {
if (requestB.status === 200) {
try {
var jsonB = JSON.parse(requestB.responseText);
for (var fb = 0; fb < jsonB.resources.length; fb++) {
var resB = jsonB.resources[fb];
if (resB.type === "room") {
if (bTilat.indexOf("code")) {
bTilat.push(resB.code + resB.name.slice(resB.name.indexOf(' ('), 50));
}
}
}
} catch (e) {
console.log(e.message);
return;
}
}
}
//console.log(bTilat);
};
requestB.open("GET", 'THIS PART HAS THE DOMAIN WE WANT TO HIDE', true, "THIS PART HAS THE API WE WANT TO HIDE", "");
requestB.send(null);
}
So my question is following; I guess we need to get rid off
requestB.open("GET", 'THIS PART HAS THE DOMAIN WE WANT TO HIDE', true, "THIS PART HAS THE API WE WANT TO HIDE", "");
requestB.send(null);
From html, but how do we request the code from wrapper?
Thank you in advance.

Tableau Embed with jQuery and PHP passing parameters

I generally use Wordpress when building my internally facing dashboards with Tableau, but that will not work in this case so I am starting from scratch. I'm a novice with PHP and slightly above novice with jQuery, but I know my way around HTML. I need to pass an Okta javascript parameter into a Tableau embed. Below is my current code:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var settings = {
url: "https://harmelin.okta.com/api/v1/users/me",
type: 'GET',
dataType: 'json',
contentType: 'application/json',
xhrFields: {
withCredentials: true
},
success: function (data) {
// alert(JSON.stringify(data));
},
error: function(err){
// alert(JSON.stringify(err));
}
}
jQuery.ajax(settings).done(function (success) {
console.log(success);
var raw = success.profile.login;
var email = raw.toLowerCase();
var $login = email.replace(/#[^#]+$/, '');
jQuery("#write-data").append($login);
});
</script>
</head>
<body>
<?php
// Tableau-provided functions for doing trusted authentication
require_once 'tableau_trusted.php';
?>
<div id="write-data"></div>
<?php
$user = 'jfedorowicz';
$server = 'dashboard1.harmelin.com';
$view = 'JoesPlayground/views/PTOStuff/Dashboard1?LCUsername=';
$theLogin = $login;
echo '<iframe src="';
echo get_trusted_url( $user,$server,$view$theLogin );
echo '" width="400" height="400"> </iframe>';
?>
</body>
Two problems:
1) What I am looking to do is pass $login (javascript variable) into $view. I 100% know that I did not do this right, but I cannot test because problem two.
2) I'm returning a 500 error: "Failed to load resource: the server responded with a status of 500 (Internal Server Error)" which I assume is a Tableau error but I cannot figure it out.
Any ideas? Thanks.
To generate authorization token you can use given code.
This code is working fine with all version upto 2018.3
/* PHP code to generate auth token */
$url = $dashboardURL . '/trusted';
$fields_string = "trusted_site=&username=" . $username;
$ch = curl_init();
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
$token = curl_exec($ch);
Now just pass this token with dashboard url in your view/html file.

Jquery/AJAX&PHP Domain checker

I'm trying to build a domain availability checker.
My PHP code is the following:
<?php
$domain = $_GET["domname"];
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$returned_content = get_data('http://freedomainapi.com/?key=XXXXXXX&domain=' . $domain);
echo $returned_content;
?>
When called as such: /domchek.php?domname=google.com
The JSON output is:
{"status":"success","domain":"google.com","available":true}
The JQuery im using to call the script is as follows:
$.get("domchek.php?domname=google.com", {data: "available"}, function(json) {
$("html").html(json);
});
I just want to return the availability not the entire JSON output. I have tried json.availability and a number of other things but can't figure it out. Also if there is a better method for this than .get() please suggest it.
UPDATE:
$.getJSON("domchek.php?domname=google.com", function(json) {
$("html").html(json.status);
});
The above works as does returning json.domain but trying to return json.available - which I require returns nothing..
Change this line:
$("html").html(json);
to:
$("html").html(json.status);
UPDATE: to force the GET request data type to JSON, change to:
$.get("domchek.php?domname=google.com", {data: "available"}, function(json) {
$("html").html(json);
}, 'json');

Get the HTML contents of another frame on another domain

I've read that you cannot read the HTML of another frame if that frame resides on another domain. Is there a way to do this in Javascript? I realise this restriction is for security purposes but my use is legitimate.
Regards
Peter
Are we talking about an iFrame here? If so, could you not get the src attribute of the iFrame (jQuery?) and initiate an ajax request which would return the page, or perhaps hand the src attribute to your own script (PHP/ASP whatever) that uses CURL to glean the information you're after?
Yes you can definitely read the contents of the frame using cross-domain proxy. Essentially you need to create a server-side script that requests the src URL of the frame in question. On the client side, you request this script instead of the src URL (which is on another domain and thereby subject to security restrictions within the browser), passing in the src URL as a parameter.
Server-Side Script
The following is an example with PHP using cURL.
<?php
$target = $_REQUEST['t'];
if (empty($target)) { die 'no url provided'; }
$useragent="Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($ch);
curl_close($ch);
echo $res;
?>
Client-Side Script
On your page, use the following JavaScript function to return the HTML of the target frame
var URL = top.frames.(YOUR FRAME NAME HERE).location;
var xh = null;
if (window.XMLHttpRequest) {
xh = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xh = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Your browser does not support XMLHTTP.");
return false;
}
var ret = null;
xh.onreadystatechange = function() {
if (xh.readyState == 4 && xh.status == 200) {
// do whatever you want with the html here
ret = xh.responseText;
}
}
xh.open("GET", url, false);
xh.send(null);
Let me know if this works for you.

Categories