Skip to content

PHP Examples

image

For PHP developers we recommend using your frameworks HTTP library or Guzzle. We also have a PHP SDK which can be installed via composer. We will provide examples below using the standard curl library.

Authentication

Note, this sample does not include error handling. You will need to add that yourself.

$token = 'YOUR_API_TOKEN_HERE';
$secret = 'YOUR_API_SECRET_HERE';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://carapi.app/api/auth/login');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Accept: text/plain',
    'Content-type: application/json',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, sprintf('{"api_token": "%s", "api_secret": "%s"}', $token, $secret));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$jwt = curl_exec($ch);
curl_close($ch);

Making a request

$endpoint = 'models';
$query['year'] = '2019';

$ch = curl_init('https://carapi.app/api/' . $endpoint . '?' . http_build_query($query));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Accept: application/json',
    'Authorization: Bearer ' . $jwt,
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$results = json_decode($result);

Caching JWTs

It's important to cache your JWT, so you don't have to authenticate on each request. We'll provide a basic cache example using the file system, but we recommend using your frameworks caching library or something like symfony/cache or cake/cache.

Secure your JWT

Your JWT should be kept as secret and secure as your API Token and API Secret.

After creating your JWT:

$filePath = '/some/path/not/readable/by/browsers/carapi_jwt.txt';
file_put_contents($filePath, $jwt);

On future requests:

$jwt = file_get_contents($filePath);
if (empty($jwt)) {
    // handle error
}

$pieces = explode('.', $jwt);
if (count($pieces) !== 3) {
    // handle error
}

$payload = base64_decode($pieces[1]);
$data = json_decode($payload); // handle json decode exceptions

if ((new DateTime('now', new DateTimeZone('America/New_York')))->getTimestamp() > $data->exp) {
    // it's time to renew your JWT and write it to cache
}

// now you can make your request!