trying to loop through array and pass values to php cURL request - php

Hello I have a successful cURL request that returns the 8 largest cities in a country including the city name, country code, latitude and longitude ($largeCities['records']). What I then want to do is loop through that array and pass the latitude, longitude and country code of each city to a new cURL routine (geonames findNearbyWikipedia api) and return that data to use in my JavaScript. I'm wondering if this is possible and if so where am I going wrong. Currently when I run the $.ajax request on my php file I'm just getting an empty array cityCluster: Array(0)
relevent php code:
//large cities in country
$url='https://public.opendatasoft.com/api/records/1.0/search/?dataset=geonames-all-cities-with-a-population-1000&q=&rows=8&sort=population&facet=timezone&facet=country&refine.country_code='. $countryCodeA2;
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
$largeCities = json_decode($result,true);
$output['data']['largeCities'] = $largeCities['records'];
foreach ($largeCities['records'] as $key => $value) {
$cityLat = $value['geometry']['coordinates'][0];
$cityLng = $value['geometry']['coordinates'][1];
$countryCodeISO2 = $value['fields']['country_code'];
//wiki cities clusters
$url='http://api.geonames.org/findNearbyWikipediaJSON?formatted=true&lat=' . $cityLat . '&lng=' . $cityLng . '&country='. $countryCodeISO2 .'&maxRows=15&username=' . $geoUserName . '&style=full';
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
curl_close($ch);
$cityCluster = json_decode($result,true);
};
//output status
$output['status']['code'] = "200";
$output['status']['name'] = "ok";
$output['status']['description'] = "success";
$output['status']['executedIn'] = intval((microtime(true) - $executionStartTime) * 1000) . " ms";
$output['data']['cityCluster'] = $cityCluster['geonames'];
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($output);

Related

Binance REST API - Placing a PHP Order (POST) via Query String

I am struggling using Binance's REST API. I have managed to get working GET request via query string such as pinging the server, ticker information, etc. My challenge now is performing POST request via query string using cURL. I have been scraping code from various places and referring back to the API to get pieces to work but I am unsure as to why I am getting this error returned from the result... {"code":-1102,"msg":"Mandatory parameter 'signature' was not sent, was empty/null, or malformed."}
(ERROR SHOWN ON WEBPAGE). I echo out the signature and its a load of gibberish so I would believe that the hash_hmac performed at the top would be working, but honestly I got pretty lucky making the GET request work. Does anyone have any suggestions as to why this would be broken? Thanks!
$apikey = "MYKEY";
$apisecret = "MYSECRET";
$timestamp = time()*1000; //get current timestamp in milliseconds
$signature = hash_hmac('sha256', "TRXBTC&type=market&side=buy&quantity=100.00&recvWindow=10000000000000000&timestamp=".$timestamp, $apisecret);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.binance.com/api/v3/order/test");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, "symbol=TRXBTC&type=market&side=buy&quantity=100.00&recvWindow=10000000000000000&timestamp=".$timestamp);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded","X-MBX-APIKEY: ".$apikey,"signature: ".$signature));
$response = curl_exec($ch);
curl_close($ch);
echo $response;
As per their API docs:
SIGNED endpoints require an additional parameter, signature, to be sent in the query string or request body.
You are sending the signature via neither of these methods and are instead sending it through the header.
Change this:
curl_setopt($ch, CURLOPT_POSTFIELDS, "symbol=TRXBTC&type=market&side=buy&quantity=100.00&recvWindow=10000000000000000&timestamp=".$timestamp);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded","X-MBX-APIKEY: ".$apikey,"signature: ".$signature));
To this:
curl_setopt($ch, CURLOPT_POSTFIELDS, "symbol=TRXBTC&type=market&side=buy&quantity=100.00&recvWindow=10000000000000000&timestamp=" . $timestamp . "&signature=" . $signature);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded","X-MBX-APIKEY: ".$apikey));
<?php
$secret = "F................";
$key = "D.................";
$s_time = "timestamp=".time()*1000;
$sign=hash_hmac('SHA256', $s_time, $secret);
$url = "https://api.binance.com/api/v3/account?".$s_time.'&signature='.$sign;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-MBX-APIKEY:'.$key));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
$result = json_decode($result, true);
echo '<pre>';
var_dump($result);
echo '</pre>';
?>
Here is an example, using php-curl-class
// Variables
// url, key and secret is on separate file, called using require once
$endPoint = "/api/v3/order/test";
$coin = "BTC";
$fiat = "EUR";
$symbol = $coin . "" . $fiat;
$side = "BUY";
$type = "LIMIT";
$timeInForce = "GTC";
$quantity = 1;
$price = 10000;
$timestamp = time();
// Constructing query arrays
queryArray = array(
"symbol" => $symbol,
"side" => $side,
"type" => $type,
"timeInForce" => $timeInForce,
"quantity" => $quantity,
"price" => $price,
"timestamp" => $timestamp*1000
);
$signature = hash_hmac("sha256", http_build_query($queryArray), $secret);
$signatureArray = array("signature" => $signature);
$curlArray = $queryArray + $signatureArray;
// Curl : setting header and POST
$curl->setHeader("Content-Type","application/x-www-form-urlencoded");
$curl->setHeader("X-MBX-APIKEY",$key);
$curl->post($url . "" . $endPoint, $curlArray);
if ($curl->error) {
echo 'Error: ' . $curl->errorCode . ': ' . $curl->errorMessage . "\n";
}
$order = $curl->response;
print_r($order);
I had the same problem, and nothing of above doesn't helped.
So I finaly figured out how to make order on my way.
So, maybe this helps someone.
function Kupovina($buy_parametri) {
$key = "xxxxxxxxxxxxxxx";
$secret = "xxxxxxxxxxxx";
$s_time = "timestamp=".time()*1000;
$timestamp = time()*1000; //get current timestamp in milliseconds
$sign = hash_hmac('sha256', $buy_parametri."&timestamp=".$timestamp, $secret);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.binance.com/api/v3/order");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $buy_parametri."&".$s_time."&signature=".$sign);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded","X-MBX-APIKEY: ".$key));
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$buy_parametri = "symbol=BTCUSDT&type=market&side=buy&quantity=0.00086";
Call function:
Kupovina($buy_parametri);

Walmart API Search Products

I am trying to get search products for a keyword
My code:
$searchquery = "ipod";
$api_endpoint = "http://api.walmartlabs.com/v1/search";
$postfields = "apiKey=". $appid ."&query=" . $searchquery;
//$postfields = array('apiKey' => $appid, 'query' => $searchquery);
$connection = curl_init();
curl_setopt($connection, CURLOPT_URL, $api_endpoint);
curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($connection, CURLOPT_SSL_VERIFYHOST, 0);
//curl_setopt($connection, CURLOPT_HTTPHEADER, $headers);
curl_setopt($connection, CURLOPT_POST, true);
curl_setopt($connection, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($connection, CURLOPT_HEADER, true);
//curl_setopt($connection, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($connection, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($connection);
curl_close($connection);
print_r($api_endpoint);
print_r($response);
When i go in browser and visit api.walmartlabs.com/v1/search?apiKey={appid}&query=ipod , it shows results, but when i try to do with curl , it shows
"Action Not Found"
Here is the Screenshot
Any help would be appreciated.
looking on the doc (https://developer.walmartlabs.com/io-docs) it appears that the server expects a GET request.
Just replace your POST request with a GET request and all should be fine
$searchquery = "ipod";
$api_endpoint = "http://api.walmartlabs.com/v1/search";
$urlParams = "apiKey=". $appid ."&query=" . $searchquery;
$fullUrl = $api_endpoint . '?' . $urlParams;
$connection = curl_init();
curl_setopt($connection, CURLOPT_URL, $fullUrl);
curl_setopt($connection, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($connection, CURLOPT_HEADER, true);
curl_setopt($connection, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($connection);
curl_close($connection);
print_r($api_endpoint);
print_r($response);
<?php
ini_set('display_errors', 1);
//API URL : https://affiliates.walmart.com/#!/api
$api_key="**********"; //https://developer.walmartlabs.com/apps/mykeys
$keywords="men%20watches"; // Search text - whitespace separated sequence of keywords to search for
$format="json"; // data we want in response
$responseGroup="base"; // Specifies the item fields returned in the response, allowed response groups are [base, full]. Default value is base.
$sort='price'; //Sorting criteria, allowed sort types are [relevance, price, title, bestseller, customerRating, new]. Default sort is by relevance.
$order="asc"; //Sort ordering criteria, allowed values are [asc, desc]. This parameter is needed only for the sort types [price, title, customerRating].
//http://api.walmartlabs.com/v1/search?apiKey={apiKey}&lsPublisherId={Your LinkShare Publisher Id}&query=ipod
$request_url="http://api.walmartlabs.com/v1/search?apiKey=".$api_key."&query=".$keywords."&format=".$format."&responseGroup=".$responseGroup."&sort=".$sort."&order=".$order;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$request_url);
curl_setopt($ch, CURLOPT_FAILONERROR,1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$retValue = curl_exec($ch);
// Check for errors and display the error message
if($errno = curl_errno($ch)) {
$error_message = curl_strerror($errno);
echo "cURL error ({$errno}):\n {$error_message}";
}
curl_close($ch);
$arr = json_decode($retValue,true);
echo "<pre>";
print_r($arr);
// echo "<pre>";
// var_dump($retValue);
?>

Curl doesn't update database

I am trying to update my online database with the offline version. The following code executes without giving an error code but the expected result is not showing. Any help will be really appreciated as series of Google searching proved abortive.
<?php
include("inc_files/inventory.php");
// update sales_rec records
$get_sales_rec = mysql_query("SELECT * FROM sales_rec WHERE status = '0' ORDER BY id ASC") or die(mysql_error());
while($rec = mysql_fetch_array($get_sales_rec)){
$id = $rec['id'];
$receipt = $rec['receipt'];
$customer = $rec['customer'];
$total = $rec['total'];
$amount = $rec['amount'];
$balance = $rec['balance'];
$discount = $rec['discount'];
$date = $rec['date'];
$time = $rec['time'];
? $type = "sales_rec";
$ch = curl_init(); // initiate curl
$url = "http://www.sample.com/inventory/test.php"; // where you want to post data
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, true); // tell curl you want to post something
curl_setopt($ch, CURLOPT_POSTFIELDS, "type=$type&r=$receipt&c=$customer&t=$total&a=$amount&b=$balance&d=$discount&dt=$date&ti=$time"); // define what you want to post
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return the output in string format
$output = curl_exec ($ch); // execute
curl_close ($ch); // close curl handle
}
?>
have you tried passing an array
$data = array('name' => 'aaa', 'title' => 'dev');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

"type Invalid 16-bit integer. invalid Input.format.short " error while HTTP POST request using CURL

I am newbie with Social Minor I am trying to create a new Feed in Social Miner using "Social-Miner Create Feed API".
Problem:
When I click on "Create Feed" button on my interface I receive following error: " type Invalid 16-bit integer. invalid Input.format.short "
Code:
<?php
error_reporting(o);
$URL = "http://192.168.200.163:8080/ccp-webapp/ccp/feed";
//Create Feed form values
$type = $_POST['type'];
$feed_name = $_POST['feed_name'];
$description = $_POST['description'];
$ur = $_POST['ur'];
$polling_interval = $_POST['polling_interval'];
$minimum_age = $_POST['minimum_age'];
$reply_template = $_POST['reply_template'];
$tags = $_POST['tags'];
//Storing above values in a string
$myFeedString='<?xml version="1.0" encoding="utf-8"?>
<Feed>
<type>$type</type>
<name>$feed_name</name>
<description>$description</description>
<ur>$ur</ur>
<polling_interval>$polling_interval</polling_interval>
<minimum_age>$minimum_age</minimum_age>
<tags>
<tag>$tags</tag>
</tags>
</Feed>
';
//setting the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_USERPWD, "hashmatkhan" . ":" . "Army2life");
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $myFeedString);
if (curl_errno($ch))
{
//moving to display page to display curl errors
echo curl_errno($ch) ;
echo curl_error($ch);
}
else
{
//getting response from server
$response = curl_exec($ch);
print_r($response);
curl_close($ch);
}
?>
Need Help?

getting Latitude And Longitude From Pin Code Using PHP

In my site i want to get the latitude and longitude of given pin code or postal code.
If i give 680721 as pin code or postal code then i want to get its corresponding latitude and longitude using php code.
How can i do this?
If this is possible in PHP?
I have php code to get latitude and longitude of given name of place.
$Url='http://maps.googleapis.com/maps/api/geocode/json?address='.$exp_pjctloc[$i].'&sensor=false';
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_REFERER, "http://www.example.org/yay.htm");
curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$output = curl_exec($ch);
curl_close($ch);
$search_data = json_decode($output);
$lat = $search_data->results[0]->geometry->location->lat;
$lng = $search_data->results[0]->geometry->location->lng;
But how can i get it by using pin code or postal code?
Below code worked for me
<?php
$zipcode="92604";
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=".$zipcode."&sensor=false";
$details=file_get_contents($url);
$result = json_decode($details,true);
$lat=$result['results'][0]['geometry']['location']['lat'];
$lng=$result['results'][0]['geometry']['location']['lng'];
echo "Latitude :" .$lat;
echo '<br>';
echo "Longitude :" .$lng;
?>
This worked for me:
$zip = 94043;
$site = file_get_contents('http://geocoder.ca/?postal='.$zip, false, NULL, 1000, 1000);
$goods = strstr($site, 'GPoint('); // cut off the first part up until
$end = strpos($goods, ')'); // the ending parenthesis of the coordinate
$cords = substr($goods, 7, $end - 7); // returns string with only the
$array = explode(', ',$cords); // convert string into array
echo "<pre>";
print_r($array); // output the array to verify
With the curl you can get lat and long from below code:
$zipcode=90012;
$url = "https://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($zipcode)."&sensor=false&key=XXXXXXXX";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$output = curl_exec($ch);
curl_close($ch);
$search_data = json_decode($output);
$lat = $search_data->results[0]->geometry->location->lat;
$lng = $search_data->results[0]->geometry->location->lng;

Categories