Taimur
Taimur

Reputation: 3241

How to easily send a POST request and receive + interpret JSON using PHP

I'm using the Foursquare API and I need to make a request to their server in order to receive an access token in JSON form (https://developer.foursquare.com/overview/auth). How do I do this using PHP?

I haven't found any definitive tutorials online, which is why I'm asking here. I've seen some stuff to do with cURL which I don't really understand, so is there any easy way to do this? I have done it before using AJAX and it was very self explanatory, but it seems very complicated in PHP, far more than it needs to be by the looks of it :(

Can anyone help? Thanks

Upvotes: 1

Views: 437

Answers (2)

Tivie
Tivie

Reputation: 18923

Well, following the link you provided, try this:

Script in the redirect link(YOUR_REGISTERED_REDIRECT_URI)

if(isset($_GET['code']))
{
    $code = $_GET['code'];
    $url = "https://foursquare.com/oauth2/access_token?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=authorization_code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI&code=$code";

    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_POST);

    $json = curl_exec($ch);

    var_dump($json);
}

NOTE: After reading the tutorial you provided, I didn't see any reference to POST request, only request, so you can try this (instead of cURL)

$json = file_get_contents($url);

If it's a simple GET request, then file_get_contents will probably work.

Upvotes: 1

Johndave Decano
Johndave Decano

Reputation: 2113

<?php

# url_get_contents function by Andy Langton: http://andylangton.co.uk/

function url_get_contents($url,$useragent='cURL',$headers=false,$follow_redirects=false,$debug=false) {

# initialise the CURL library
$ch = curl_init();

# specify the URL to be retrieved
curl_setopt($ch, CURLOPT_URL,$url);

# we want to get the contents of the URL and store it in a variable
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);

# specify the useragent: this is a required courtesy to site owners
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);

# ignore SSL errors
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

# return headers as requested
if ($headers==true){
curl_setopt($ch, CURLOPT_HEADER,1);
}

# only return headers
if ($headers=='headers only') {
curl_setopt($ch, CURLOPT_NOBODY ,1);
}

# follow redirects - note this is disabled by default in most PHP installs from 4.4.4 up
if ($follow_redirects==true) {
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
}

# if debugging, return an array with CURL's debug info and the URL contents
if ($debug==true) {
$result['contents']=curl_exec($ch);
$result['info']=curl_getinfo($ch);
}

# otherwise just return the contents as a variable
else $result=curl_exec($ch);

# free resources
curl_close($ch);

# send back the data
return $result;
}

?>

Upvotes: 1

Related Questions