Retrieve a Get Http request in php - php

I need to retrieve a get http request in php and store it in a variable.
I need to execute the following:
https://graph.facebook.com/oauth/access_token?
client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&
grant_type=client_credentials
I know this is simple. just not able to get my head around it.

$content = file_get_contents('https://graph.facebook.com/oauth/access_token?client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&grant_type=client_credentials');

Within the Open Graph protocol page on Facebook, there is an example within the documentation coded using PHP: http://developers.facebook.com/docs/opengraph/
<?php
$ogurl = "INSERT_YOUR_OG_URL_HERE";
define(FACEBOOK_APP_ID, "YOUR_APP_ID_HERE");
define(FACEBOOK_SECRET, "YOUR_SECRET_KEY_HERE");
$mymessage = "Hello World!";
$access_token_url = "https://graph.facebook.com/oauth/access_token";
$parameters = "grant_type=client_credentials&client_id=" . FACEBOOK_APP_ID ."&client_secret=" . FACEBOOK_SECRET;
$access_token = file_get_contents($access_token_url . "?" . $parameters);
$apprequest_url = "https://graph.facebook.com/feed";
$parameters = "?" . $access_token . "&message=" . urlencode($mymessage) . "&id=" . $ogurl . "&method=post";
$myurl = $apprequest_url . $parameters;
$result = file_get_contents($myurl);
// output the post id
echo "post_id" . $result;
}
?>
The key line in actually making the call being:
$result = file_get_contents($myurl);
There is also a good amount of other information about the resulting object you get back there that would be good to take a look into.
Hope this is helpful.

if ($fp = fopen('https://graph.facebook.com/oauth/access_token?
client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&
grant_type=client_credentials', 'r')) {
$content = '';
// keep reading until there's nothing left
while ($line = fread($fp, 1024)) {
$content .= $line;
}
// do something with the content here
// ...
} else {
// an error occured when trying to open the specified url
}

You mean something like
$client_id = $_GET['client_id'];
$client_secret = $_GET['client_secret'];
$grant_type = $_GET['grant_type'];
?
Or rather something like
$content = file_get_contents($url);
?

Use the following
$id = $_GET['client_id'];
$type = $_GET['grant_type'];
$secret = $_GET['client_secret'];
Hope this helps you

Related

How to construct url with http_build_query, but display values without variables?

I'm trying to generate an URL from all values of two arrays by using http_build_query:
Array 1:
$server = array($_GET["server"]);
Array 2:
$data = array($_GET["z_koord"],
$_GET['x_koord'],
$_GET["y_koord"],);
The code for generating URL I currently have written:
$server = array(''=>$_GET["server"]);
$data = array($_GET["z_koord"],
$_GET['x_koord'],
$_GET["y_koord"],);
$url = '.tile.openstreetmap.org';
$saite = http_build_query($server). $url ."/". http_build_query($data,'','/').".png";
Here's the URL made of code above:
=c.tile.openstreetmap.org/0=6/1=90/2=110.png
Here's the structure of url I'm trying to make:
c.tile.openstreetmap.org/6/90/110.png
I have reviewed some other posts about this topic like this one and this, but those posts aren't completely useful for solving my problem.
So I hope someone with greater knowledge could show me a solution or at least a hint how to get closer to solution.
You could use implode():
$server = $_GET["server"];
$data = [$_GET["z_koord"],
$_GET['x_koord'],
$_GET["y_koord"]];
$url = '.tile.openstreetmap.org';
$saite = "$server/$url/" . implode('/', $data) . ".png";
I'm not sure about some things in this code, but the implode() should do the job.
You are using http_build_query in the wrong way. You just don't need that. There are 2 options, you may use any one of them.
Use implode(), the simplest way to do the job.
$server = array(
'' => $_GET['server']
);
$data = array(
$_GET['z_koord'],
$_GET['x_koord'],
$_GET['y_koord'],
);
$url = $server . '.tile.openstreetmap.org';
$saite = $url . '/' . implode("/", $data) . '.png';
Directly create the URL using the Parameters as shown here:
$url = '.tile.openstreetmap.org' .;
$saite = $_GET['server'] . $url . '/' . $_GET['z_koord'] .'/'. $_GET['x_koord'] . '/'.$_GET['y_koord'] . '.png';

Combine 2 place request to get postal code

I would like to combine two place-api calls in one to get further information about listings.
Example:
My first script request provides Name and Address from the API. However, the Placesearch API does not provide the postal code or other information I need.
My current script shows me this:
name;adress,lnt,lng,place_id
but I need more information for each listing, like the postal code, which not included here.
How can I include a 2nd API call for each place_id and display the postal code?
$apikey = 'KEY';
$url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=51.374,10.1495&rankby=distance&name=keyword&language=de&key=$apikey";
$json = file_get_contents($url);
$obj = json_decode($json, true);
for($i=0; $i<count($obj['results']); $i++) {
echo "" . $obj['results'][$i]['name'] . ";" . $obj['results'][$i]['vicinity'] . ";" . $obj['results'][$i]['geometry']['location']['lat'] . ";" . $obj['results'][$i]['geometry']['location']['lng'] . ";" . $obj['results'][$i]['place_id'] . DISPLaY POSTCODE "<BR>";
};
I know, I need to run this query for each place_id:
https://maps.googleapis.com/maps/api/place/details/json?placeid=$place_id=name,rating,formatted_phone_number&key=YOUR_API_KEY
But how can I combine it together with the first results? I need:
Name;Adress;Postcode;LAT;LNG;
Update:
1st request:
$apikey = 'KEY';
$url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=51.374,10.1495&rankby=distance&name=keyword&language=de&key=$apikey";
$json = file_get_contents($url);
$obj = json_decode($json, true);
for($i=0; $i<count($obj['results']); $i++) {
echo "" . $obj['results'][$i]['name'] . ";" . $obj['results'][$i]['vicinity'] . ";" . $obj['results'][$i]['geometry']['location']['lat'] . ";" . $obj['results'][$i]['geometry']['location']['lng'] . ";" . $obj['results'][$i]['place_id'] . DISPLaY POSTCODE "<BR>";
};
this is one ex response from the first request, the ChIJidzOXaLBpEcRxEKHcEN9fuo is the place id which i have to request the details:
Flinsberger Sportplatz;Heilbad Heiligenstadt;51.3163051;10.1929773;ChIJidzOXaLBpEcRxEKHcEN9fuo
this is api call shows the neede details, which i need and can access:
https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJidzOXaLBpEcRxEKHcEN9fuo=name,rating,formatted_phone_number&key=YOUR_API_KEY
i need to include the 2nd request in the 1st, to get for ex. the postalcode for the specific item, which is my problem i dont know.
and the result should be:
name,adress,postalcode, ... , ... ,...
Following the comments, I came up with this. Note that I do not have an API key myself to test, the the idea is there. You might have to adjust the reference to $obj2 based on the result of the json_decode function for the second query (the one in the loop).
<?php
$apikey = 'KEY';
$url1 = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=51.374,10.1495&rankby=distance&name=keyword&language=de&key=$apikey";
$json1 = file_get_contents($url1);
$obj1 = json_decode($json1, true);
for( $i = 0; $i < count($obj1['results']); $i++)
{
$place_id = $obj1['results'][$i]['place_id'];
$url2 = "https://maps.googleapis.com/maps/api/place/details/output?json&key=" .$apikey . "&placeid=" . $place_id . "&fields=address_component"
$json2 = file_get_contents($url2);
$obj2 = json_decode($json2, true);
echo "" . $obj1['results'][$i]['name'] . ";" . $obj1['results'][$i]['vicinity'] . ";" . $obj1['results'][$i]['geometry']['location']['lat'] . ";" . $obj1['results'][$i]['geometry']['location']['lng'] . ";" . $obj1['results'][$i]['place_id'] . $obj2['result']['address_components']['postal_code'] . "<br>";
};
?>
The idea is you get the information you want form $obj1 and $obj2 based on the results of the 2 queries.

Check URL parameter in php

I want to check a parameter in a url variable, for example:
$var2join = 'en'; // can be anything else
$url = 'https://www.example.com/hello/parameter2';
$url2 = 'https://www.example.com/hello2';
$url3 = 'https://www.example.com/en/hey';
first check if the $url vars have the $var2join into $var as parameter if have it, leave it intact and if not add it.
Wanted output:
$url = 'https://www.example.com/en/hello/parameter2';
$url2 = 'https://www.example.com/en/hello2';
$url3 = 'https://www.example.com/en/hey';
I tried:
$url = (!preg_match('~^/[a-z]{2}(?:/|$)~', $location)) ? '/' . $var2join . $url : $url;
Use parse_url(), it is specifically for analysing URLs and their various elements.
Note this code assumes your parameters are path segments, as you describe above. If you ever use query string parameters like ?foo=bar, you'd need to adjust.
$var2join = 'en';
$url = 'https://www.example.com/hello/parameter2';
// Split URL into each of its parts
$url_parts = parse_url($url);
// Create an array of all the path parts, which correspond to
// parameters in your scheme
$params = explode('/', $url_parts['path']);
// Check if your var is in there
if (!in_array($var2join, $params)) {
// If not, reconstruct the same URL, but with your var inserted.
// NOTE this assumes a pretty simple URL, you'll need to adjust if
// you ever have other elements like port number, u/p, query strings
// etc. #Jason-rush links to something in the PHP docs to handle
// such cases.
$url = $url_parts['scheme'] . '://' . $url_parts['host'] . '/' . $var2join . $url_parts['path'];
}
// Check your result - https://www.example.com/en/hello/parameter2
echo $url;
This is a little generic function with some support code to give you some ideas... Not very elegant but it works.
<?php
$base_url = 'https://www.example.com/';
$var2join = 'en'; // can be anything else
$url = $base_url . 'hello/parameter2';
$url2 = $base_url . 'hello2';
$url3 = $base_url . 'en/hey';
$url4 = $base_url . 'hey/this/is/longer';
echo prepend_path_to_url($base_url, $url, $var2join);
echo '<br>';
echo prepend_path_to_url($base_url, $url2, $var2join);
echo '<br>';
echo prepend_path_to_url($base_url, $url3, $var2join);
echo '<br>';
echo prepend_path_to_url($base_url, $url4, $var2join);
echo '<br>';
/**
* Prepend a Path to the url
*
* #param $base_url
* #param $url
* #param $path_to_join
* #return string
*/
function prepend_path_to_url($base_url, $url, $path_to_join) {
// Does the path_to_join exist in the url
if (strpos($url, $path_to_join) === FALSE) {
$url_request = str_replace($base_url,'',$url);
$url = $base_url . $path_to_join . '/'. $url_request;
}
return $url;
}

Looping through CSV and parsing a JSON query using each result

So despite hours of fiddling I cannot understand why my JSON query only returns a result for the last line in the CSV/TXT files I am trying to parse.
Here is the code:
//Enter API Key Here
$api_key = 'AIzaSyB9Dq3w1HCxkS5qyELI_pZuTmdK8itOBHo';
$origin = 'RG12 1AA';
$output_type = 'json'; //xml or json
$csv_location = 'http://www.naturedock.co.uk/postcodes.csv';
//Do not edit
$base_url = 'https://maps.googleapis.com/maps/api/directions/';
$origin_url = '?origin=';
$destination_url = '&destination=';
$end_url = '&sensor=false&key=';
$page = join("",file("$csv_location"));
$kw = explode("\n", $page);
for($i=0;$i<count($kw);$i++){
$destination = $kw[$i];
echo $destination;
$raw_url = $base_url . $output_type . $origin_url . $origin . $destination_url . $destination . $end_url . $api_key;
$request_url = str_replace(' ', '', $raw_url);
$getJson = file_get_contents($request_url);
$routes = json_decode($getJson);
$result = $routes->routes[0]->legs[0]->distance->value;
echo $result . '<br>';
}
The result I get looks like this:
Distance by Post Code Generator v0.1 by Phil Hughes
RG12 0GA
RG12 0GB
RG12 0GC
RG12 0GD4066
Where the '4066' is the correct variable for RG12 0GD postcode but none of the others return results as you can see.
Please help.
Your
join("",file("$csv_location"));
concatenated all lines feom the file to a single line without separator. The following explode() sees no newlines any more. So you are working on one line only. count($kw) always evaluates to 1 and your loop runs only one time.

Max CDN purge through API

I am trying to purge a file through the MaxCDN API but it's not working. Here's the code I'm using. The print_r doesn't return any result.
function purge() {
date_default_timezone_set('America/Los_Angeles');
$date = date('c');
$apiid = 'myapiid';
$apikey = 'myapi';
$auth_key = hash('sha256', $date.':'.$apikey.':purge');
$url = 'http://softsailor.alexdumitru.netdna-cdn.com/wp-content/themes/ss3/includes/sprite.jpg';
if (!class_exists('IXR_Client')) {
require_once (ABSPATH . WPINC . '/class-IXR.php');
}
$client = new IXR_Client('api.netdna.com','/xmlrpc/cache',80);
$client->timeout = 30;
$client->query('cache.purge', $apiid, $auth_string, $date, $url);
print_r($client->getResponse());
}
I turned debug on and I'm getting the following error
Something went wrong - -32300 : transport error - HTTP status code was not 200
Hey Alex. I work at MaxCDN and here is a code example that I took from our Wiki:
<?php
date_default_timezone_set('America/Los_Angeles');
include("lib/xmlrpc.inc");
$cur = date('c');
$apiKey = 'api-key';
$apiUserId = 'api-user-id';
$namespace = 'cache';
$method = 'purge';
$authString = hash('sha256', $cur . ':' . $apiKey . ':' . $method);
// this is the url to purge
$url= 'http://static.jdorfman.netdna-cdn.com/static/images/frugal-it-logo.png';
$f=new xmlrpcmsg("$namespace.$method", array(php_xmlrpc_encode($apiUserId),
php_xmlrpc_encode($authString), php_xmlrpc_encode($cur),
php_xmlrpc_encode($url)));
$c=new xmlrpc_client("/xmlrpc/cache", "api.netdna.com", 80,'http11');
$r=&$c->send($f);
print_r($r);
?>
If you have any other questions or concerns feel free to get in contact with me: jdorfman at maxcdn dot com
jdorfman's example dumps the entire raw response but if you are like me you want to get it into data objects using php
Here are some helpful tips:
$r->serialize() to access just the raw XML response
to convert to JSON use this:
$xml = simplexml_load_string($r->serialize());
echo json_encode($xml);

Categories