Skip to content

Commit

Permalink
feat: add CORS headers to current request
Browse files Browse the repository at this point in the history
  • Loading branch information
fakeheal committed Jun 15, 2023
1 parent 8981ed8 commit 15af515
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,21 +27,25 @@ composer require fakeheal/cors-anywhere
```php
<?php

use Fakeheal\CorsAnywhere\Exceptions\NoValidUrlProvidedException;
use Fakeheal\CorsAnywhere\Exceptions\CorsAnywhereException;
use Fakeheal\CorsAnywhere\Proxy;

// ...

// allowed hosts passed down to the Proxy class
try {
$server = new Proxy([
// allowed hosts to proxy to
'rescuetime.com',
'google.com'
], [
// allowed headers
'Content-Type',
'Accepts'
]);

// call handle that... handles everything
$server->handle();
} catch (NoValidUrlProvidedException $e) {
} catch (CorsAnywhereException $e) {
die($e->getMessage()); // or die trying
}
```
Expand Down
17 changes: 15 additions & 2 deletions src/Proxy.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
class Proxy
{
private const METHOD_GET = 'GET';
private const METHOD_OPTIONS = 'OPTIONS';
private const PARAM_URL = 'url';

/**
Expand All @@ -34,7 +35,7 @@ public function __construct(
private ?Client $client = null
) {
if (is_null($this->request)) {
$this->request = new Request($_GET, $_POST, [], [], [], $_SERVER);
$this->request = Request::createFromGlobals();
}

if (is_null($this->response)) {
Expand Down Expand Up @@ -91,7 +92,19 @@ private function redirect(): Proxy
*/
public function handle(): void
{
$this->redirect()->response->send();
if ($this->request->server->get('HTTP_ORIGIN')) {
$this->response->headers->set('Access-Control-Allow-Origin', $this->request->server->get('HTTP_ORIGIN'));
$this->response->headers->set('Access-Control-Allow-Credentials', true);
}

if ($this->request->getMethod() === self::METHOD_OPTIONS) {
$this->response->headers->set('Access-Control-Allow-Methods', ['GET', 'POST', 'OPTIONS']);
$this->response->headers->set('Access-Control-Allow-Headers', $this->allowedHeaders);
} else {
$this->redirect();
}

$this->response->send();
}

/**
Expand Down

0 comments on commit 15af515

Please sign in to comment.