khanat-opennel-code/code/web/private_php/ams/autoload/rest_api.php

75 lines
2.7 KiB
PHP
Raw Normal View History

2014-08-04 08:35:11 +00:00
<?php
/**
* REST API class
*
* Request for the given url using cURL
* and send the AccessToken for authentication
* to make public access for the user.
2014-08-04 08:35:11 +00:00
*
* @author Shubham Meena, mentored by Matthew Lagoe
*/
class Rest_Api {
/**
* Makes a request using cURL with authentication headers , data to post and returns the response.
2014-08-04 08:35:11 +00:00
*
* @param $url where request is to be sent
* @param $applicationKey user generated key
* @param $host host for the website
* @param $data data to send using POST request
*
* @return $response URL response.
2014-08-04 08:35:11 +00:00
*/
public function request( $url , $applicationKey, $host , $data )
2014-08-04 08:35:11 +00:00
{
// Check the referer is the host website
$referer = $_SERVER['HTTP_REFERER'];
$referer_parse = parse_url( $referer );
if ( $referer_parse['host'] == $host ) {
// Initialize the cURL session with the request URL
$session = curl_init( $url );
// Tell cURL to return the request data
curl_setopt( $session, CURLOPT_RETURNTRANSFER, true );
// Set the HTTP request authentication headers
$headers = array(
'AppKey: ' . $applicationKey,
'Timestamp: ' . date( 'Ymd H:i:s', time() ),
'Accept: application/json',
'Content-Type: application/json'
2014-08-04 08:35:11 +00:00
);
curl_setopt( $session, CURLOPT_HTTPHEADER, $headers );
curl_setopt( $session, CURLOPT_CUSTOMREQUEST, "POST" );
curl_setopt( $session, CURLOPT_POSTFIELDS, $data );
2014-08-04 08:35:11 +00:00
// Execute cURL on the session handle
$response = curl_exec( $session );
2014-08-13 07:27:30 +00:00
if ( curl_errno( $session ) ) {
// if request is not sent
die( 'Couldn\'t send request: ' . curl_error( $session ) );
} else {
// check the HTTP status code of the request
$resultStatus = curl_getinfo( $session, CURLINFO_HTTP_CODE );
if ( $resultStatus == 200 ) {
// everything went fine return response
return $response;
} else {
// the request did not complete as expected. common errors are 4xx
// (not found, bad request, etc.) and 5xx (usually concerning
// errors/exceptions in the remote script execution)
die( 'Request failed: HTTP status code: ' . $resultStatus );
}
}
curl_close( $session );
2014-08-04 08:35:11 +00:00
}
else {
return null;
}
}
}