I am trying to read JSON values using the "Have I Been PWNED" API v2.
I have tried two different ways to display the data using the URL (https://haveibeenpwned.com/api/v2/breach/Adobe) and using a local .json file, but both methods display nothing.
Method 1 (URL):
index.php
<?php
// Breach Title
$breach_title = 'Adobe';
// JSON URL
$url = 'https://haveibeenpwned.com/api/v2/breach/'.$breach_title;
// Put the contents of the url into a variable
$json = file_get_contents($url);
// Decode the JSON feed
$object = json_decode($json);
// Echo Results
echo $object[0]->Title;
echo $object[0]->Name;
echo $object[0]->Domain;
echo $object[0]->Description;
echo $object[0]->BreachDate;
?>
Method 2 (Local .json file):
index.php
<?php
// Put the contents of the file into a variable
$json = file_get_contents("Adobe.json");
// Decode the JSON feed
$object = json_decode($json);
// Echo Results
echo $object[0]->Title;
echo $object[0]->Name;
echo $object[0]->Domain;
echo $object[0]->Description;
echo $object[0]->BreachDate;
?>
Adobe.json
{
"Title": "Adobe",
"Name": "Adobe",
"Domain": "adobe.com",
"BreachDate": "2013-10-04",
"AddedDate": "2013-12-04T00:00:00Z",
"ModifiedDate": "2013-12-04T00:00:00Z",
"PwnCount": 152445165,
"Description": "In October 2013, 153 million Adobe accounts were breached with each containing an internal ID, username, email, <em>encrypted</em> password and a password hint in plain text. The password cryptography was poorly done and many were quickly resolved back to plain text. The unencrypted hints also disclosed much about the passwords adding further to the risk that hundreds of millions of Adobe customers already faced.",
"DataClasses": [
"Email addresses",
"Password hints",
"Passwords",
"Usernames"
],
"IsVerified": true,
"IsFabricated": false,
"IsSensitive": false,
"IsActive": true,
"IsRetired": false,
"IsSpamList": false,
"LogoType": "svg"
}
I have been using the following as resources:
Read JSON values from URL via PHP
How do I extract data from JSON with PHP?
https://stackoverflow.com/a/29308899/9925901
Also no output using this in both methods:
print_r($object);
With the version of Adobe.json in your question, you don't need the [0] to access the data...
$object = json_decode($json);
// Echo Results
echo $object->Title;
echo $object->Name;
echo $object->Domain;
echo $object->Description;
echo $object->BreachDate;
To get the file URL with https, it may be easier to use CURL...
// Breach Title
$breach_title = 'Adobe';
// JSON URL
$url = 'https://haveibeenpwned.com/api/v2/breach/'.$breach_title;
// Put the contents of the url into a variable
//$json = file_get_contents($url);
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_USERAGENT => "spider", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_SSL_VERIFYPEER => false // Disabled SSL Cert checks
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$json = curl_exec( $ch );
// Decode the JSON feed
$object = json_decode($json);
$object = json_decode($json);
// Echo Results
echo $object->Title;
echo $object->Name;
echo $object->Domain;
echo $object->Description;
echo $object->BreachDate;
Here is my corrected code after reading the HIBP APIv2 closer thanks to #MonkeyZeus
Just needed to add a user agent and removed [0].
<?php
ini_set('user_agent', 'Test App');
// Breach Title
$breach_title = 'Adobe';
// JSON URL
$url = 'https://haveibeenpwned.com/api/v2/breach/'.$breach_title;
// Put the contents of the url into a variable
$json = file_get_contents($url);
// Decode the JSON feed
$object = json_decode($json);
// Echo Results
echo $object->Title;
echo $object->Name;
echo $object->Domain;
echo $object->Description;
echo $object->BreachDate;
?>
Related
I want to grab this number (28/28) with PHP from a tracking software (https://aircrasher.livefpv.com/live/scoring/) for drone races. But I can't. I think it's a websocket, but I don't know how to retrieve information from it. I tried curl, I tried the "ultimate-web-scraper" from GitHub (https://github.com/cubiclesoft/ultimate-web-scraper). I tried a code example from another post from here (PHP simple web socket client) but I'm not able to get this number. Is it imposible to get this number (with php)?
This is what I tried so far with the help of "ultimate-web-scraper" (https://kleesit.de/beta/livetime/webscraper/test.php):
<?php
require_once "support/web_browser.php";
require_once "support/tag_filter.php";
// Retrieve the standard HTML parsing array for later use.
$htmloptions = TagFilter::GetHTMLOptions();
// Retrieve a URL (emulating Firefox by default).
$url = "https://aircrasher.livefpv.com/live/scoring/";
$web = new WebBrowser();
$result = $web->Process($url);
// Check for connectivity and response errors.
if (!$result["success"])
{
echo "Error retrieving URL. " . $result["error"] . "\n";
exit();
}
if ($result["response"]["code"] != 200)
{
echo "Error retrieving URL. Server returned: " . $result["response"]["code"] . " " . $result["response"]["meaning"] . "\n";
exit();
}
// Get the final URL after redirects.
$baseurl = $result["url"];
// Use TagFilter to parse the content.
$html = TagFilter::Explode($result["body"], $htmloptions);
// Find all anchor tags inside a div with a specific class.
// A useful CSS selector cheat sheet: https://gist.github.com/magicznyleszek/809a69dd05e1d5f12d01
echo "All the URLs:\n";
$result2 = $html->Find("div.someclass a[href]");
if (!$result2["success"])
{
echo "Error parsing/finding URLs. " . $result2["error"] . "\n";
exit();
}
foreach ($result2["ids"] as $id)
{
// Faster direct access.
echo "\t" . $html->nodes[$id]["attrs"]["href"] . "\n";
echo "\t" . HTTP::ConvertRelativeToAbsoluteURL($baseurl, $html->nodes[$id]["attrs"]["href"]) . "\n";
}
// Find all table rows that have 'th' tags.
// The 'tr' tag IDs are returned.
$result2 = $html->Filter($html->Find("tr"), "th");
if (!$result2["success"])
{
echo "Error parsing/finding table rows. " . $result2["error"] . "\n";
exit();
}
foreach ($result2["ids"] as $id)
{
echo "\t" . $html->GetOuterHTML($id) . "\n\n";
}
?>
This is what I tried with CURL and the help of a stackoverflow post (https://kleesit.de/beta/livetime/test2.php):
<?php
// random 7 chars digit/alphabet for "t" param
$random = substr(md5(mt_rand()), 0, 7);
$socket_server='https://aircrasher.livefpv.com/live/scoring/';
// create curl resource
$ch = curl_init();
//N°1 GET request
curl_setopt_array(
$ch,
[
CURLOPT_URL => $socket_server,
CURLOPT_RETURNTRANSFER => TRUE,
// since it is TRUE by default we should disable it
// on our localhost, but from real https server it will work with TRUE
CURLOPT_SSL_VERIFYPEER => FALSE
]);
// $output contains the output string
$output = curl_exec($ch);
$output=substr($output, 1);
echo $socket_server;
// server response in my case was looking like that:
// '{"sid":"4liJK2jWEwmTykwjAAAR","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":20000,"maxPayload":1000000}'
var_dump($output);
$decod=json_decode($output);
// setting ping Interval accordingly with server response
$pingInterval = $decod->pingInterval;
//N°2 POST request
$socket_server_with_sid = $socket_server.'&sid='.$decod->sid;
curl_setopt_array(
$ch,
[
CURLOPT_URL => $socket_server_with_sid,
CURLOPT_POST => TRUE,
CURLOPT_TIMEOUT_MS => $pingInterval,
// 4 => Engine.IO "message" packet type
// 0 => Socket.IO "CONNECT" packet type
CURLOPT_POSTFIELDS => '40'
]);
$output = curl_exec($ch);
// ok
var_dump($output);
// Pervious 2 requests are called "hand shake" now we can send a message
// N°3 socket.emit
if ($output==='ok') {
curl_setopt_array(
$ch,
[
CURLOPT_URL => $socket_server_with_sid,
CURLOPT_TIMEOUT_MS => $pingInterval,
CURLOPT_POST => TRUE,
// 4 => Engine.IO "message" packet type
// 2 => Engine.IO "EVENT" packet type
CURLOPT_POSTFIELDS => '42["chat message","0devhost message 10"]'
]);
$output = curl_exec($ch);
// ok
echo $output.'<br/>';
echo $socket_server_with_sid;
}
// close curl resource to free up system resources
curl_close($ch);
?>
I am trying to retrieve the html from file get contents in php then save it to a php file so I can include it into my homepage.
Unfortunately my script isn't saving the data into the file. I also need to verwrite this data on a daily basis as it will be setup with a cron job.
Can anyone tell me where I am going wrong please? I am just learning php :-)
<?php
$richSnippets = file_get_contents('http://website.com/data');
$filename = 'reviews.txt';
$handle = fopen($filename,"x+");
$somecontent = echo $richSnippets;
fwrite($handle,$somecontent);
echo "Success";
fclose($handle);
?>
A couple of things,
http://website.com/data gets a 404 error, it doesn't exist.
Change your code to
$site = 'http://www.google.com';
$homepage = file_get_contents($site);
$filename = 'reviews.txt';
$handle = fopen($filename,"w");
fwrite($handle,$homepage);
echo "Success";
fclose($handle);
Remove $somecontent = echo $richSnippets; it doesn't do anything.
if you have the proper permissions it should work.
Be sure that your pointing to an existing webpage.
Edit
When cURL is enabled you can use the following function
function get_web_page( $url ){
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_USERAGENT => "spider", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$content = curl_exec( $ch );
curl_close( $ch );
return $content;
}
Now change
$homepage = file_get_contents($site);
in to
$homepage = get_web_page($site);
You should use / instead of ****
$homepage = file_get_contents('http://website.com/data');
Also this part
$somecontent = echo $richSnippets;
I don't see $richSnippets above... it's probably not declared?
You probably want to do this:
fwrite($handle,$homepage);
This is the function I use to grab a JSON file from Feedbin API.
<?php
error_reporting(E_ALL);
// JSON URL which should be requested
$json_url = 'https://api.feedbin.me/v2/entries.json';
$username = 'my_username'; // authentication
$password = ' my_password'; // authentication
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERPWD => $username . ":" . $password // authentication
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting JSON result string
print_r ($result);
?>
Problem is the JSON I get is a bit.. strange.
It has a lot of chars like \u003E\u003C/a\u003E\u003C/p\u003E\n\u003Cp\u003E ...
You can see the JSON here.
When you call json_decode in PHP on strings that contain these encodings they will be correctly decoded. http://json.org/ lists \ufour-hex-digits as a valid character. There is no issue.
$ echo json_decode('"\u003E\u003C/a\u003E\u003C/p\u003E\n\u003Cp\u003E"');
></a></p>
<p>
They are valid unicode sequence. Here is a simple example
$data = array(
"abc" => 'åbcdéfg'
);
// Encode
$data = json_encode($data) . "\n";
// Output Value
echo $data;
// Output Decoded Value
print_r(json_decode($data));
Output
{"abc":"\u00e5bcd\u00e9fg"}
stdClass Object
(
[abc] => åbcdéfg
)
I am trying to implement sketchfab api in my website. I got the code and access token from their website , I implemented everything but when I execute the code, I get a blank screen. What is the problem?
The first problem was with curl, I enabled it by going to php.ini file but then this blank screen problem.
<?php
$url = "https://api.sketchfab.com/v1/models";
$path = "./";
$filename = "m.3DS";
$description = "Test of the api with a simple model";
$token_api = "THE ACCESS TOKEN";
$title = "Uber Glasses";
$tags = "test collada glasses";
$private = 1;
$password = "Tr0b4dor&3";
$data = array(
"title" => $title,
"description" => $description,
"fileModel" => "#".$path.$filename,
"filenameModel" => $filename,
"tags" => $tags,
"token" => $token_api,
"private" => $private,
"password" => $password
);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $data
));
$response = curl_exec($ch);
curl_close($ch);
echo $response; // I am trying to echo the response here
?>
The call to the upload api will return a json that contains the id of the model. You can use this id to generate an url and make another call to the oEmbed api. pseudo code example:
// your curl setup
$response = curl_exec($ch);
// Response
{success: true, {result: {id: 'xxxxxx'} } when upload OK
{success: false, error: 'error message'} when upload error
$id = $response['result']['id'];
$call= "https://sketchfab.com/oembed?url=https://sketchfab.com/show/" . $id;
// do another curl call with $call content
// it will return a response like below but with your model information
// Response
{
provider_url: "http://sketchfab.com",
provider_name: "Sketchfab",
thumbnail_url: "https://sketchfab.com/urls/dGUrytaktlDeNudCEGKk31oTJY/thumbnail_448.png?v=24a1cb0590851ccfeeae01a2ca1eece1",
thumbnail_width: "448",
thumbnail_height: "280",
author_name: "Klaas Nienhuis",
author_url: "https://sketchfab.com/klaasnienhuis",
title: "Maison d'artiste",
html: "<iframe frameborder="0" width="640" height="320" webkitallowfullscreen="true" mozallowfullscreen="true" src="http://sketchfab.com/embed/dGUrytaktlDeNudCEGKk31oTJY?autostart=0&transparent=0&autospin=0&controls=1&watermark=0"></iframe>",
width: 640,
height: 320,
version: "1.0",
type: "rich"
}
If you have an issue with this try in the command line to print the result of call.
I'm trying to connect an API that uses 0AUTH2 via PHP. The original plan was to use client-side JS, but that isn't possible with 0AUTH2.
I'm simply trying get a share count from the API's endpoint which is here:
https://api.bufferapp.com/1/links/shares.json?url=[your-url-here]&access_token=[your-access-key-here]
I do have a proper access_token that I am using to access the json file, that is working fine.
This is the code I have currently written, but I'm not even sure I'm on the right track.
// 0AUTH2 ACCESS TOKEN FOR AUTHENTICATION
$key = '[my-access-key-here]';
// JSON URL TO BE REQUESTED
$json_url = 'https://api.bufferapp.com/1/links/shares.json?url=http://bufferapp.com&access_token=' . $key;
// GET THE SHARE COUNT FROM THE REQUEST
$json_string = '[shares]';
// INITIALIZE CURL
$ch = curl_init( $json_url );
// CONFIG CURL OPTIONS
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
CURLOPT_POSTFIELDS => $json_string
);
// SETTING CURL AOPTIONS
curl_setopt_array( $ch, $options );
// GET THE RESULTS
$result = curl_exec($ch); // Getting jSON result string
Like I said, I don't know if this is the best method - so I'm open to any suggestions.
I'm just trying to retrieve the share count with this PHP script, then with JS, spit out the share count where I need it on the page.
My apologies for wasting anyone's time. I have since been able to work this out. All the code is essentially the same - to test to see if you're getting the correct response, just print it to the page. Again, sorry to have wasted anyones time.
<?php
// 0AUTH2 ACCESS TOKEN FOR AUTHENTICATION
$key = '[your_access_key_here]';
// URL TO RETRIEVE SHARE COUNT FROM
$url = '[your_url_here]';
// JSON URL TO BE REQUESTED - API ENDPOINT
$json_url = 'https://api.bufferapp.com/1/links/shares.json?url=' . $url . ' &access_token=' . $key;
// GET THE SHARE COUNT FROM THE REQUEST
$json_string = '[shares]';
// INITIALIZE CURL
$ch = curl_init( $json_url );
// CONFIG CURL OPTIONS
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
CURLOPT_POSTFIELDS => $json_string
);
// SETTING CURL AOPTIONS
curl_setopt_array( $ch, $options );
// GET THE RESULTS
$result = curl_exec($ch); // Getting jSON result string
print $result;
?>