PSR-7 / PSR-15 middleware that determines the client's remote TCP port (from the REMOTE_PORT server param) and stores it as a ServerRequest attribute named remotePort.
Works with:
- Slim 4+ (PSR-15 single-pass)
- Slim 3 (legacy double-pass) – still supported for backwards compatibility
- Any PSR-15 compatible framework (Mezzio, etc.)
- PHP >= 8.0
- psr/http-message ^1.0 || ^2.0
- psr/http-server-middleware ^1.0
composer require luisinder/remote-port-middlewareOn each request the middleware inspects $request->getServerParams()['REMOTE_PORT'] (if present) and attaches it to the request as remotePort (integer or null if missing).
use Slim\Factory\AppFactory;
use Luisinder\Middleware\RemotePort;
require __DIR__ . '/vendor/autoload.php';
$app = AppFactory::create();
$app->add(RemotePort::class); // or new RemotePort()
$app->get('/', function ($request, $response) {
$remotePort = $request->getAttribute('remotePort');
$response->getBody()->write('Remote port: ' . ($remotePort ?? 'unknown'));
return $response;
});
$app->run();If you prefer adding via DI container (e.g. using PHP-DI):
$container->set(RemotePort::class, function() { return new RemotePort(); });
$app->add(RemotePort::class);$app->add(new Luisinder\Middleware\RemotePort());
$app->get('/', function ($request, $response) {
$remotePort = $request->getAttribute('remotePort');
return $response->write('Remote port: ' . ($remotePort ?? 'unknown'));
});The attribute key is remotePort. Example:
$remotePort = $request->getAttribute('remotePort'); // int|nullIf REMOTE_PORT is missing the attribute value will be null.
You can simulate a request by constructing a PSR-7 ServerRequest with a custom server params array:
$request = $request->withServerParams(['REMOTE_PORT' => 54321]);PRs and issues are welcome. Please include tests where possible.
BSD-3-Clause. See the LICENSE file for details.