Skip to content

Instantly share code, notes, and snippets.

@ViskoB
Last active August 29, 2015 14:20
Show Gist options
  • Save ViskoB/111b8d08c1ee430d0185 to your computer and use it in GitHub Desktop.
Save ViskoB/111b8d08c1ee430d0185 to your computer and use it in GitHub Desktop.
gw2api-tools
<?php
/**
* request.inc.php
* created: 05.06.13 by codemasher (smiley.1438) https://github.com/codemasher/gw2api-tools/blob/master/inc/request.inc.php
* modified: 09.05.15 by moturdrn (Moturdrn.2837) for API v2 Keys
*/
/**
* A small function to request&receive data from the GW2 API.
* Doesn't use CURL and doesn't depend on allow_url_fopen.
*
* @param string $request
* @param string $api_key
*
* @return array|bool
*/
/**
* Example 1 - v1 Endpoint
* $result = gw2_api_request('/v1/wvw/matches.json');
*
* Example 2 - v2 Endpoint
* $result = gw2_api_request('/v2/quaggans');
*
* Example 3 - v2 Endpoint w/ Authentication
* $result = gw2_api_request('/v2/account', 'XXXX-XXXX-XXX-XXXXXXXXX-XXXXX');
*/
function gw2_api_request($request, $api_key = ""){
// Check API Key against pattern
if($api_key != ""){
$pattern="/^[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{20}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}$/";
if(!preg_match($pattern, $api_key)) return false;
}
$url = parse_url('https://api.guildwars2.com'.$request);
// open the socket
if(!$fp = @fsockopen('ssl://'.$url['host'], 443, $errno, $errstr, 5)){
return false;
// you may want improved error handling...
# return 'connection error: '.$errno.', '.$errstr;
}
// prepare the request header...
$nl = "\r\n";
$header = 'GET '.$url['path'].(isset($url['query']) ? '?'.$url['query'] : '').' HTTP/1.1'.$nl.'Host: '.$url['host'].$nl;
$header .= !empty($api_key) ? 'Authorization: Bearer '.$api_key.$nl : '';
$header .= 'Connection: Close'.$nl.$nl;
// ...and send it.
fwrite($fp, $header);
stream_set_timeout($fp, 5);
// receive the response
$response = '';
do{
if(strlen($in = fread($fp,1024))==0){
break;
}
$response.= $in;
}
while(true);
// now the nasty stuff... explode the response at the newlines
$response = explode($nl, $response);
// you may want some advanced error handling over here, too
if(isset($response[0]) && $response[0] == 'HTTP/1.1 200 OK'){
// the response is non chunked, so we can assume the data is contained in the last line
$response = json_decode($response[count($response)-1], true);
return $response;
}
return false;
}
?>
@ViskoB
Copy link
Author

ViskoB commented May 11, 2015

Cheers, added the cleaner $header addition, and basic check for the API key pattern based on what I've seen so far.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment