How do I Add Parsing JSON to PHP Script - php

So here's my sample code that I pull from SEOMOZ API for links on a targeted URL.
this script is command line
#!/usr/bin/php
<?php
$objectURL = $domain_url;$accessID = "xyz";
$secretKey = "xya";
$expires = mktime() + 300;
$stringToSign = $accessID."\n".$expires;
$binarySignature = hash_hmac('sha1', $stringToSign, $secretKey, true);
$urlSafeSignature = urlencode(base64_encode($binarySignature));
$urlToFetch = "http://lsapi.seomoz.com/linkscape/links/".urlencode($objectURL)."?AccessID=".$accessID."&Expires=".$expires."&Signature=".$urlSafeSignature."&SourceCols=26&&TargetCols=4&Scope=page_to_domain&Filter=follow&Sort=page_authority&Limit=10";
$handle = fopen($urlToFetch, "r");
$links_contents = '';
while (!feof($handle)) {
$links_contents .= fread($handle, 8192);
}
fclose($handle);
echo $links_contents;
?>
the result of the script is that it returns info in JSON format but in a huge glob not in an orderly manner. Whats the easiest way to format the result into a more neater/readable display?
here is the return from JSON
{
"frid": 1,
"lf": 2,
"lrid": 3,
"lsrc": 4,
"ltgt": 5,
"luuu": 6,
"prid": 7,
"ufq": 8,
"upl": 9,
"urid": 10
}

You mean json_decode($links_contents)?

Related

Am I decrypting this correctly?

Given the following inputs:
CLIENT RANDOM : 61fc160e0a6e96db43aebcca55da7fbccb97cc04d59fcc105490b4396a915ab9
SERVER RANDOM : f0ecb127db6e353a2985894c123532a8d092fafcf7cdce3a444f574e47524401
PREMASTER KEY : 0303ec4418e91f0abf9a012f524b61c0312008641ebce76d68b2417447e3d9a970d02fd65a20e5e3e98413dbd13b6536
First I use these input to calculate the following key buffers:
CLIENT MAC: 500c7c6e6101cb1693b4cee7db6fb0bc2725deca
SERVER MAC: 41e260280fe213bd5f2c0412c69389cac2e39e4f
CLIENT KEY: c17226212f6195c1515602a0c0864ec90e73e7bcd05ad90b196fd5a5cb2445f2
SERVER KEY: 6b07166b634a7e58e623b969eb0c024a1e866bc2719c054e1a05849b87ccf79b
CLIENT IV: dac71f7b3639cf4d4ec86ee51b9530f6
SERVER IV: c1212631365432c8d5a4c93f6f999a8e
I calculate these values using helper functions I found online:
function p_hash($algo, $secret, $seed, $size) {
$output = "";
$a = $seed;
while (strlen($output) < $size) {
$a = hash_hmac($algo, $a, $secret, true);
$output .= hash_hmac($algo, $a . $seed, $secret, true);
}
return substr($output, 0, $size);
}
function prf_tls12($secret, $label, $seed, $size) {
return p_hash("sha256", $secret, $label . $seed, $size);
}
function generate_master($pre_master_secret, $client_random, $server_random) {
return prf_tls12($pre_master_secret, 'master secret', $client_random . $server_random, 48);
}
$client_random = hex2bin('61fc160e0a6e96db43aebcca55da7fbccb97cc04d59fcc105490b4396a915ab9');
$server_random = hex2bin('f0ecb127db6e353a2985894c123532a8d092fafcf7cdce3a444f574e47524401');
$pre_master_secret = hex2bin('0303ec4418e91f0abf9a012f524b61c0312008641ebce76d68b2417447e3d9a970d02fd65a20e5e3e98413dbd13b6536');
$master_secret = generate_master($pre_master_secret, $client_random, $server_random);
$key_buffer = prf_tls12($master_secret, 'key expansion', $server_random . $client_random, 136);
$client_mac = substr($key_buffer, 0, 20);
$server_mac = substr($key_buffer, 20, 20);
$client_key = substr($key_buffer, 40, 32);
$server_key = substr($key_buffer, 72, 32);
$client_iv = substr($key_buffer, 104, 16);
$server_iv = substr($key_buffer, 120, 16);
Here I have an AES_256_CBC encrypted message sent from the CLIENT ---> SERVER in Hex format
$EncryptedMessage = 'f32da333a3416888d55c583c9796f8fc498895e386616a62aa364a41cd2bfc203c1f296b4afd9c4a9674c993bf0db558de0c0cb2b3dc4b083af3824e0b9a3327';
I run the following code using the PHPSECLIB v3.0 plugin:
$cipher = new AES('cbc');
$cipher->setIV($client_iv);
$cipher->setKey($client_key);
$cipher->disablePadding();
$DecryptedMessage = bin2hex($cipher->decrypt(hex2bin($EncryptedMessage)));
print($DecryptedMessage);
I get the following output in Hex:
f889ff0ce7cc744c2182363e7117ae74e34ccb0510099e7c11133c369f98468de9f20fa6e7207c8121484a9663929d1af4bffb5410da37029aa26b9298411e3b
Basically, I have no idea whether I'm doing this right or not. I dont seem to see anything in my decrypted message. Also, unless I specifically use the $cipher->disablePadding(); I will get a PHP Fatal Error saying that PHP Fatal error: Uncaught phpseclib3\Exception\BadDecryptionException: The ciphertext has an invalid padding length (81) compared to the block size (16)
Note: This is supposed to be an "Encrypted Handshake Message" sent as the first message from a client to server after the Key Exchange using TLS 1.2. I am unable to determine if my decryption is correct, since I cant find much on the structure of value anywhere. Any help is appreciated, thanks!

What is the proper way to parse yahoo currency http://finance.yahoo.com/connection/currency-converter-cache?date?

As the code i tried and by trial removal to get json content out of the return is below
method i used.
$date= YYYYMMDD;
//example '20140113'
$handle = fopen('http://finance.yahoo.com/connection/currency-converter-cache?date='.$date.'', 'r');
//sample code is http://finance.yahoo.com/connection/currency-converter-cache?date=20140208 paste the url in browser;
// use loop to get all until end of content
while (!feof($handle)) {
$contents .= fread($handle, 8192);
}
fclose($handle);
the code return a given bulk in yahoo and json format
so remove the unknown format which is
"/**/YAHOO.Finance.CurrencyConverter.addConversionRates (" and ends with ");"
by
$contents = str_replace('/**/YAHOO.Finance.CurrencyConverter.addConversionRates(','',$contents);
$contents = str_replace(');','',$contents);
$obj = json_decode($contents,true);
then loop the content by
foreach($obj['list']['resources'] as $key0 => $value0){
}
I prefer to use file_get_contents to get the html and preg_match_all to cleanup the json, i.e.:
<?php
$json = file_get_contents("http://finance.yahoo.com/connection/currency-converter-cache?date=20140113");
preg_match_all('/\((.*)\);/si', $json, $json, PREG_PATTERN_ORDER);
$json = $json[1][0];
$json = json_decode($json,true);
foreach ($json["list"]["resources"] as $resource){
echo $resource["resource"]["fields"]["date"];
echo $resource["resource"]["fields"]["price"];
echo $resource["resource"]["fields"]["symbol"];
echo $resource["resource"]["fields"]["price"];
}
NOTE:
I've tested the code and it works as intended.

Socket fread() sometimes return an empty string

I'm using some API to get a remote server's info by sending a packet with fwrite() and then read the returned value by fread(). Most of the times it works properly, but every 5 to 10 times, it will return an empty string from fread(). This is the code I use:
public function getInfo()
{
#fwrite($this->rSocket, $this->createPacket('i'));
$inforead = fread($this->rSocket, 999);
if(strlen($inforead) >= 28)
{
$inforead = substr($inforead, 11);
$aDetails['password'] = (integer) ord(substr($inforead, 0, 1));
$aDetails['players'] = (integer) $this->toInteger(substr($inforead, 1, 2));
$aDetails['maxplayers'] = (integer) $this->toInteger(substr($inforead, 3, 2));
$inforead = substr($inforead, 5);
$iStrlen = ord(substr($inforead, 0, 4));
if(!$iStrlen) return -1;
$aDetails['hostname'] = (string) substr($inforead, 4, $iStrlen);
$inforead = substr($inforead, 4+$iStrlen);
$iStrlen = ord(substr($inforead, 0, 4));
$aDetails['gamemode'] = (string) substr($inforead, 4, $iStrlen);
$inforead = substr($inforead, 4+$iStrlen);
$iStrlen = ord(substr($inforead, 0, 4));
$aDetails['mapname'] = (string) substr($inforead, 4, $iStrlen);
}
return $aDetails;
}
I also debugged fwrite() and it seems it returns the number of bytes written and not false, meaning the error wasn't in fwrite(). Is the problem with my code or with the server failing to provide the info?
The constructor opens the socket, so it won't be visible here.
I've just encountered a strange stream socket situation, my fread code always returned empty string.
I replaced fread by stream_get_contents and problem solved

How to make api request cache with php?

There is a code api url and it is output json format. I need cache my json result or different solution. Because my page when visiting new user it calling api again and page opening speeds consists of problems. How can i make it?
My Code:
<?php
$jsonurl = 'http://api.site.com/deal/browse.html?apiKey=VN43U6&p=2';
$json = file_get_contents($jsonurl, 0, null, null);
$json_output = json_decode($json);
foreach ($json_output->deals as $objects) {
$title = $objects->title;
echo '<h5 class="coupon-title">' . $title . '</h5>';
}
?>
If you want to use memcache as your cache service, you can try something like this:
$memcache = new Memcache;
$memcache->connect("localhost", 11211);
$hash = hash('sha256', $jsonurl);
$json = $memcache->get($hash);
if (!$json) {
$json = file_get_contents($jsonurl, 0, null, null);
$memcache->set($hash, $json, false, strtotime("+1 day"));
}
$json_output = json_decode($json);
Just cache it in a file :
$cache_json='yourfilename.json';
if(!is_file(cache_json)){
$json = file_get_contents($jsonurl, 0, null, null);
file_put_contents($cache_json,$json);
}
else{
$json = file_get_contents($cache_json);
}
$json_output = json_decode($json);
With this example the cache is infinite, you can just remove the cache file with a cron task or check the file creation timestamp with the php function filemtime to set a time limit for cache.
You can cache it in DB too with a table with 3 fields : key, value (json), timeout

PHP Websocket Server hybi10

So Chrome 14 has implemented hybi10 version of websockets. I have a in house program that our company uses via chrome that uses websockets which is broken with this change.
Has anyone been successful framing the data using a php server? I am able to get the new handshake to work but I can't seem to figure out the framing. There is a python example here https://github.com/kanaka/websockify/blob/master/websocket.py#L233 but I am having a difficult time converting this to php, anyone have a suggestion?
I should mention that the function in question on the python example is decode_hybi().
i just completed a class wich makes the PHP-Websocket-Server of Nico Kaiser (https://github.com/nicokaiser/php-websocket) capable of handling hybi-10 frames and handshake. You can download the new class here: http://lemmingzshadow.net/386/php-websocket-serverclient-nach-draft-hybi-10/ (Connection.php)
This code assumes no errors or malformed frames and is based on this answer - How to (de)construct data frames in WebSockets hybi 08+?.
This code is very basic and is far from a complete solution. It works for my purposes (which are pretty basic). Hopefully it is of use to others.
function handle_data($data){
$bytes = $data;
$data_length = "";
$mask = "";
$coded_data = "" ;
$decoded_data = "";
$data_length = $bytes[1] & 127;
if($data_length === 126){
$mask = substr($bytes, 4, 8);
$coded_data = substr($bytes, 8);
}else if($data_length === 127){
$mask = substr($bytes, 10, 14);
$coded_data = substr($bytes, 14);
}else{
$mask = substr($bytes, 2, 6);
$coded_data = substr($bytes, 6);
}
for($i=0;$i<strlen($coded_data);$i++){
$decoded_data .= $coded_data[$i] ^ $mask[$i%4];
}
$this->log("Server Received->".$decoded_data);
return true;
}
Here is the code to send data back. Again this is pretty basic, it assumes you are sending a single text frame. No continuation frames etc. No error checking either. Hopefully others find it useful.
public function send($data)
{
$frame = Array();
$encoded = "";
$frame[0] = 0x81;
$data_length = strlen($data);
if($data_length <= 125){
$frame[1] = $data_length;
}else{
$frame[1] = 126;
$frame[2] = $data_length >> 8;
$frame[3] = $data_length & 0xFF;
}
for($i=0;$i<sizeof($frame);$i++){
$encoded .= chr($frame[$i]);
}
$encoded .= $data;
write_to_socket($this->socket, $encoded);
return true;
}

Categories