ok, i think i just fucked up everything because of my brain failure.
I followed Google's example of "phpsqlsearch_v3":
imported the sql file
change the query from showing miles to kilometers
testing by using this:
phpsqlsearch_genxml.php?lat=37.315903&lng=-121.977928&radius=40
everything works as charm...
going into website to get latlong, adding and changing some data in db
now, I'm changing the phpsqlsearch_genxml.php to....
phpsqlsearch_genxml.php?lat=59.627847&lng=17.838589&radius=40
...nothing... however, if i change radius to 8000 it will work but the distance for places around input will be like 5665.231121242624km but if i flip the input because I'm on the right side of the earth blink blink to
phpsqlsearch_genxml.php?lat=17.838589&lng=59.627847&radius=100
it will give me a more accurate result, however... the result should closer and around 1-2km...
suggestion what to do now?
function getAddress($lat, $lng) {
$use_curl = false;
if ($use_curl) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://maps.googleapis.com/maps/api/geocode/json?latlng=" . $lat . "," . $lng . "&sensor=true");
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, Array (
"Content-type: application/binary"
));
curl_setopt($ch, CURLOPT_POST, 1);
$response = curl_exec($ch);
if (curl_errno($ch))
return -1;
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$str = substr($response, $header_size);
curl_close($ch);
$data = json_decode($str, true);
if (isset($data["results"]) && is_array($data["results"])) {
$street = $data["results"][0]["formatted_address"];
$ac = $data["results"][0]["address_components"];
$len = count($ac);
$i = 0;
$city = "";
while ($i<$len) {
if (in_array("locality", $ac[$i]["types"])) $city = $ac[$i]["long_name"];
else if (in_array("country", $ac[$i]["types"])) $city .= ",".$ac[$i]["short_name"];
$i++;
}
$meta = array(
"status"=>200,
"message"=>"Succeed."
);
return array("meta"=>$meta, "response"=>array("address"=>$street, "city"=>$city));
} else {
$meta = array(
"status"=>406,
"message"=>"Address is not known."
);
return array("meta", $meta);
}
} else {
$str = #file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=" . $lat . "," . $lng . "&sensor=true");
$data = json_decode($str, true);
if (isset($data["results"]) && is_array($data["results"])) {
$street = $data["results"][0]["formatted_address"];
$ac = $data["results"][0]["address_components"];
$len = count($ac);
$i = 0;
$city = "";
while ($i<$len) {
if (in_array("locality", $ac[$i]["types"])) $city = $ac[$i]["long_name"];
else if (in_array("country", $ac[$i]["types"])) $city .= ",".$ac[$i]["short_name"];
$i++;
}
$meta = array(
"status"=>200,
"message"=>"Succeed."
);
return array("meta"=>$meta, "response"=>array("address"=>$street, "city"=>$city));
} else {
$meta = array(
"status"=>406,
"message"=>"Address is not known."
);
return array("meta"=>$meta);
}
}
}
Related
This is the challenge: In the PHP file, write a program to perform a GET request on the route https://coderbyte.com/api/challenges/json/age-counting which contains a data key and the value is a string which contains items in the format: key=STRING, age=INTEGER. Your goal is to count how many items exist that have an age equal to or greater than 50, and print this final value.
Example Input
{"data":"key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt, age=47"}
Once your function is working, take the final output string and replace all characters that appear in your ChallengeToken with --[CHAR]--.
Your ChallengeToken: ndv946kie1
Here's my code:
<?PHP
$ch = curl_init('https://coderbyte.com/api/challenges/json/age-counting');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
//print_r(json_decode($data, true));
$arr = json_decode($data, true);
$items = explode(', ', $arr['data']);
$count = 0;
foreach ($items as $item){
//print_r($item . PHP_EOL);
if(str_starts_with($item,'age=')===true){
$age = explode('=',$item)[1];
if($age >= 50)
$count++;
}
}
$str = 'ndv946kie1';
$chars = str_split($str);
$final = '';
foreach ($chars as $char){
$final = $final . $count;
}
print_r($final);
?>
coderbyte says incorrect output, maybe I misunderstood the last instruction?
I had the same problem...
Giving below the code that worked for me:
<?php
$ch = curl_init('https://coderbyte.com/api/challenges/json/age-counting');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
//print_r(json_decode($data, true));
$arr = json_decode($data, true);
$items = explode(', ', $arr['data']);
$count = 0;
foreach ($items as $item){
//print_r($item . PHP_EOL);
if(str_starts_with($item,'age=')===true){
$age = explode('=',$item)[1];
if($age >= 50)
$count++;
}
}
print_r($count);
?>
Please try with this
<?php
$ch = curl_init('https://coderbyte.com/api/challenges/json/age-counting');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
$json_data = json_decode($data, true);
$items = explode(', ', $json_data['data']);
$count = array_reduce($items, function ($count, $item) {
if (strpos($item, 'age=') !== false) {
$age = explode('=', $item)[1];
if ($age >= 50) return $count + 1;
}
return $count;
}, 0);
print_r($count);
Good evening,
I'm creating a script to check proxies.
But, I understand a little bit about the loop in PHP, I do my best ..
Here is the code:
<?php
//$_POST INFORMATIONS
$address = $_POST['address'];
if (!empty($_POST['address']))
{
//COMPTE LE NOMBRE D'ENTREES
$delimiter = $address;
$delimiterArray = ($delimiter != '')?explode(",",$delimiter):NULL;
$arrayCount = count($delimiterArray);
for ($i = 1; $i <= $arrayCount; $i++) {
$url = 'http://api.proxyipchecker.com/pchk.php';
//DELIMITE L'IP ET PORT
$format = explode(":", $address);
$ip = $format[0];
$port = $format[1];
//CURL
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,'ip='.$ip.'&port='.$port);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
list($res_time, $speed, $country, $type) = explode(';', curl_exec($ch));
//REMPLACE LE RESULT
if (isset($type))
{
if ($type >= 4 or $type <= 0)
{
$type = "Undefined";
}
elseif ($type = 1)
{
$type = "Transparent";
}
elseif ($type = 2)
{
$type = "Anonymous";
}
elseif ($type = 3)
{
$type = "High anonymous";
}
}
//ECHO RESULT
echo $ip.":".$port." / Response time: ".$res_time." seconds / Country ".$country." / Type ".$type."\n";
}
}
Error is here
//DELIMITE L'IP ET PORT
$format = explode(":", $address);
$ip = $format[0];
$port = $format[1];
Since it is a loop put [0], [1] it will be good for the first, and then it will be an offset ..
If anyone has an idea, thank you very much!
Informations:
Format -> IP:PORT,IP:PORT..
And I need IP & PORT for each address for cURL.
Thanks you!
Breaking down what you're trying to do, your loop logic is a bit off and far too complicated for what (I think) you want.
...
//COMPTE LE NOMBRE D'ENTREES
//THIS IS THE FULL STRING (IP:PORT,IP:PORT,...)
$delimiter = $address;
//THIS IS AN ARRAY OF FORM 0 => "IP:PORT", 1 => "IP:PORT", etc.
$delimiterArray = ($delimiter != '')?explode(",",$delimiter):NULL;
//ARRAYS ARE ITERABLE; USE FOREACH TO TRAVERSE EACH ENTRY
foreach ($delimiterArray as $value){
$value = explode(":", $value);
//THE COPY INSIDE OF VALUE IS NOW AN ARRAY;
//$value[0] IS THE IP
//$value[1] IS THE PORT
//NOW DO WHAT YOU WANT WITH THOSE VALUES
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,'ip='.$value[0].'&port='.$value[1]);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
list($res_time, $speed, $country, $type) = explode(';', curl_exec($ch));
//REMPLACE LE RESULT
if (isset($type))
{
if ($type >= 4 or $type <= 0)
{
$type = "Undefined";
}
elseif ($type = 1)
{
$type = "Transparent";
}
elseif ($type = 2)
{
$type = "Anonymous";
}
elseif ($type = 3)
{
$type = "High anonymous";
}
}//end foreach
You will probably want to close each curl session after completion as well (curl_close)
I wrote a script that communicates with a popular game, called kahoot. It logs in and answer's each question, and then echo's when it is finished. Here is it working on the command line. However, when I add this functionality to my website, when I run it it gives me a 504 gateway timeout, even though before the timeout it should have produced some output and echoed it to the page.
Here is the website code:
Full execution code:
<html>
<head>
<title>Kahoot bot</title>
</head>
<body>
<?php
$username = 'kahootbot28#gmail.com';
$password = 'botkahoot28';
$loginUrl = 'https://create.kahoot.it/rest/authenticate';
$kahootId = $_GET['quizid'];
$type = $_GET['what'];
if ($type == "bot") {
$call = "~/www/reteps.tk/go/kahoot-auto " . $_GET['gamepin'] . " " . $_GET['username'] . " ";
echo($call);
}
$pageUrl = 'https://create.kahoot.it/rest/kahoots/' . $kahootId;
$loginheader = array();
$loginheader[] = 'content-type: application/json';
$loginpost = new stdClass();
$loginpost->username = $username;
$loginpost->password = $password;
$loginpost->grant_type = "password";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $loginUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($loginpost));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,$loginheader);
$store = curl_exec($ch);
curl_close($ch);
$token = json_decode($store,true)["access_token"];
//get questions
$quizheader = array();
$quizheader[] = 'authorization: ' . $token;
$options = array(
'http' => array(
'method' => 'GET',
'header' => "Authorization: ".$token."\r\n"
)
);
$pairs = array(
0 => "red",
1 => "blue",
2 => "yellow",
3 => "green",
);
$context = stream_context_create($options);
$raw_result = file_get_contents($pageUrl, false, $context);
$result = json_decode($raw_result,true)["questions"];
echo("<a href='kahoot_bot'>back</a><br>");
foreach($result as $value) {
if ($type == "text") {
echo($value['question']." ");
}
$choices = $value['choices'];
for($i=0;$i<count($choices);$i++) {
if ($choices[$i]['correct'] == true) {
if ($type == "text") {
echo($choices[$i]['answer']."<br>");
} elseif ($type == "bot") {
$call .= $i;
} else {
echo($pairs[$i].", ");
}
break 1;
}
}
}
if ($type == "bot") {
$old_result = "";
$handle = popen($call . " 2>&1", "r");
$result = fread($handle, 2096);
echo($result);
while ((strpos($result, "end") !== false) != true) {
$result = fread($handle, 2096);
sleep(1);
if ($result != $old_result) {
echo($result);
$old_result = $result;
}
}
pclose($handle);
}
?>
</body>
</html>
I have following loop to calculate comments and likes
function AddCampaignDetails($next=null){
$AccessToken = ACCESS_TOKEN;
$url = "https://api.instagram.com/v1/tags/canonfanatic/media/recent?access_token=".$AccessToken;
if($url !== null) {
$url .= '&max_tag_id=' . $next;
}
/*//Also Perhaps you should cache the results as the instagram API is slow
$cache = './'.sha1($url).'.json';
if(file_exists($cache) && filemtime($cache) > time() - 60*60){
// If a cache file exists, and it is newer than 1 hour, use it
$jsonData = json_decode(file_get_contents($cache));
}else{
$jsonData = json_decode((file_get_contents($url)));
file_put_contents($cache,json_encode($jsonData));
}*/
$Ch = curl_init();
curl_setopt($Ch, CURLOPT_URL, $url);
curl_setopt($Ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($Ch, CURLOPT_TIMEOUT, 20);
$Result = curl_exec($Ch);
curl_close($Ch);
$Result = json_decode($Result);
$Data = $Result->data;
//echo "<pre>"; print_r($Data); echo "</pre>";
$CommentsSum = 0;
$LikesSum = 0;
for($i=0; $i<count($Data); $i++){
$CommentsSum += $Data[$i]->comments->count;
$LikesSum += $Data[$i]->likes->count;
}
//echo ' Comments '.$CommentsSum;
//echo ' Likes '.$LikesSum;
echo "<br />";
if(isset($Result->pagination->next_url) && !empty($Result->pagination->next_url)){
$next = $Result->pagination->next_url;
$this->AddCampaignDetails($next);
}else{
$NextUrl = "";
die;
}
return $result;
}
After this loop, I have echo $CommentsSum; variable and get this output
183
306
320
42
Now I want above number sum 851.
Any idea?
Thanks.
Your $Data[$i]->comments->count must be a number, and it's seem that is a string, so it's merging string instead of doing math.
And If you really have a new line between each number (like you said in echo) maybe $Data[$i]->comments->count is equal to "183\n"
use for example :
$CommentsSum += intval($Data[$i]->comments->count)
I use the code in php to connect to the api and display the results...
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
require("OAuth.php");
$cc_key = "cc_key"; //cc_key
$cc_secret = "cc_secret"; // cc_secret key
$url = "https://yboss.yahooapis.com/ysearch/web";
$args = array();
$args["q"] = htmlspecialchars($_GET["q"]);
$args["format"] = "json";
$consumer = new OAuthConsumer($cc_key, $cc_secret);
$request = OAuthRequest::from_consumer_and_token($consumer, NULL,"GET", $url, $args);
$request->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, NULL);
$url = sprintf("%s?%s", $url, OAuthUtil::build_http_query($args));
//echo $url . "<br>"; test uri
$ch = curl_init();
$headers = array($request->to_header());
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$rsp = curl_exec($ch);
$results = json_decode($rsp, true);
//force to assoc-array, which will allow array-access
foreach($results['bossresponse']['web']['results'] as $result)
{
//$result is array here, but do the same stuff
echo '<a href="'.$result['url'].'" target=\'_blank\'>'.$result['title'].'</a></br>';
echo ''.$result['abstract'].'</br>';
echo '<a href="'.$result['url'].'" target=\'_blank\'>'.$result['dispurl'].'</a></br>';
}
?>
then write mini "pagination"
//$start = "&start=" . "0";
$start_val = $_GET['start'];
if ($start_val == "") $start_val = 0;
$start = "&start=" . $start_val;
// Some more code...
$count_val = 10;
$count = "&count=" . $count_val;
if ($query != "") {
if ($start_val != 0) {
echo 'previous';
echo '<span> | </span>';
}
echo 'next';
}
but "pagination" does not work =(
I can not understand why does not work
My question is how do I paginate results, since all the 50 results appear on the first web page only. I want to display ten results in every page.
Please HELP me
Thanks.