Skip to content

Instantly share code, notes, and snippets.

@asaokamei
Created April 8, 2019 08:38
Show Gist options
  • Save asaokamei/acf4e48cbc4652622460880ba1b64f33 to your computer and use it in GitHub Desktop.
Save asaokamei/acf4e48cbc4652622460880ba1b64f33 to your computer and use it in GitHub Desktop.
Control Ajax and/or CORS access sample class.
<?php
namespace Study\StudyCore\Utils;
class ServerAjaxControl
{
const AJAX_HEADER_TOKEN = 'HTTP_X_REQUESTED_WITH';
const AJAX_HEADER_VALUE = 'XMLHttpRequest';
const HTTP_ORIGIN_TOKEN = 'HTTP_ORIGIN';
const HEADER_ALLOW_ORIGIN = 'Access-Control-Allow-Origin';
const REQUEST_METHOD = 'REQUEST_METHOD';
const PREFLIGHT_METHOD = 'OPTIONS';
/**
* @var array
*/
private $server;
/**
* @param array $server
*/
public function __construct(array $server)
{
$this->server = $server;
}
/**
* @return bool
*/
public function isAjax()
{
if (!isset($this->server[self::AJAX_HEADER_TOKEN])) return false;
if ($this->server[self::AJAX_HEADER_TOKEN] !== self::AJAX_HEADER_VALUE) return false;
return true;
}
/**
* @return bool
*/
public function isCors()
{
return isset($this->server[self::HTTP_ORIGIN_TOKEN]);
}
/**
* @return bool
*/
public function isPreFlight()
{
if (!isset($this->server[self::REQUEST_METHOD])) return false;
return $this->server[self::REQUEST_METHOD] === self::PREFLIGHT_METHOD;
}
/**
* list URLs in $allowedOrigins that are allowed to access.
* returns true if CORS is from allowed origins.
* returns false otherwise.
*
* @param string[] $allowedOrigins
* @return bool
*/
public function headerAllowOrigins(array $allowedOrigins)
{
$origin = $this->server[self::HTTP_ORIGIN_TOKEN];
trim($origin, ' /');
if (in_array($origin, $allowedOrigins)) {
$this->headerAllowOrigin($origin);
return true;
}
return false;
}
/**
* @param string $source
*/
public function headerAllowOrigin($source)
{
header(self::HEADER_ALLOW_ORIGIN . ": {$source}", false);
}
/**
* a sample access code to allow AJAX, or CORS from $allowedOrigins.
* if returened false, maybe return responce with 403 error code.
* if returned true, continue process and return JSON response.
*
* @param array $allowedOrigins
* @return bool
*/
public function allowAjaxOrCorsFromOrigins(array $allowedOrigins)
{
if ($this->isAjax()) {
return true;
}
if (!$this->isCors()) {
return false;
}
if ($this->headerAllowOrigins($allowedOrigins)) {
return false;
}
if ($this->isPreFlight()) {
exit;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment