
Product
Socket Zero Introduces Automated Remediation PRs
Put vulnerability remediation on autopilot with automated security patches and intelligent dependency upgrades across your GitHub repositories.
sindaniel/raygun4php
Advanced tools
Raygun.com client for sending errors and exceptions automatically.
Raygun.com provider for PHP 7.2+
See v1.8 documentation for PHP v5.3+ support
Raygun4PHP uses Guzzle to handle the transmission of data to the Raygun API. Having cURL installed is recommended, but is not required, as Guzzle will use a PHP stream wrapper if cURL is not installed.
Composer is a package management tool for PHP which automatically fetches dependencies and also supports autoloading - this is a low-impact way to get Raygun4PHP into your site.
1. If you use a *nix environment, follow the instructions to install Composer. Windows users can run this installer to automatically add it to the Path.
2. Inside your project's root directory create a composer.json file, containing:
{
"require": {
"mindscape/raygun4php": "^2.0"
}
}
3. From your shell run php composer.phar install (*nix) or composer install (Windows). This will download Raygun4PHP and create the appropriate autoload data.
4. Then in a PHP file just add:
require_once 'vendor/autoload.php';
and the library will be imported ready for use.
You can automatically send both PHP errors and object-oriented exceptions to Raygun. The RaygunClient requires an HTTP transport (e.g. Guzzle or other PSR-7 compatible interface).
There are Guzzle-based asynchronous and synchronous transport classes in the provider, or you can use your own.
This is an example of basic usage for asynchronous sending of errors and exceptions:
<?php
namespace {
require_once 'vendor/autoload.php';
use GuzzleHttp\Client;
use Raygun4php\RaygunClient;
use Raygun4php\Transports\GuzzleAsync;
$httpClient = new Client([
'base_uri' => 'https://api.raygun.com',
'timeout' => 2.0,
'headers' => [
'X-ApiKey' => 'INSERT_API_KEY_HERE'
]
]);
$transport = new GuzzleAsync($httpClient);
$raygunClient = new RaygunClient($transport);
set_error_handler(function($errno, $errstr, $errfile, $errline) use ($raygunClient) {
$raygunClient->SendError($errno, $errstr, $errfile, $errline);
});
set_exception_handler(function($exception) use ($raygunClient) {
$raygunClient->SendException($exception);
});
register_shutdown_function(function() use ($raygunClient) {
$lastError = error_get_last();
if (!is_null($lastError)) {
[$type, $message, $file, $line] = $lastError;
$raygunClient->SendError($type, $message, $file, $line);
}
});
register_shutdown_function([$transport, 'wait']);
}
For synchronous transport, use the snippet above but replace use Raygun4php\Transports\GuzzleAsync; with:
use Raygun4php\Transports\GuzzleSync;
And replace $transport = new GuzzleAsync($httpClient); with:
$transport = new GuzzleSync($httpClient);
Remove this line:
register_shutdown_function([$transport, 'wait']);
Note that if you are placing it inside a file with a namespace of your choosing, the above code should be declared to be within the global namespace (thus the namespace { } is required). You will also need whichever require statement as above (autoload or manual) before the $raygunClient instantiation.
Copy your application's API key from the Raygun app, and paste it into the X-ApiKey header field of the HTTP client.
If the handlers reside in their own file, just import it in every file where you'd like exceptions and errors to be sent, and they will be delivered to Raygun.
A URL can be set as the proxy property on the HTTP Client:
// ...
$httpClient = new Client([
'base_uri' => 'https://api.raygun.com',
'proxy' => 'http://someproxy:8080',
'headers' => [
'X-ApiKey' => 'INSERT_API_KEY_HERE'
]
]);
See Guzzle's proxy documentation for more options.
We recommend using a logger which is compatible with the PSR-3 LoggerInterface (e.g. Monolog).
Expanding on the Asynchronous transport example above, you can set a logger to be used by the transport like so:
// ...
use Monolog\Handler\FirePHPHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
// ...
$logger = new Logger('my_logger');
$logger->pushHandler(new StreamHandler(__DIR__ . '/debug.log'));
$logger->pushHandler(new FirePHPHandler());
// Create $httpClient ...
$transport = new GuzzleAsync($httpClient);
$transport->setLogger($logger);
$raygunClient = new RaygunClient($transport);
// Set error handlers ...
You can transmit the version number of your PHP project along with the message by calling SetVersion() on your RaygunClient after it is instantiated - this is optional but recommended as the version number is considered to be first-class data for a message.
$raygunClient = new RaygunClient($transport);
$raygunClient->SetVersion('1.0.0.0');
Tags can be added to error data to provide extra information and to help filtering errors within Raygun.
They are provided as an array of strings or numbers passed as the 5th argument to the SendError function and as the 2nd argument to the SendException function.
The declaration of the exception and error handlers for adding tags to each payload could look something like this:
<?php
// ...
$raygunClient = new RaygunClient($transport);
$tags = ['staging-environment', 'machine-4'];
set_error_handler(function($errno, $errstr, $errfile, $errline) use ($raygunClient, $tags) {
$raygunClient->SendError($errno, $errstr, $errfile, $errline, $tags);
});
set_exception_handler(function($exception) use ($raygunClient, $tags) {
$raygunClient->SendException($exception, $tags);
});
register_shutdown_function(function() use ($raygunClient, $tags) {
$lastError = error_get_last();
if (!is_null($lastError)) {
[$type, $message, $file, $line] = $lastError;
$raygunClient->SendError($type, $message, $file, $line, $tags);
}
});
// ...
You can add tags when manually sending a handled exception like so:
try {
// Do something questionable...
} catch(Exception $exception) {
$raygunClient->SendException($exception, ['handled-exception']);
}
You can call $raygunClient->SetUser, passing in some or all of the following data, which will be used to provide an affected user count and reports:
$raygunClient->SetUser($user = 'email_or_unique_identifier', $firstName = 'Example', $fullName = 'Example User', $emailAddress = 'test@example.com', $isAnonymous = false, $uuid = 'abc123');
$user should be a unique identifier which is used to identify your users. If you set this to their email address, be sure to also set the $email parameter too.
This feature and values are optional if you wish to disable it for privacy concerns. To do so, pass true in as the second parameter to the RaygunClient constructor.
// Disable user tracking:
$raygunClient = new RaygunClient($transport, true);
Note that this data is stored as cookies. If you do not call SetUser the default is to store a random UUID to represent the user.
This feature can be used in CLI mode by calling SetUser() at the start of your session.
Control of how error instances are grouped together can be achieved by passing a callback to the SetGroupingKey method on the client. If the callback returns a string, ideally 100 characters or less, errors matching that key will be grouped together, overriding the default automatic grouping. If the callback returns a non-string value then that error will be grouped automatically.
$raygunClient->SetGroupingKey(function($payload, $stackTrace) {
// Inspect the above parameters and return a hash from the properties ...
return $payload->Details->Error->Message; // Naive message-based grouping only
});
Some error data will be too sensitive to transmit to an external service, such as credit card details or passwords. Since this data is very application specific, Raygun doesn't filter out anything by default. You can configure to either replace or otherwise transform specific values based on their keys. These transformations apply to form data ($_POST), custom user data, HTTP headers, and environment data ($_SERVER). It does not filter the URL or its $_GET parameters, or custom message strings. Since Raygun doesn't log method arguments in stack traces, those don't need filtering. All key comparisons are case insensitive.
$raygunClient->setFilterParams([
'password' => true,
'creditcardnumber' => true,
'ccv' => true,
'php_auth_pw' => true, // filters basic auth from $_SERVER
]);
// Example input: ['Username' => 'myuser','Password' => 'secret']
// Example output: ['Username' => 'myuser','Password' => '[filtered]']
You can also define keys as regular expressions:
$raygunClient->setFilterParams([
'/^credit/i' => true,
]);
// Example input: ['CreditCardNumber' => '4111111111111111','CreditCardCcv' => '123']
// Example output: ['CreditCardNumber' => '[filtered]','CreditCardCcv' => '[filtered]']
In case you want to retain some hints on the data rather than removing it completely, you can also apply custom transformations through PHP's anonymous functions. The following example truncates all keys starting with "address".
$raygunClient->setFilterParams([
'Email' => function($key, $val) {return substr($val, 0, 5) . '...';}
]);
// Example input: ['Email' => 'test@test.com']
// Example output: ['Email' => 'test@...']
If you want to ensure all form submission data is filtered out irrespective of field names for situations where there are a lot of forms that might request private information, you can do that too. The field names will still be transmitted, but the values will be filtered out.
$raygunClient->setFilterAllFormValues(true);
Note that when any filters are defined, the Raygun error will no longer contain the raw HTTP data, since there's no effective way to filter it.
Cookies are used for the user tracking functionality of the Raygun4PHP provider. In version 1.8 of the provider, the options passed to the setcookie method can now be customized to your needs.
$raygunClient->SetCookieOptions([
'expire' => 2592000, // 30 * 24 * 60 * 60
'path' => '/',
'domain' => '',
'secure' => false,
'httponly' => false
]);
As mentioned above, you can specify a logger to the HTTP transport:
$transport->setLogger($logger);
This will log out exceptions occurring while transmitting data to Raygun. Create an issue or contact us if you continue to have problems.
If, when running a PHP script from the command line on *nix operating systems, you receive a '400 Bad Request' error (in your debug log), check to see if you have any LESS_TERMCAP environment variables set. These are not compatible with the current version of Raygun4PHP. As a workaround, unset these variables before your script runs, then reset them afterwards.
If you are using the setup as described above errors will be sent to Raygun regardless of any lines prepended with an error control operator (the @ symbol). To stop these errors from being sent to Raygun you can call PHP's error_reporting method which return 0 if the triggered error was preceded by an @ symbol.
Error handler example:
function ($errno, $errstr, $errfile, $errline) use ($raygunClient) {
if (error_reporting() !== 0) {
$raygunClient->SendError($errno, $errstr, $errfile, $errline);
}
}
See the Error Control Operators section on PHP.net for more information.
toJsonRemoveUnicodeSequences() and removeNullBytes() methods from the RaygunClient class - use toJson() instead--dev option for composer installations as it's now deprecatedFAQs
Raygun.com client for sending errors and exceptions automatically.
We found that sindaniel/raygun4php demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.

Product
Put vulnerability remediation on autopilot with automated security patches and intelligent dependency upgrades across your GitHub repositories.

Product
Socket Zero automates vulnerability remediation with upgrades and targeted patches, including fixes for 100% of known, patchable RubyGems CVEs.

Product
Explore Socket’s redesigned Alerts UI, multi-branch repository monitoring, and new tools for resolving findings, searching scans, and filtering security alerts.