PHP Functions 6 programs with output 15 Q/A 5 MCQs

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
FunctionPurpose
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.
File: htdocs/phpbook/ch26/backtrace.php
<?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>";
?>
OUTPUT browser · http://localhost/phpbook/ch26/backtrace.php
#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
File: htdocs/phpbook/ch26/lasterror.php
<?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();
?>
OUTPUT browser · http://localhost/phpbook/ch26/lasterror.php
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
FunctionPurpose
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.)

File: htdocs/phpbook/ch26/headers.php
<?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();
?>
OUTPUT browser · http://localhost/phpbook/ch26/headers.php
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:

File: htdocs/phpbook/ch26/redirect.php
<?php
header("Location: target.php");
exit;        // always stop the script after a redirect
?>
OUTPUT browser · http://localhost/phpbook/ch26/redirect.php (address bar changes to target.php)
You were redirected to target.php (status OK).
Mail Functions
FunctionPurpose
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
FunctionPurpose
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 / decbinBinary ↔ decimal.
hexdec / dechexHexadecimal ↔ decimal.
octdec / decoctOctal ↔ 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.
File: htdocs/phpbook/ch26/math.php
<?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();
?>
OUTPUT browser · http://localhost/phpbook/ch26/math.php
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() = 2147483647

Random numbers are different on every run, so seeding with a fixed value makes the sequence repeatable (useful for tests):

File: htdocs/phpbook/ch26/random.php
<?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)";
?>
OUTPUT browser · http://localhost/phpbook/ch26/random.php
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 example Location: redirects – and must come before any output; follow a redirect with exit.
  • http_response_code(), headers_list() and headers_sent() inspect and control the response.
  • Maths: rounding (ceil, floor, round), intdiv, fmod, powers and roots, logs, trigonometry in radians, base conversions and number_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)

Answer : It sets or returns the level of errors PHP reports for the current script, e.g. error_reporting(E_ALL) or error_reporting(E_ALL & ~E_NOTICE).

Answer : 0 sends the message to PHP's system logger/log file, 1 sends it by e-mail to the destination address, 3 appends it to the destination file, 4 sends it to the SAPI logging handler.

Answer : The list of function calls that led to the current point in the program; debug_backtrace() returns it as an array and debug_print_backtrace() prints it.

Answer : An associative array (type, message, file, line) describing the last error that occurred, or null if none.

Answer : header("Location: page.php"); followed by exit; so that the rest of the script does not run.

Answer : HTTP headers are sent before the page body; once any output (even a space) has been sent, the headers are already gone and PHP reports "headers already sent".

Answer : headers_list() returns the headers that are prepared to be sent; headers_sent() tells whether the headers have already been sent (and where output started).

Answer : setcookie() URL-encodes the cookie value automatically; setrawcookie() sends the value as it is.

Answer : ceil() rounds up to the next integer, floor() rounds down, and round() rounds to the nearest value with an optional number of decimal places.

Answer : intdiv(a, b) returns the integer quotient; fmod(x, y) returns the floating-point remainder.

Answer : In radians; convert degrees with deg2rad() (and back with rad2deg()).

Answer : dechex(255) gives "ff" and decbin(255) gives "11111111".

Answer : number_format(1234567.891, 2) gives 1,234,567.89 (Western grouping); Indian grouping (12,34,567.89) needs the NumberFormatter class with the en_IN locale.

Answer : mt_rand() is fast but predictable (pseudo-random) and can be seeded; random_int() is cryptographically secure and should be used for OTPs, tokens and passwords.

Answer : To make the random sequence repeatable, for example in tests or demonstrations.
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.

Q1. Which function rounds 4.1 up to 5?

Show Answer

Correct Answer : C. ceil()
ceil() always rounds up.

Q2. header("Location: home.php"); is used to:

Show Answer

Correct Answer : B. Redirect the browser
The Location header tells the browser to load another URL.

Q3. Which error_log() message type appends to a file?

Show Answer

Correct Answer : C. 3
Type 3 appends the message to the destination file.

Q4. dechex(255) returns:

Show Answer

Correct Answer : A. "ff"
255 decimal is ff in hexadecimal.

Q5. For a secure OTP you should use:

Show Answer

Correct Answer : C. random_int()
random_int() is cryptographically secure.

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.

  1. The PHP Group. (n.d.). PHP Manual – Error Handling Functions. https://www.php.net/manual/en/ref.errorfunc.php
  2. The PHP Group. (n.d.). PHP Manual – header. https://www.php.net/manual/en/function.header.php
  3. The PHP Group. (n.d.). PHP Manual – Network Functions (header, setcookie). https://www.php.net/manual/en/ref.network.php
  4. The PHP Group. (n.d.). PHP Manual – Math Functions. https://www.php.net/manual/en/ref.math.php
  5. The PHP Group. (n.d.). PHP Manual – random_int. https://www.php.net/manual/en/function.random-int.php