PHP code example of chubbyphp / chubbyphp-trusted-proxy
1. Go to this page and download the library: Download chubbyphp/chubbyphp-trusted-proxy library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
chubbyphp / chubbyphp-trusted-proxy example snippets
declare(strict_types=1);
namespace App;
use Chubbyphp\TrustedProxy\ForwardedResolver;
use Chubbyphp\TrustedProxy\TrustedProxyAttributes;
use Chubbyphp\TrustedProxy\TrustedProxyMiddleware;
use Psr\Http\Message\ServerRequestInterface;
$app = ...;
// the ips / cidrs of the proxies: the entries of X-Forwarded-For get walked from the right, the first one not within
// the ranges is the client (robust against a varying number of hops)
$app->add(new TrustedProxyMiddleware(new ForwardedResolver(['10.0.0.0/8', '::1'])));
$handler = static function (ServerRequestInterface $request) {
// each one ?string: the unresolved ones are null
$clientIp = $request->getAttribute(TrustedProxyAttributes::CLIENT_IP); // 'clientIp'
$scheme = $request->getAttribute(TrustedProxyAttributes::SCHEME); // 'scheme'
$host = $request->getAttribute(TrustedProxyAttributes::HOST); // 'host'
...
};
use Chubbyphp\TrustedProxy\ForwardedHeaders;
use Chubbyphp\TrustedProxy\ForwardedResolver;
new ForwardedResolver(['10.0.0.0/8'], new ForwardedHeaders(for: 'X-Real-IP', proto: 'X-Forwarded-Proto', host: null));
declare(strict_types=1);
namespace App;
use Chubbyphp\Laminas\Config\Config;
use Chubbyphp\Laminas\Config\ContainerFactory;
use Chubbyphp\TrustedProxy\ForwardedResolverInterface;
use Chubbyphp\TrustedProxy\ServiceFactory\ForwardedResolverFactory;
use Chubbyphp\TrustedProxy\ServiceFactory\TrustedProxyMiddlewareFactory;
use Chubbyphp\TrustedProxy\TrustedProxyMiddleware;
$container = (new ContainerFactory())(new Config([
'chubbyphp' => [
'trustedProxy' => [
'trustedProxies' => ['10.0.0.0/8', '::1'],
// 'headers' => ['for' => 'X-Forwarded-For', 'proto' => 'X-Forwarded-Proto', 'host' => 'X-Forwarded-Host'],
// '