Learning Objectives – after this chapter you will be able to:
- Use the error-handling and logging functions, including backtraces.
- Send HTTP headers, cookies and redirects with
header(),setcookie()and related functions. - Look up mail functions.
- Use PHP's mathematical functions for rounding, conversions, trigonometry and random numbers.
Error Handling and Logging Functions
| Function | Purpose |
|---|---|
| error_reporting([level]) | Sets/returns which PHP errors are reported. |
| error_log(message [, type, destination, headers]) | Sends an error message: type 0 to PHP's system logger, 1 by e-mail to destination, 3 appended to the file destination, 4 to the SAPI handler. |
| set_error_handler(callback [, levels]) | Sets a user-defined error handler function. |
| restore_error_handler() | Restores the previous error handler. |
| set_exception_handler(callback) | Sets a user-defined handler for uncaught exceptions. |
| restore_exception_handler() | Restores the previous exception handler. |
| trigger_error(message [, level]) | Generates a user-level error/warning/notice. user_error() is an alias. |
| error_get_last() | Returns information about the last error that occurred. |
| debug_backtrace() | Generates a backtrace and returns it as an array. |
| debug_print_backtrace() | Prints a backtrace. |
<?php
function level3() { debug_print_backtrace(); return count(debug_backtrace()); }
function level2() { return level3(); }
function level1() { return level2(); }
echo "<pre>";
$depth = level1();
echo "Depth returned by debug_backtrace(): $depth\n";
echo "</pre>";
?>#0 /opt/lampp/htdocs/phpbook/ch26/backtrace.php(3): level3() #1 /opt/lampp/htdocs/phpbook/ch26/backtrace.php(4): level2() #2 /opt/lampp/htdocs/phpbook/ch26/backtrace.php(6): level1() Depth returned by debug_backtrace(): 3
<?php
$x = @file_get_contents("missing.txt"); // error suppressed with @
$e = error_get_last();
echo "Last error type: " . $e['type'] . "<br>";
echo "Message: " . $e['message'] . "<br>";
echo "Current error_reporting level: " . error_reporting();
?>Last error type: 2 Message: file_get_contents(missing.txt): Failed to open stream: No such file or directory Current error_reporting level: 32767
HTTP Functions
| Function | Purpose |
|---|---|
| header(string [, replace, response_code]) | Sends a raw HTTP header, e.g. Location:, Content-Type:. |
| headers_list() | Returns an array of the headers that will be sent. |
| headers_sent([&file, &line]) | Checks whether headers have already been sent. |
| header_remove([name]) | Removes a previously set header. |
| http_response_code([code]) | Gets or sets the HTTP response status code. |
| setcookie(name [, value, expires, path, domain, secure, httponly]) | Sends a cookie (URL-encodes the value) – Chapter 30. |
| setrawcookie(name [, value, ...]) | Sends a cookie without URL-encoding the value. |
header(), setcookie() and session_start() must be called before any output – even a blank line or space before <?php – otherwise PHP reports "Cannot modify header information – headers already sent". (XAMPP's output_buffering = 4096 hides small mistakes, but do not rely on it.)
<?php
header("Content-Type: text/html; charset=UTF-8");
header("X-Powered-By-Book: PHP Basics to Advance");
header("Cache-Control: no-cache");
echo "Headers prepared by this script:<br>";
foreach (headers_list() as $h) {
echo htmlspecialchars($h) . "<br>";
}
echo "Response code: " . http_response_code();
?>Headers prepared by this script: Content-Type: text/html; charset=UTF-8 X-Powered-By-Book: PHP Basics to Advance Cache-Control: no-cache Response code: 200
Redirecting the browser to another page with a Location header:
<?php
header("Location: target.php");
exit; // always stop the script after a redirect
?>You were redirected to target.php (status OK).
Mail Functions
| Function | Purpose |
|---|---|
| mail(to, subject, message [, headers, params]) | Sends mail (Chapter 15). |
| ezmlm_hash(addr) | Calculated the hash value needed by EZMLM mailing lists – removed in PHP 8.0. |
Mathematical Functions
| Function | Purpose |
|---|---|
| abs(number) | Absolute value. |
| ceil(number) | Rounds fractions up to the next integer. |
| floor(number) | Rounds fractions down to the next integer. |
| round(number [, precision]) | Rounds to the nearest value with the given number of decimals. |
| intdiv(a, b) | Integer division. |
| fmod(x, y) | Floating-point remainder of x / y. |
| max(values...) / min(values...) | Highest / lowest value (also of an array). |
| pow(base, exp) | base raised to the power exp (same as **). |
| sqrt(n) | Square root. |
| exp(n) | e raised to the power n. |
| log(n [, base]) / log10(n) / log1p(n) | Natural / base-10 logarithm; log(1+n). |
| pi() | The value of π (constant M_PI). |
| sin / cos / tan (rad) | Sine, cosine, tangent (argument in radians). |
| asin / acos / atan (n) | Arc sine, arc cosine, arc tangent in radians. |
| atan2(y, x) | Arc tangent of y/x using the signs to find the quadrant. |
| deg2rad(deg) / rad2deg(rad) | Converts degrees ↔ radians. |
| base_convert(number, from_base, to_base) | Converts a number between any bases 2–36. |
| bindec / decbin | Binary ↔ decimal. |
| hexdec / dechex | Hexadecimal ↔ decimal. |
| octdec / decoct | Octal ↔ decimal. |
| is_finite / is_infinite / is_nan (value) | Checks for finite numbers, infinity, "not a number". |
| number_format(number [, decimals, dec_point, thousands_sep]) | Formats a number with grouped thousands. |
| rand([min, max]) / mt_rand([min, max]) | Random integer (both use the Mersenne Twister in PHP 7.1+). |
| random_int(min, max) | Cryptographically secure random integer (PHP 7). |
| getrandmax() / mt_getrandmax() | Largest possible random value. |
| srand([seed]) / mt_srand([seed]) | Seeds the random number generator. |
| lcg_value() | Pseudo-random float between 0 and 1. |
<?php
echo "abs(-7.5) = " . abs(-7.5) . "<br>";
echo "ceil(4.1) = " . ceil(4.1) . ", floor(4.9) = " . floor(4.9) . "<br>";
echo "round(3.14159, 2) = " . round(3.14159, 2) . ", round(1234.5) = " . round(1234.5) . "<br>";
echo "intdiv(17, 5) = " . intdiv(17, 5) . ", fmod(17.5, 5) = " . fmod(17.5, 5) . "<br>";
echo "max(4, 9, 2) = " . max(4, 9, 2) . ", min([4, 9, 2]) = " . min([4, 9, 2]) . "<br>";
echo "pow(2, 10) = " . pow(2, 10) . ", sqrt(144) = " . sqrt(144) . "<br>";
echo "pi() = " . pi() . "<br>";
echo "sin(30°) = " . round(sin(deg2rad(30)), 2) . ", rad2deg(M_PI) = " . rad2deg(M_PI) . "<br>";
echo "log(M_E) = " . log(M_E) . ", log10(1000) = " . log10(1000) . ", exp(1) = " . round(exp(1), 4) . "<br>";
echo "decbin(10) = " . decbin(10) . ", bindec('1010') = " . bindec("1010") . "<br>";
echo "dechex(255) = " . dechex(255) . ", hexdec('ff') = " . hexdec("ff") . "<br>";
echo "decoct(8) = " . decoct(8) . ", base_convert('z', 36, 10) = " . base_convert("z", 36, 10) . "<br>";
echo "number_format(1234567.891, 2) = " . number_format(1234567.891, 2) . "<br>";
echo "number_format(1234567.891, 2, ',', '.') = " . number_format(1234567.891, 2, ',', '.') . "<br>";
echo "is_nan(sqrt(-1)) = " . var_export(is_nan(sqrt(-1)), true) . "<br>";
echo "mt_getrandmax() = " . mt_getrandmax();
?>abs(-7.5) = 7.5
ceil(4.1) = 5, floor(4.9) = 4
round(3.14159, 2) = 3.14, round(1234.5) = 1235
intdiv(17, 5) = 3, fmod(17.5, 5) = 2.5
max(4, 9, 2) = 9, min([4, 9, 2]) = 2
pow(2, 10) = 1024, sqrt(144) = 12
pi() = 3.1415926535898
sin(30°) = 0.5, rad2deg(M_PI) = 180
log(M_E) = 1, log10(1000) = 3, exp(1) = 2.7183
decbin(10) = 1010, bindec('1010') = 10
dechex(255) = ff, hexdec('ff') = 255
decoct(8) = 10, base_convert('z', 36, 10) = 35
number_format(1234567.891, 2) = 1,234,567.89
number_format(1234567.891, 2, ',', '.') = 1.234.567,89
is_nan(sqrt(-1)) = true
mt_getrandmax() = 2147483647Random numbers are different on every run, so seeding with a fixed value makes the sequence repeatable (useful for tests):
<?php mt_srand(2026); echo "Seeded mt_rand(1, 6): "; for ($i = 0; $i < 5; $i++) echo mt_rand(1, 6) . " "; echo "<br>A secure OTP: " . str_pad(random_int(0, 999999), 6, "0", STR_PAD_LEFT) . " (changes every run)"; ?>
Seeded mt_rand(1, 6): 4 1 3 1 4 A secure OTP: 868124 (changes every run)
Key Takeaways
- Error functions:
error_reporting,error_log,set_error_handler,trigger_error,error_get_last,debug_backtrace. header()sends raw HTTP headers – for exampleLocation:redirects – and must come before any output; follow a redirect withexit.http_response_code(),headers_list()andheaders_sent()inspect and control the response.- Maths: rounding (
ceil,floor,round),intdiv,fmod, powers and roots, logs, trigonometry in radians, base conversions andnumber_format. - Use
random_int()for security-related random numbers.
Program File
Extract the ZIP into C:\xampp\htdocs. It creates the folder phpbook/ch26 used in the file labels above; open the programs at http://localhost/phpbook/… with Apache (and MySQL, where needed) started in the XAMPP Control Panel.
Question / Answer (15 questions)
MCQ Test : Check Your Understanding (5 questions)
Select an option and press Check Answer, or answer all questions and press Submit Test to see your score. Each answer comes with an explanation.
Bibliography/References
The notes on this page are the author’s own compilation from the e-book PHP: Basics to Advance. Every program was run on Apache with PHP 8 and MariaDB, and the output shown is the real result of that run. The works listed below were consulted and are cited for attribution and further reading. Product names and trademarks belong to their respective owners.
- The PHP Group. (n.d.). PHP Manual – Error Handling Functions. https://www.php.net/manual/en/ref.errorfunc.php
- The PHP Group. (n.d.). PHP Manual – header. https://www.php.net/manual/en/function.header.php
- The PHP Group. (n.d.). PHP Manual – Network Functions (header, setcookie). https://www.php.net/manual/en/ref.network.php
- The PHP Group. (n.d.). PHP Manual – Math Functions. https://www.php.net/manual/en/ref.math.php
- The PHP Group. (n.d.). PHP Manual – random_int. https://www.php.net/manual/en/function.random-int.php