I am working on a little project for a programming course here on my university. It involves getting data from the google api (JSON) and providing some of that information to the user.
function compare($city, $start, $destination)
{
// merge city with start and destination
$city_start = $start . ', ' . $city;
$city_destination = $destination . ', ' . $city;
// reject symbols that start with ^
if (preg_match("/^\^/", $city) OR preg_match("/^\^/", $start) OR preg_match("/^\^/", $destination))
{
return false;
}
// reject symbols that contain commas
if (preg_match("/,/", $city) OR preg_match("/,/", $start) OR preg_match("/,/", $city))
{
return false;
}
// determine url
$url = "http://maps.googleapis.com/maps/api/directions/json?origin=$city_start&destination=$city_destination&sensor=false&mode=bicycling";
echo $url;
// open connection to google maps
$curl_session = curl_init($url);
curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_session, CURLOPT_HEADER, 0);
// get data from json output
$json = curl_exec($curl_session);
curl_close($curl_session);
var_dump($json);
}
The above code returns a 400 error at var_dump, where $city, $start and $destination are respectively starting adress, destination adress and the city where the addresses belong to. The url stored in $url works alright and returns JSON output when entered in a browser.
Can anyone tell me what I am doing wrong?
Cheers,
D.
You could try and urlencode the variables:
$city_start = urlencode($start . ', ' . $city);
$city_destination = urlencode($destination . ', ' . $city);
Related
Today i have some php cURL code that must show to user his loacation like: ip, country, city it have.. And if the user is bot - do nothing. So, i do it like this, but it's not working properly. Only ip is shown and nothing else.. Please help.. And let the power be with you.. Thank to all for help.
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$apiurl = "https://api.2ip.ua/geo.json?ip=$ip";
//--
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$apiurl");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec ($ch);
//--
curl_close ($ch);
//- **************-//
$pieces = explode('"', $contents);
$country = $pieces['7'];
$city = $pieces['11'];
$city2 = $pieces['13'];
echo "Your IP is :" . $ip . " and country " .$country. " and city " .$city;
?>
Don't use explode!, the answer of the api is a JSON, instead you got to do this:
$data = json_decode($contents, true);
$country = $data['country'];
$city = $data['city'];
and so on for any other field you need.
BTW you can also improve the IP detection with this code that support multiple detection with ipv4 and ipv6 support
if (isset($_SERVER['REMOTE_HOST'])) {
$ip = $_SERVER['REMOTE_HOST'];
} elseif (isset($_SERVER['HOST'])) {
$ip = $_SERVER['HOST'];
} elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
} else {
$host = '';
}
$ip = str_replace("::ffff:","",$ip);//::ffff:127.127.127.127 en caso de jugo ipv6
Regards and vote up
First, don't use explode, use json_decode instead and then there is something wrong with the SSL-Certificate of your API so use http instead.
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$apiurl = "http://api.2ip.ua/geo.json?ip=";
$contents = file_get_contents($apiurl . $ip);
$json = json_decode($contents);
$country = $json->country;
$city = $json->city;
echo "Your IP is :" . $ip . " and country " . $country . " and city " . $city;
I use CURL in php, and I use CURL something like this
$url = "http://exampledomain.com";
$smsURL = $url;
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, $smsURL);
curl_exec ($curl);
curl_close ($curl);
This is not working, but if I wrote "http://exampledomain.com" in place of "$smsURL" at curl_setopt (); It will work fine. Where is issue in my code? did I miss something?
Original Code
$url = $this->conf['sms_getway_url'];
$url .= '&recipient=' . $_POST['txt_customer_contact_no'];
$url .= '&sender=' . strtoupper($saloon_info['saloon_name']);
$url .= '&is_payor=' . $this->conf['sms_is_payor'];
$url .= '&pay_amount=' . $this->conf['sms_pay_amount'];
$url .= '&token=5ce7467e9ec045cbbac448ba5a422a02';
//$url .= '&customer_num=' . $this->conf['sms_customer_num'] . $saloon_id;
$url .= '&customer_num=' . $this->conf['sms_customer_num'];
$appointment_time = date('H:i', strtotime($app_start_time));
$employee_name = $_POST['hdn_selected_employee_name']; //$value['id_employee'];
//$sms_msg = "Hey. Recalling that I await tomorrow at. " . $appointment_time . " Regards " . $employee_name . ", " . $saloon_name . ". ";
$sms_msg = t('msg_sms_book_appointment', array('%emp_name' => $employee_name, '%saloon_name' => $_POST['hdn_selected_saloon_name'], '%time' => $appointment_time));
$url .= '&sms_msg=' . $sms_msg;
$smsURL = $url;
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, $smsURL);
curl_exec ($curl);
curl_close ($curl);
Thanks
You compose the URL from pieces but you don't encode the values properly. There are characters that have special meaning in URLs (/, ?, &, =, %, , + and a few more). They have to be encoded when they appear in the values from the query string, in order to retain their literal meaning.
PHP helps you for this goal with function urlencode() that can be used to encode each value individually when you create a query string. Something like this:
$url = $this->conf['sms_getway_url'];
$url .= '&recipient=' . urlencode($_POST['txt_customer_contact_no']);
$url .= '&sender=' . urlencode(strtoupper($saloon_info['saloon_name']));
...
But, because this is a tedious work, it also provides an easier method. Put all the values you need into an array, using the names of the variables as keys, then pass the array to function http_build_query(). There is no need to call urlencode() any more; http_build_query() takes care of it. Also it puts ampersands (&) between the variables and equals (=) where they belong.
The code is like this:
$url = $this->conf['sms_getway_url'];
// Prepare the values to put into the query string
$vars = array();
$vars['recipient'] = $_POST['txt_customer_contact_no'];
$vars['sender'] = strtoupper($saloon_info['saloon_name']);
$vars['is_payor'] = $this->conf['sms_is_payor'];
$vars['pay_amount'] = $this->conf['sms_pay_amount'];
$vars['token'] = '5ce7467e9ec045cbbac448ba5a422a02';
$vars['customer_num'] = $this->conf['sms_customer_num'];
$appointment_time = date('H:i', strtotime($app_start_time));
$employee_name = $_POST['hdn_selected_employee_name'];
$sms_msg = t('msg_sms_book_appointment', array(
'%emp_name' => $employee_name,
'%saloon_name' => $_POST['hdn_selected_saloon_name'],
'%time' => $appointment_time,
));
$vars['sms_msg'] = $sms_msg;
// Now, the magic comes into place
$smsURL = $url.'?'.http_build_query($vars);
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, $smsURL);
if (! curl_exec ($curl)) {
// Something went wrong. Check the status code (at least)
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
// Do something here.
// If $code >= 500 then the remote server encountered an internal error
// retry later or ask them to fix it
// If 400 <= $code < 500 then there is a problem with the request:
// maybe the resource is not there (404, 410)
// or you are not allowed to access it (403)
// or something else.
echo('Failure sending the SMS. HTTP status code is '.$code."\n");
}
curl_close ($curl);
Check the list of HTTP status codes for more details.
I have following problem. I'm using google maps in php to get the address of latitude and longitude and a map snapshot of this location.
To obtain address I use following code:
// INITIALIZING CURL
$returnValue = NULL;
$ch = curl_init();
// SERVICE CALL
$url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=".$lat.",".$lon."&sensor=false";
// SETTING PARAMS OF CURL
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// GETTING AND RESULTING RESULT
$result_part = curl_exec($ch);
$json = json_decode($result_part, TRUE);
And I parse obtained JSON as follows:
// PARSING RESULTS FROM JSON
if (isset($json['results'])) {
foreach ($json['results'] as $result_part) {
foreach ($result_part['address_components'] as $address_component) {
$types = $address_component['types'];
// GETTING STREET
if (in_array('route', $types)) {
$addr = $address_component['long_name'];
}
// GETTING STREET NUMBER
if (in_array('street_number', $types)) {
$number = $address_component['long_name'];
}
// GETTING COUNTRY
if (in_array('country', $types)) {
$country = $address_component['long_name'];
}
// GETTING POSTAL CODE
if (in_array('postal_code', $types)) {
$postal_code = $address_component['long_name'];
}
// GETTING CITY
if (in_array('locality', $types)) {
$city = $address_component['long_name'];
}
}
}
}
It works fine but sometimes the address is not obtained. It looks like some overload of requests but I dont understand why because the site that I'm programming is not accessible yet for other people.
Other problem connected to this is the map snapshots. Here is the code:
<? echo "<a href = \"https://maps.google.com/maps?q=".$lat.",".$lon."\" target=\"_blank\">" ?>
<? echo "<img src=\"http://maps.googleapis.com/maps/api/staticmap?center=" . $lat . "," . $lon . "&zoom=16&size=200x200&markers=color:blue%7Clabel:I%7C" . $lat . "," . $lon . "&sensor=false\" alt=\"google maps\" width=\"200\" height=\"200\" /></a>" ?>
This works also fine but sometimes I obtain image like this:
I doubt that I exceeded the limit.
Any ideas ? Thank you for your answers.
As #geocodezip has suggested it could be because of not using a key.
Also as per the reverse geocoding documentation on :
https://developers.google.com/maps/documentation/geocoding/#ReverseGeocoding
Note: Reverse geocoding is an estimate. The geocoder will attempt to find the closest addressable location within a certain tolerance; if no match is found, the geocoder will return zero results.
I'm trying to get the real file URL from a url that doesn't show up the real file name.
My url is like this http://video.premium.com/file/ee7bfec921cfbe16e6f08e282992b99670a00ca3/3
If I could get the real file url I could stream it directly online through a web player, but it needs .mp4 or other file format to play, just the url http://video.premium.com/file/ee7bfec921cfbe16e6f08e282992b99670a00ca3/3 doesnt work.
but when I open the URL using VLC media player, it works. doesn't work with online flash or other players..
Is this even possible? Anyway to do this?
With curl, use this: It follows the redirect until it finds the endpoint. In the included code I used goo.gl to shorten the url to a rando image. You will see the output is the original link (and it would output whatever number of redirects and their URLs), and the final redirect to the actual file. I think this is what you are looking for. I did not write this originally, but found it somewhere some time ago and reused it many times again with tweaking when needed. It seems to fit well in many places. Glad to pass it on. I think it might help to achieve what you are looking for.
<?php
function follow_redirect($url){
$redirect_url = null;
if(function_exists("curl_init")){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
}
else{
$url_parts = parse_url($url);
$sock = fsockopen($url_parts['host'], (isset($url_parts['port']) ? (int)$url_parts['port'] : 80));
$request = "HEAD " . $url_parts['path'] . (isset($url_parts['query']) ? '?'.$url_parts['query'] : '') . " HTTP/1.1\r\n";
$request .= 'Host: ' . $url_parts['host'] . "\r\n";
$request .= "Connection: Close\r\n\r\n";
fwrite($sock, $request);
$response = fread($sock, 2048);
fclose($sock);
}
$header = "Location: ";
$pos = strpos($response, $header);
if($pos === false){
return false;
}
else{
$pos += strlen($header);
$redirect_url = substr($response, $pos, strpos($response, "\r\n", $pos)-$pos);
return $redirect_url;
}
}
$url = 'http://goo.gl/66VJB';
echo '<ol>';
while(($newurl = follow_redirect($url)) !== false){
echo '<li>', $url, '</li>';
$url = $newurl;
}
echo '</ol>';
echo '', $url, '';
?>
Output:
http://goo.gl/66VJB
http://1.bp.blogspot.com/_XE0TDW07Noo/TOSVQXZtgAI/AAAAAAAAELo/aG80jZ7u_fo/s1600/aptitude_test.gif
I have spent the past couple of hours trying all types of variations but according to the Twitter API this should have worked from step 1!
1 addition I have made to the script below is that I have added in:
$header = array("Expect:");
This I found helped in another question on stackoverflow from getting a denied issue / 100-continue.
Issue:
Failed to validate oauth signature and token is the response EVERY time!!!
Example of my post data:
Array ( [oauth_callback] => http://www.mysite.com//index.php [oauth_consumer_key] => hidden [oauth_nonce] => hidden [oauth_signature_method] => HMAC-SHA1 [oauth_timestamp] => 1301270847 [oauth_version] => 1.0 )
And my header data:
Array ( [0] => Expect: )
Script:
$consumer_key = "hidden";
$consumer_secret = "hidden";
function Post_Data($url,$data,$header){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$data['oauth_callback'] = "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
$data['oauth_consumer_key'] = $consumer_key;
$data['oauth_nonce'] = md5(time());
$data['oauth_signature_method'] = "HMAC-SHA1";
$data['oauth_timestamp'] = time();
$data['oauth_version'] = "1.0";
$header = array("Expect:");
$content = Post_Data("http://api.twitter.com/oauth/request_token",$data,$header);
print_r($content);
Can anybody see an obvious mistake that I may be making here? Preferably I would not like to go with somebody elses code as most examples have full classes & massive functions, I am looking for the most simple approach!
Your problem is that you did not include the OAuth signature in your request.
You can read about the concept on this page.
A working implementation can be found here.
I faced same issue, what I was missing is passing header in to the curl request.
As shown in this question, I was also sending the $header = array('Expect:'), which was the problem in my case. I started sending signature in header with other data as below and it solved the case for me.
$header = calculateHeader($parameters, 'https://api.twitter.com/oauth/request_token');
function calculateHeader(array $parameters, $url)
{
// redefine
$url = (string) $url;
// divide into parts
$parts = parse_url($url);
// init var
$chunks = array();
// process queries
foreach($parameters as $key => $value) $chunks[] = str_replace('%25', '%', urlencode_rfc3986($key) . '="' . urlencode_rfc3986($value) . '"');
// build return
$return = 'Authorization: OAuth realm="' . $parts['scheme'] . '://' . $parts['host'] . $parts['path'] . '", ';
$return .= implode(',', $chunks);
// prepend name and OAuth part
return $return;
}
function urlencode_rfc3986($value)
{
if(is_array($value)) return array_map('urlencode_rfc3986', $value);
else
{
$search = array('+', ' ', '%7E', '%');
$replace = array('%20', '%20', '~', '%25');
return str_replace($search, $replace, urlencode($value));
}
}