Properly returning JSON format to page - javascript

I am attempting to capture a latitude and longitude and then pass it to Google Maps to return some data and then exact the zip code out of the response and use that.
When I call it directly to a browser I get a response on the page that ends up being like:
{"zip":"90029"}
But when I attempt to view it in Chrome's developer tools, it states "This request has no response data". So it seems as though my JSON is not being encoded properly, or I am not returning it to the page properly in a JSON format type header.
I've tried various things, and nothing seems to work properly in order to get it return the JSON data.
Here's my present code:
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
$now = #date("Ymd-His");
$myFile = "loc" . $now . ".txt";
$fh = fopen("locations/" . $myFile, 'w') or die("can't open file");
$lat = $_REQUEST['lat'];
$long = $_REQUEST['long'];
$type = $_REQUEST['type'];
$phone = $_REQUEST['phone'];
$loc = $_REQUEST['typed_location'];
$url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$long&sensor=false";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_ENCODING, "");
$curlData = curl_exec($curl);
curl_close($curl);
$address = json_decode($curlData, true);
$temp_data = $address['results'][0]['formatted_address'];
$temp = explode(", ", $temp_data);
$temp_2 = explode(" ", $temp[2]);
$zip = $temp_2[1];
fwrite($fh, $zip);
fclose($fh);
$array = array("zip" => $zip);
$t = json_encode($array);
echo $t;

For anyone else looking to solve this problem - when using cross domains, be sure to allow for the Access-Control by setting the following as a header:
header("access-control-allow-origin: *");

Related

altering javascript function to fit an AJAX to PHP call

I'm creating modals to provide information about various countries.
One of the modals I am trying to create is to show the weather and I found this codepen example which is very nice! https://codepen.io/irwingb1979/pen/XWMbqmP
Is there any way to make such a call using javaScript AJAX to a PHP file like such
<?php
// remove for production
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$executionStartTime = microtime(true);
$url='https://api.openweathermap.org/data/2.5/onecall?lat=' . $_REQUEST['lat'] . '&lon=' . $_REQUEST['lng'] . '&units=metric&appid=01a69c43fa692a1e67ae4c9bdabb8fdc';
$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);
echo var_dump($result, $url);
$decode = json_decode($result,true);
$output['status']['code'] = "200";
$output['status']['name'] = "ok";
$output['status']['description'] = "success";
$output['status']['returnedIn'] = intval((microtime(true) - $executionStartTime) * 1000) . " ms";
$output['data'] = $decode['geonames'];
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($output);
?>
I'm not quite sure how to alter it to fit my modal and call like above

AngularJS stream audio from PHP server 2

I have the following PHP code which authenticate to a third-party server using JWT and download the recorded audio from the server and then it serves the .mp3 to javascript which constructs an Audio object to playback the audio. How to do this more efficiently?
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Key;
use Lcobucci\JWT\Signer\Rsa\Sha256;
private function generate_jwt() {
$dev = preg_match("/blah.blah.com/", $_SERVER["HTTP_HOST"]);
$jwt = false;
date_default_timezone_set('UTC'); //Set the time for UTC + 0
//$key = file_get_contents($keyfile); //Retrieve your private key
$key = $dev ? self::DEV_KEY : self::PRODUCTION_KEY;
$id = $dev ? self::DEV_ID : self::PRODUCTION_ID;
$signer = new Sha256();
$privateKey = new Key($key);
$jwt = (new Builder())->setIssuedAt(time() - date('Z')) // Time token was generated in UTC+0
->set('application_id', $id) // ID for the application you are working with
->setId( base64_encode( mt_rand ( )), true)
->sign($signer, $privateKey) // Create a signature using your private key
->getToken(); // Retrieves the JWT
return $jwt;
}
public function playback($url) {
$response = "";
if (!empty($url)) {
//Create your JWT
$jwt = $this->generate_jwt();
//Add the JWT to your headers
$headers = array('Content-Type: application/json', "Authorization: Bearer " . $jwt);
$ch = curl_init();
//Make a request to $recording_url
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$file = __TMPDIR__ . basename($url).".mp3";
file_put_contents($file, $response);
header('Pragma: public'); // required
header('Content-Type: audio/mpeg');
header('Content-length: ' . filesize($file));
header("Content-Transfer-Encoding: binary");
header('Content-Disposition: filename="' . basename($file));
header('X-Pad: avoid browser bug');
header('Cache-Control: no-cache');
$len = readfile($file);
} else
error_log(__FILE__." ".__FUNCTION__." ".__LINE__.": Invalid url! ".$url);
}

How to consume here.com's REST api service

Has anyone tried using here.com's rest api?
I'm trying to run an example request, but nothing happens. I'm new to REST, so I'm clueless about the problem. If the $url is plugged directly into the browsers address text box, the image is displayed, but my curl function in the code below does not retrieve anything, or so it seems.
$url = "http://image.maps.cit.api.here.com/mia/1.6/route?app_id=redacted&app_code=redacted&r0=52.5338,13.2966,52.538361,13.325329&r1=52.540867,13.262444,52.536691,13.264561,52.529172,13.268337,52.528337,13.273144,52.52583,13.27898,52.518728,13.279667&m0=52.5338,13.2966,52.538361,13.325329&m1=52.540867,13.262444,52.518728,13.279667&lc0=440000ff&sc0=440000ff&lw0=6&lc1=44ff00ff&sc1=44ff00ff&lw1=3";
$ch = curl_init($url);
$options = array(
CURLOPT_CONNECTTIMEOUT => 20 ,
CURLOPT_AUTOREFERER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
$result = json_decode($response);
echo "response: <br>";
echo "<br>";
echo "result: <br> " . $result;
curl_close($ch);
I found the error in the end.. This is a working sample of using the here.com REST api that I'm posting so that anyone who is in the same situation may have a look at it. The problem was that the construction of the query string was incorrect as I just copied and pasted it from the browser. If anybody comes across the same problem, I recommend taking a look at the documentation here..
$base_url = 'http://image.maps.cit.api.here.com';
$path = '/mia/1.6/';
$resource = 'route'; // type of service... this should change if you want something else
$query_string = array(
'app_id' => 'XXXXXXXXXXXXXXXXXXXXXX', //your app id
'app_code' => 'XXXXXXXXXXXXXXXXXXXXXX', // your app code
'r0' => '52.540867,13.262444,52.536691,13.264561,52.529172,13.268337,52.528337,13.273144,52.52583,13.27898,52.518728,13.279667', // coords for the route
'lw' => '4', // line width
'lc' => '00ff00', // line color
);
$url = $base_url . $path.$resource . '?' . http_build_query($query_string);
$img_file = './img/test_img2.jpg'; // save image here
$ch = curl_init($url);
$fp = fopen($img_file, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
?>
<img src='<?php echo $img_file;?>'>

Replace whateverorigin.org call with local proxy in php

I'm currently using whateverorigin.org in some javascript to retrieve a URL as a JSON object because a 3rd party site hasn't made one of their functions available via their JSON API.
I'd like to remove this dependancy from my website as whateverorigin.org breaks the HTTPS/SSL browser checks for secure content because it's a clear http call.
Has anyone done this? I haven't found an example of it anywhere.
Thanks in advance for a response!
Ok, so since I first typed up this question, I've now already found some examples and cobbled together a working proxy function in php... Feel free to use it for your own purposes!
<?php
// Sourced from: http://stackoverflow.com/questions/2511410/curl-follow-location-error
function curl_exec_follow(/*resource*/ &$ch, /*int*/ $redirects = 20, /*bool*/ $curlopt_header = false) {
if ((!ini_get('open_basedir') && !ini_get('safe_mode')) || $redirects < 1) {
curl_setopt($ch, CURLOPT_HEADER, $curlopt_header);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $redirects > 0);
curl_setopt($ch, CURLOPT_MAXREDIRS, $redirects);
return curl_exec($ch);
} else {
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FORBID_REUSE, false);
do {
$data = curl_exec($ch);
if (curl_errno($ch))
break;
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code != 301 && $code != 302)
break;
$header_start = strpos($data, "\r\n")+2;
$headers = substr($data, $header_start, strpos($data,"\r\n\r\n", $header_start)+2-$header_start);
if (!preg_match("!\r\n(?:Location|URI): *(.*?) *\r\n!",$headers, $matches))
break;
curl_setopt($ch, CURLOPT_URL, $matches[1]);
} while (--$redirects);
if (!$redirects)
trigger_error('Too many redirects. When following redirects, libcurl hit the maximum amount.', E_USER_WARNING);
if (!$curlopt_header)
$data = substr($data, strpos($data, "\r\n\r\n")+4);
return $data;
}
}
header('Content-Type: application/json');
$retrieveurl = curl_init(urldecode($_GET['url']));
$callbackname = $_GET['callback'];
$htmldata = curl_exec_follow($retrieveurl);
if (curl_error($retrieveurl))
die(curl_error($retrieveurl));
$status = curl_getinfo($retrieveurl, CURLINFO_HTTP_CODE);
curl_close($retrieveurl);
$data = array('contents' => $htmldata, 'status' => $status);
$jsonresult = json_encode($data);
echo $callbackname . '(' . $jsonresult . ')';
?>
Hope this helps someone!

Accessing and printing HTML source code using PHP or JavaScript

I am trying to access and then print (or just be able to use) the source code of any website using PHP. I am not very experienced and am now thinking I might need to use JS to accomplish this. So far, the code below accesses the source code of a web page and displays the web page... What I want it to do instead is display the source code. Essentially, and most importantly, I want to be able to store the source code in some sort of variable so I can use it later. And eventually read it line-by-line - but this can be tackled later.
$url = 'http://www.google.com';
function get_data($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
echo get_data($url); //print and echo do the same thing in this scenario.
Consider using file_get_contents() instead of curl. You can then display the code on your page by replacing every opening bracket (<) with < and then outputting it to the page.
<?php
$code = file_get_contents('http://www.google.com');
$code = str_replace('<', '<', $code);
echo $code;
?>
Edit:
Looks like curl is actually faster than FGC, so ignore that suggestion. The rest of my post still stands. :)
You should try to print the result between <pre></pre> tags;
echo '<pre>' . get_data($url) . '</pre>';
I rewrote your function. The function can return the source with lines or without lines.
<?php
function get_data($url, $Addlines = false){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$content = curl_exec($ch);
$content = htmlspecialchars($content); // Prevents the browser to parse the html
curl_close($ch);
if ($Addlines == true){
$content = explode("\n", $content);
$Count = 0;
foreach ($content as $Line){
$lines = $lines .= 'Line '.$Count.': '.$Line.'<br />';
$Count++;
}
return $lines;
} else {
$content = nl2br($content);
return $content;
}
}
echo get_data('https://www.google.com/', true); // Source code with lines
echo get_data('https://www.google.com/'); // Source code without lines
?>
Hope it gets you on your way.
Add a header Content-Type: text/plain
header("Content-Type: plain/text");
Use htmlspecialchars() in php to print the source code.
In your code, use
return htmlspecialchars($data);
instead of
return $data;

Categories