Skip to content

Instantly share code, notes, and snippets.

@mtvbrianking
Last active April 11, 2023 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mtvbrianking/afae108e3ca24118a49af87b0f987230 to your computer and use it in GitHub Desktop.
Save mtvbrianking/afae108e3ca24118a49af87b0f987230 to your computer and use it in GitHub Desktop.
PHP Forwarding Proxy

Authentication

.env

  ...
+ PROXY_AUTH_KEY=Bj5pnZEX6DkcG6Nz6AjDUT1bvcGRVhRaXDuKDX9CjsEs2

Approach #1

routes/proxy.php

use Zounar\PHPProxy\Proxy;

/*
 * Dedicate a routes file to 'routes/proxy.php'
 * Register it with prexix 'proxy' --> http://localhost:8000/proxy
 */
Proxy::$AUTH_KEY = getenv('PROXY_AUTH_KEY');

Proxy::run();

die();

Approach #2

routes/web.php routes/api.php

use Zounar\PHPProxy\Proxy;

/**
 * This approach isn't recommended since 
 * the web, api route groups already have various middlewares attached to them.
 */
Route::any('/proxy', function () {
    Proxy::$AUTH_KEY = getenv('PROXY_AUTH_KEY');

    Proxy::run();

    die();
});

Testing

curl --location --request GET 'http://localhost:8000/proxy' \
--header 'Proxy-Auth: Bj5pnZEX6DkcG6Nz6AjDUT1bvcGRVhRaXDuKDX9CjsEs2' \
--header 'Proxy-Target-URL: https://jsonplaceholder.typicode.com/todos/1'
@mtvbrianking
Copy link
Author

You should setup CORS on your proxy

  • Restrict origins
  • Allow all request headers
  • Expose all response headers

@mtvbrianking
Copy link
Author

Run as a standalone script

php -S localhost:8000 -t Proxy.php

@mtvbrianking
Copy link
Author

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