Required output generated for json data - php

{"99.net":{"status":"regthroughothers","classkey":"dotnet"},
"99.org": {"status":"regthroughothers","classkey":"domorg"},
"99.mobi":{"status":"regthroughothers","classkey":"dotmobi"},
"99.name":{"status":"Invalid Domain Name","classkey":"dotname"},
"99.us":{"status":"regthroughothers","classkey":"domus"},
"99.com":{"status":"regthroughothers","classkey":"domcno"},
"99.info":{"status":"Invalid Domain Name","classkey":"dominfo"},
"99.co.uk":{"status":"available","classkey":"thirdleveldotuk"},
"99.biz":{"status":"Invalid Domain Name","classkey":"dombiz"},
"99.in":{"status":"Invalid Domain Name","classkey":"dotin"}}
I'm able to display the output with the following code:
$json1 = json_decode($response1);
foreach($json1 as $key=>$sel_rows)
{
echo $key ;
echo " status: ". $sel_rows->status." ";
echo " Class: ". $sel_rows->classkey." ";
echo "Price";
echo "<br>";
}<br>
Now, I need to sort it so that a table such as the following can be shown:
<table border="1">
<tr>
<td>.com</td>
<td>.net</td>
<td>.info</td>
<td>.org</td>
</tr>
<tr>
<td>ADD</td>
<td>ADD</td>
<td>ADD</td>
<td>ADD</td>
</tr>
</table>
I'm having trouble figuring out how to sort the response in a way that I can use to generate this table, using the response data to add tool tips to the ADD links (like dinakar.com).

$json1 = json_decode($response1, TRUE);
foreach($json1 as $key=>$sel_rows)
{
echo $key ;
echo " status: ". $sel_rows['status']." ";
echo " Class: ". $sel_rows['classkey']." ";
echo "Price";
echo "<br>";
}

It looks like you're not having a problem decoding the response, but rather normalizing it for what you need to display. To do that, you'll need to extract the TLD from the domain string, unless you know it ahead of time. Presumably you do, as it was used to request the response to begin with?
Anyway, the following code illustrates one way of getting it into an array suitable for you to pass to your view (or however you're doing it):
$response1 = <<< EOF
{"99.net":{"status":"regthroughothers","classkey":"dotnet"},
"99.org": {"status":"regthroughothers","classkey":"domorg"},
"99.mobi":{"status":"regthroughothers","classkey":"dotmobi"},
"99.name":{"status":"Invalid Domain Name","classkey":"dotname"},
"99.us":{"status":"regthroughothers","classkey":"domus"},
"99.com":{"status":"regthroughothers","classkey":"domcno"},
"99.info":{"status":"Invalid Domain Name","classkey":"dominfo"},
"99.co.uk":{"status":"available","classkey":"thirdleveldotuk"},
"99.biz":{"status":"Invalid Domain Name","classkey":"dombiz"},
"99.in":{"status":"Invalid Domain Name","classkey":"dotin"}}
EOF;
function get_tld($url) {
$host = parse_url($url);
$domain = $host['path'];
$tail = substr($domain, -7); // Watch out, gotcha! Be sure of this.
$tld = strstr($tail, ".");
return $tld;
}
$domains = array();
$json1 = json_decode($response1);
foreach ($json1 as $idx => $obj) {
$tld = get_tld($idx);
$domains[$tld] = array('tld' => $tld, 'status' => $obj->status, 'classkey' => $obj->classkey);
}
This is off the top of my head. The resulting $domains array looks like this (truncated for brevity):
Array
(
[.net] => Array
(
[tld] => .net
[status] => regthroughothers
[classkey] => dotnet
)
[.org] => Array
(
[tld] => .org
[status] => regthroughothers
[classkey] => domorg
)
Note, I'm not doing a whole lot of sanity here, but that should be enough to help you sink your teeth into it. You'd then just make your table head off the keys, and populate your add links with whatever information they need that was returned in the response.

Related

Is this a reasonably secure way to use $_GET

I am just a weekend coder and only work on my own projects but I would like to use $_GET in a reasonably secure way. I typically use $_GET from a table with many items that I would like to perform some action on (Edit, Delete). Do any of you veterans see any security issues with the functions I have created or a simpler more elegant way of doing it? I appreciate any input, Thanks.
<?php session_start();
if (empty($_SESSION['SecretKey'])) {
$_SESSION['SecretKey'] = bin2hex(openssl_random_pseudo_bytes(16));
}
function GetURLEncode($ArrayData,$SecretKey,$Echo = true) {
$GetQuery = http_build_query($ArrayData,'','&');
$Checksum = http_build_query(Array("Checksum" => hash_hmac('ripemd160', $GetQuery, $SecretKey)));
if ($Echo) {
echo ''.htmlspecialchars($ArrayData['Action']).'';
} else {
return "?".$GetQuery."&".$Checksum;
}
}
function GetURLDecode($GetData,$SecretKey,&$ReturnData) {
$Checksum = $GetData['Checksum'];
unset($GetData['Checksum']);
$GetQuery = http_build_query($GetData,'','&');
if (hash_equals(hash_hmac('ripemd160', $GetQuery, $SecretKey),$Checksum)) {
$ReturnData = $GetData;
return true;
}
$ReturnData = "";
return false;
}
if (!empty($_GET)) {
if (GetURLDecode($_GET,$_SESSION['SecretKey'],$ReturnData)) {
echo "Array Returned<br>";
echo var_dump($ReturnData)."<br><Br>";
} else {
echo "Checksum Error<br><br>";
}
}
//Example 1
$MyArray1 = Array ("FirstName" => "John",
"LastName" => "Doe",
"Adderss" => "12345 MyStreet",
"City" => "Apple Valley",
"State" => "California");
echo "Sample 1<br>";
$URL = GetURLEncode($MyArray1,$_SESSION['SecretKey'],false);
echo 'Click Me';
//Example 2
$MyArray2 = Array(Array("Id" => 0,"Make" => "Chevy","Model" => "HHR"),
Array("Id" => 1,"Make" => "Chevy","Model" => "Corvette"),
Array("Id" => 2,"Make" => "Ford","Model" => "Mustang"),
Array("Id" => 3,"Make" => "Nissan","Model" => "Sentra"),
Array("Id" => 4,"Make" => "Ford","Model" => "Ranger"),
Array("Id" => 5,"Make" => "Dodge","Model" => "Charger"));?>
<br><br>
<table>
<th>sample 2</th>
<?php foreach ($MyArray2 as $Array) { ?>
<tr>
<td><?= $Array['Make'];?></td>
<td><?= $Array['Model'];?></td>
<td><?php GetURLEncode(array("Id"=>$Array['Id'],"Action"=>"Edit"),$_SESSION['SecretKey']);?></td>
<td><?php GetURLEncode(array("Id"=>$Array['Id'],"Action"=>"Delete"),$_SESSION['SecretKey']);?></td>
</tr>
<?php } ?>
</table>
Hello there weekend coder, the only issue i see with using a GET method is that a user can directly change the GET data in the url. for example, lets take youtube for example ( at least back in the day ), each youtube video has a GET value of v and it's value is some random 64bit alphanumeric hex hash of digits and you can see it directly in the URL youtube com/watch?v=xxxxxxxxxxxx since this is so, you can manually change this value and it will take you to another video because you changed the video id number. this is useful because you can copy this link and send it to your friends.
on the other hand, POST is different as you cannot really directly change the POST data values being sent. though there some mischievous ways some may be able too, which is why form validation is always needed for POST forms and values!!!
if we changed youtube's methods to use POST, all youtube videos would have youtubeDOTcom as the URL and the video ID would be hidden underneath the page as POST. now the user cannot directly see their video's random unique ID and cannot send the link to others to be shared.
Hope this explains a bit, it depends on what type of information you are sending. if you think it should be secured and not visible to all users, use POST. if you want the link to be shared and changed often to view different pages,media, etc, that's not confidential, you can use GET

API in 1 request instead of multiple loops

This question has been asked before, however the answers did not match the api im using.
Essentially the API i am using is split up into different functions just to get ALL domain names owned by 1 customer i selected. As the array is in soap and comes out in arrays im having to put them in loops. This makes it extremely slow with 400 results and having to loop through each individually with seperate queries 3 times or so. I am hoping i can run them in 1 instead of multiple queries however it seems far past my coding abilities.
//include the required files
require_once('includes/config.php');
require_once('classes/reseller_api.php');
//initialise the base reseller_api object
$reseller_api = new reseller_api();
//construct the request data
//send the request
$response = $reseller_api->call('GetDomainList', $request);
$decodedresponse = json_encode( $response, true );
$decoded_response = json_decode( $decodedresponse, true );
$loadeddata = $decoded_response['APIResponse']['DomainList'];
foreach ($loadeddata as $key => $value) {
$domainnameis = $value['DomainName'];
$domainnamestatus = $value['Status'];
$domainnameexpiry = $value['Expiry'];
$domainnameexpiry2 = date('d-m-Y',strtotime($domainnameexpiry));
?>
<tr>
<?php
/// GET THE DOMAIN NAME OWNER ID
$request2 = array(
'DomainName' => $value['DomainName']
);
$response2 = $reseller_api->call('DomainInfo', $request2);
if (isset($response2->APIResponse->DomainDetails)) {
$domainownerident = $response2->APIResponse->DomainDetails->RegistrantContactIdentifier;
/// NOW IF THE OWNER ID CAME BACK, GRAB THE NAME OF THE OWNER
$request3 = array(
'ContactIdentifier' => $domainownerident
);
$response3 = $reseller_api->call('ContactInfo', $request3);
/// NOW WE HAVE THE OWNER, SEE IF ITS OWNED BY HEAD OFFICE AND LAUNCH IT
if ($response3->APIResponse->ContactDetails->FirstName == "Reece") {
?>
<td <?php echo $domainbckstyle; ?>><?php echo $domainnameis; ?></td>
<td><?php echo $regback; ?></td>
<td <?php echo $domainbckstyle; ?>><?php echo $domainnameexpiry2; ?></td>
</tr>
<?php }}}} ?>
API Documentation here: http://docdro.id/jzpZNdv
from what i can see it does not have the ability too. It is on a per call basis and doesnt except arrays.

How to Parse the ajax script in DOM Parser?

I parsing scores from http://sports.in.msn.com/football-world-cup-2014/south-africa-v-brazil/1597383
I able to parse all the attributes. But I can't able to parse the time.
I Used
$homepages = file_get_html("http://sports.in.msn.com/football-world-cup-2014/south-africa-v-brazil/1597383");
$teama = $homepages->find('span[id="clock"]');
Kindly help me
Since the that particular site is loading the values dynamically (thru AJAX request), you cant really parse the value upon initial load.
<span id="clock"></span> // this tends to be empty initial load
Normal scrapping:
$homepages = file_get_contents("http://sports.in.msn.com/football-world-cup-2014/south-africa-v-brazil/1597383");
$doc = new DOMDocument();
#$doc->loadHTML($homepages);
$xpath = new DOMXPath($doc);
$query = $xpath->query("//span[#id='clock']");
foreach($query as $value) {
echo $value->nodeValue; // the traversal is correct, but this will be empty
}
My suggestion is instead of scraping it, you will need to have to access it thru a request also, since it is a time (of course, as the match goes on this will change and change until the game has ended). Or you can also use their request.
$url = 'http://sports.in.msn.com/liveplayajax/SOCCERMATCH/match/gsm/en-in/1597383';
$contents = file_get_contents($url);
$data = json_decode($contents, true);
echo '<pre>';
print_r($data);
echo '</pre>';
Should yield something like (a part of it actually):
[2] => Array
(
[Code] =>
[CommentId] => -1119368663
[CommentType] => manual
[Description] => FULL-TIME: South Africa 0-5 Brazil.
[Min] => 90'
[MinExtra] => (+3)
[View] =>
[ViewHint] =>
[ViewIndex] => 0
[EditKey] =>
[TrackingValues] =>
[AopValue] =>
)
You should get the 90' by using foreach. Consider this example:
foreach($data['Commentary']['CommentaryItems'] as $key => $value) {
if(stripos($value['Description'], 'FULL-TIME') !== false) {
echo $value['Min'];
break;
}
}
Should print: 90'

Implode associative array with variable key name

I'm using an associative array to build a list of albums and the images inside those albums. The array is built with the following code (some code omitted for clarity -- just the stuff that loads $title, $desc, etc.):
<?php
$directory = 'gallery/*';
$subfolders = glob($directory);
foreach($subfolders as $subfolder) {
$photos = glob($subfolder.'/*.[Jj][Pp][Gg]');
$album = explode('_', $subfolder);
$albumname = str_replace(' ','%20',$album[1]);
foreach($photos as $photo){
$photolist[$albumname] .= '<span data-title="'.$title.'" data-desc="'.$desc.'" data-camera="'.$camera.'" data-lens="'.$lens.'" data-length="'.$length.'" data-shutter="'.$shutter.'" data-aperture="'.$aperture.'" data-iso="'.$iso.'" style="background-image:url('.$photo.'); background-size:contain;" class="slide"></span>';
}
}
?>
I'm trying to use implode() to spit out the relevant elements based on the $currentalbum (read from a cookie) as follows:
<?php
if(isset($_COOKIE["currentalbum"])) {
$currentalbum = $_COOKIE["currentalbum"];
} else {
$currentalbum = "New";
}
$currentphotolist = implode("",$photolist[$currentalbum]);
echo $currentphotolist;
?>
This is returning the error:
Warning: implode() [function.implode]: Invalid arguments passed in index.php on line 97
I presume it has some problem with the array, but when I print_r() it, I get the following, which looks fine:
Array
(
[New] => <span data-title="Train" data-desc="This is a picture of a train. Look at it go!" data-camera="Nikon D300" data-lens="Tamron 17-50mm f/2.8 VC" data-length="17mm" data-shutter="1/250s" data-aperture="f/6.3" data-iso="200" style="background-image:url(gallery/01_New/Train.jpg); background-size:contain;" class="slide"></span><span data-title="Billow" data-desc="" data-camera="Nikon D300" data-lens="Nikkor 50mm f/1.8D" data-length="50mm" data-shutter="1/250s" data-aperture="f/8" data-iso="200" style="background-image:url(gallery/01_New/Billow.jpg); background-size:contain;" class="slide"></span><span data-title="3059" data-desc="" data-camera="Nikon D300" data-lens="Micro-Nikkor 105mm f/2.8 VR" data-length="105mm" data-shutter="1/30s" data-aperture="f/22" data-iso="200" style="background-image:url(gallery/01_New/3059.jpg); background-size:contain;" class="slide"></span>
[Landscapes] => <span data-title="Influx" data-desc="" data-camera="Nikon D300" data-lens="Nikkor 70-300mm f/4.5-5.6 VR" data-length="70mm" data-shutter="30s" data-aperture="f/8" data-iso="200" style="background-image:url(gallery/02_Landscapes/Influx.jpg); background-size:contain;" class="slide"></span>
[Constructs] => <span data-title="Fervor" data-desc="I took this while wandering around in SEA-TAC airport waiting for a flight home. It\'s a lantern, hanging with some others in a shop. It caught my eye from across the terminal, but the shop was pretty small and I\'m always a little worried about knocking stuff with my camera bag, so I shot it through the window. I think it turned out pretty well regardless." data-camera="Nikon D7000" data-lens="Tamron 17-50mm f/2.8 VC" data-length="50mm" data-shutter="1/60s" data-aperture="f/2.8" data-iso="180" style="background-image:url(gallery/03_Constructs/Fervor.jpg); background-size:contain;" class="slide"></span>
)
Any idea why I'm getting the error?
The second argument to implode should be an array. It seems from your foreach loop that $photolist[$currentalbum] is a string.
Try
foreach($photos as $photo){
$photolist[$albumname][]= '<span data-title...</span>';
}
I believe implode requires a character as the first attribute. Try using a space or comma.
// Space
$currentphotolist = implode(" ",$photolist[$currentalbum]);
// Comma
$currentphotolist = implode(",",$photolist[$currentalbum]);

Json PHP Output Numbers(Integer)

I hope I'm right here.
I am making a search engine and take my Data from a json-file(url)
I can read out the text with my code (php)
<?php
foreach ($obj['Products'] as $key => $value) {
echo '<p>Artikel: '.$value['ProductName']. '</p> <br/>';
echo '<p> Produktbeschreibung: '.$value['Description'].'</p> <br/><br/>';
echo ' zum Shop <br/><br/>';
}
$service = "http://dateck-media.de/sf/ddd.php ;This is the JSON // Put together request $request = $service . "?" . http_build_query($params); Get response $response = file_get_contents($request,TRUE); $obj = json_decode($response,true);
but now i want to show the results of my search. in my json file it looks like
Array (
[ProductsSummary] => Array (
[Records] => 20
[TotalRecords] => 41
[TotalPages] => 3
[CurrentPage] => 1
)
[Products]
I don't know how to get the [Totalrecords] in my code to ECHO "You have [TotalRecords] for your search"
Please help me.
You could write the total as follows (outside of the loop you have):
echo "You have {$obj['ProductsSummary']['TotalRecords']} results for your search";
Thx to all and sorry for my English... now i will try to put the Total- and CurrentPages at the End of the search, to go forward to the next site! But first i try alone :-)

Categories