trigger_error(): generating user-level error messages

Generate an application warning

<?php
$sellPrice = 100;
$buyPrice = 120;

if ($sellPrice <= $buyPrice) {
    trigger_error('Selling price does not include a profit.', E_USER_WARNING);
}
?>

Exact error wording and whether it is displayed in the browser depend on the PHP version and error configuration. Production applications usually log errors rather than exposing paths and stack details to visitors.

Available user-level constants

<?php
trigger_error('This is a notice.', E_USER_NOTICE);
trigger_error('This is a warning.', E_USER_WARNING);
trigger_error('This is a user error.', E_USER_ERROR);
?>

Convert selected PHP errors into exceptions

<?php
set_error_handler(
    static function (int $severity, string $message, string $file, int $line): bool {
        if (!(error_reporting() & $severity)) {
            return false;
        }

        throw new ErrorException($message, 0, $severity, $file, $line);
    }
);

try {
    trigger_error('Custom warning.', E_USER_WARNING);
} catch (ErrorException $e) {
    echo htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8');
} finally {
    restore_error_handler();
}
?>

Validation example

<?php
$age = -5;

if ($age < 0) {
    trigger_error('Age cannot be negative.', E_USER_WARNING);
}
?>

Log errors instead of displaying them

<?php
ini_set('log_errors', '1');
// Configure error_log in php.ini or server configuration where possible.
trigger_error('This message can be written to the PHP error log.', E_USER_NOTICE);
?>

Syntax and legacy output examples

The function signature is:

trigger_error(string $message, int $error_level = E_USER_NOTICE): true

A development server may display a warning similar to:

Warning: Selling price does not include a profit. in /path/example.php on line 7

An older tutorial may explicitly request E_USER_ERROR:

<?php
trigger_error('Do you want to sell without profit?', E_USER_ERROR);
?>

Older PHP versions might display wording such as:

Fatal error: Do you want to sell without profit? in /path/example.php on line 5

E_USER_NOTICE has the numeric value 1024, but using the named constant is clearer:

<?php
trigger_error('Do you want to sell without profit?', E_USER_NOTICE);
?>

A notice may appear in development output like this:

Notice: Do you want to sell without profit? in /path/example.php on line 5

user_error() is an alias of trigger_error().

Managing PHP errors →




Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer