
Everything You Should Know about PHP Array Redactor
Everything you should know about PHP array Redactor
The Array Redactor package is a PHP library developed by Mark Townsend under MIT license to redact array values by their keys. The readactor call returns the array version of the JSON string. Here is an example to understand how this package works.
Installation
Install via composer:
composer require mtownsend/array-redactor
This package is designed to work with any PHP 5.6+ application but has special Facade support for Laravel.
Registering the service provider (Laravel users)
For Laravel 5.4 and lower, add the following line to your config/app.php:
/* * Package Service Providers... */ Mtownsend\ArrayRedactor\Providers\ArrayRedactorServiceProvider::class,
For Laravel 5.5 and greater, the package will auto-register the provider for you.
An example array, maybe a request being made to/from an API application you wish to log in your database. You can quick start the package by running the following.
$login = [ 'email' => 'cyblance@gmail.com', 'password' => 'cyblance123', 'data' => [ 'session_id' => 'z481jf0an4kasnc8a84aj831' ], ]; $redactor = (new ArrayRedactor($login, ['password', 'session_id']))->redact(); // $redactor will return: [ 'email' => 'cyblance@gmail.com', 'password' => '[REDACTED]', 'data' => [ 'session_id' => '[REDACTED]' ], ];
You can use the package in advanced to pass a valid JSON string instead of an array of content:
$json = json_encode([ 'email' => 'john_doe@domain.com', 'password' => 'secret123', 'data' => [ 'session_id' => 'z481jf0an4kasnc8a84aj831' ], ]); $redactor = (new ArrayRedactor($json, ['password', 'session_id']))->redact();
You will receive your content back as JSON instead of an array.
You can this package for any PHP project, If you’re using lumen it will provide the service provider.
Error handling
To handle the error while passing the data you use or throw an ArrayRedactorException.
try { $redactor = (new ArrayRedactor('i am an invalid argument', ['password']))->redact(); } catch (\Mtownsend\ArrayRedactor\Exceptions\ArrayRedactorException $exception) { // do something... }
Why do you need or use this package?
Have you ever built or interacted with an API and needed to log all outgoing and incoming calls? Chances are that somewhere in that process is an authentication, either by an app or on behalf of a user. Logs are useful for debugging, but storing sensitive information such as passwords or API keys is not something you want to have in your logs for anyone to see. The usage goes beyond just this example, but that is what prompted me to create the ArrayRedactor package.