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

Learning Objectives – after this chapter you will be able to:

  • Use the network functions for host names, IP addresses, services, sockets and the system log.
  • Control output with the output-buffering functions.
  • Read and change PHP's configuration at run time and get information about the environment.
  • Look up the session functions and know which old ones were removed.
Network Functions
FunctionPurpose
gethostbyname(host)Returns the IPv4 address of a host name.
gethostbynamel(host)Returns a list of all IPv4 addresses of a host name.
gethostbyaddr(ip)Returns the host name of an IP address.
gethostname()Returns the host name of the local machine.
ip2long(ip)Converts a dotted IPv4 address into an integer.
long2ip(int)Converts an integer into a dotted IPv4 address.
getservbyname(service, protocol)Port number of a service, e.g. http/tcp → 80.
getservbyport(port, protocol)Service name of a port number.
getprotobyname(name) / getprotobynumber(n)Protocol number of a name / name of a number.
checkdnsrr(host [, type])Checks DNS records of a host (dns_check_record() is an alias).
dns_get_record(host [, type])Returns the DNS records of a host.
getmxrr(host, &mxhosts [, &weights])Gets the mail-exchanger (MX) records (dns_get_mx() is an alias).
fsockopen(host [, port, &errno, &errstr, timeout])Opens an Internet or Unix-domain socket connection.
pfsockopen(...)Opens a persistent socket connection.
openlog(ident, option, facility) / syslog(priority, message) / closelog()Writes messages to the system log.
define_syslog_variables()Initialised syslog variables – removed in PHP 5.4.
File: htdocs/phpbook/ch28/network.php
<?php
echo "gethostbyname('localhost'): " . gethostbyname("localhost") . "<br>";
echo "gethostbyaddr('127.0.0.1'): " . gethostbyaddr("127.0.0.1") . "<br>";
echo "ip2long('192.168.1.10'): " . ip2long("192.168.1.10") . "<br>";
echo "long2ip(3232235786): " . long2ip(3232235786) . "<br>";
echo "getservbyname('http', 'tcp'): " . getservbyname("http", "tcp") . "<br>";
echo "getservbyname('https', 'tcp'): " . getservbyname("https", "tcp") . "<br>";
echo "getservbyport(3306, 'tcp'): " . getservbyport(3306, "tcp") . "<br>";
echo "getprotobyname('tcp'): " . getprotobyname("tcp") . "<br>";

// open a socket to the local web server and send a raw HTTP request
$fp = fsockopen("localhost", 80, $errno, $errstr, 5);
if (!$fp) {
    echo "Socket error: $errstr ($errno)";
} else {
    fwrite($fp, "HEAD / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n");
    echo "First line of the server's reply: " . fgets($fp);
    fclose($fp);
}
?>
OUTPUT browser · http://localhost/phpbook/ch28/network.php
gethostbyname('localhost'): 127.0.0.1
gethostbyaddr('127.0.0.1'): localhost
ip2long('192.168.1.10'): 3232235786
long2ip(3232235786): 192.168.1.10
getservbyname('http', 'tcp'): 80
getservbyname('https', 'tcp'): 443
getservbyport(3306, 'tcp'): mysql
getprotobyname('tcp'): 6
First line of the server's reply: HTTP/1.1 200 OK
Output Buffering Functions

Normally PHP sends output to the browser as it is produced. With output buffering the output is collected in a buffer first, so that you can still send headers, modify the output or discard it.

FunctionPurpose
ob_start([callback])Turns output buffering on (optionally passing the output through a callback).
ob_get_contents()Returns the contents of the buffer.
ob_get_length()Returns the length of the buffer's contents.
ob_get_level()Returns the nesting level of output buffering.
ob_get_clean()Returns the buffer contents and deletes the buffer.
ob_clean()Erases the contents of the buffer.
ob_flush()Sends the buffer contents to the output.
ob_end_flush()Sends the buffer contents and turns this buffer off.
ob_end_clean()Erases the buffer contents and turns this buffer off.
ob_list_handlers()Lists all output handlers in use.
ob_gzhandler(buffer, mode)Callback for ob_start() that gzip-compresses the output.
ob_implicit_flush([flag])Turns implicit flushing on or off.
flush()Flushes the system write buffers of PHP and the web server.
output_add_rewrite_var(name, value)Adds a name/value pair to URLs and forms in the output.
output_reset_rewrite_vars()Resets the values added by output_add_rewrite_var().
File: htdocs/phpbook/ch28/buffer.php
<?php
ob_start();
echo "This text goes into the buffer.";
$captured = ob_get_contents();
$length = ob_get_length();
ob_end_clean();                          // discard the buffer – nothing was sent
echo "Captured: '$captured' ($length characters)<br>";

function shout($buffer) { return strtoupper($buffer); }
ob_start("shout");                       // pass the output through a callback
echo "this line is converted to capitals by the callback.<br>";
ob_end_flush();

ob_start();
include "box.php";                       // capture the output of an included file
$html = ob_get_clean();
echo "box.php produced " . strlen($html) . " bytes: " . $html;
echo "<br>Buffer level now: " . ob_get_level();
?>
OUTPUT browser · http://localhost/phpbook/ch28/buffer.php
Captured: 'This text goes into the buffer.' (31 characters)
THIS LINE IS CONVERTED TO CAPITALS BY THE CALLBACK.
box.php produced 13 bytes: [box]
Buffer level now: 1

(The final buffer level is 1, not 0, because XAMPP's php.ini enables output_buffering = 4096, which starts one buffer for every request.)

PHP Configuration and Information Functions
FunctionPurpose
phpinfo([what])Displays the complete configuration and environment of PHP (Chapter 2).
phpversion([extension])Returns the PHP version (or of an extension).
phpcredits([flag])Displays the credits of PHP.
php_uname([mode])Returns information about the operating system.
php_sapi_name()Returns the server API used, e.g. apache2handler, cli.
zend_version()Returns the version of the Zend Engine.
version_compare(v1, v2 [, operator])Compares two version strings.
ini_get(name) / ini_get_all([extension])Gets one / all configuration options.
ini_set(name, value)Sets a configuration option for this script. ini_alter() is an alias.
ini_restore(name)Restores an option to its php.ini value.
get_cfg_var(name)Gets the value from php.ini (ignores run-time changes).
php_ini_loaded_file() / php_ini_scanned_files()Returns the loaded php.ini / the additional .ini files.
set_time_limit(seconds)Sets the maximum execution time of the script.
memory_get_usage([real]) / memory_get_peak_usage()Memory currently / at most used by the script.
extension_loaded(name)Checks whether an extension is loaded.
get_loaded_extensions()Returns the names of all loaded extensions.
get_extension_funcs(name)Returns the functions of an extension.
get_defined_constants([categorize])Returns all defined constants.
get_include_path() / set_include_path(path)Gets / sets the include_path option.
get_included_files()Returns the names of included/required files (get_required_files() is an alias).
getenv(name) / putenv("NAME=value")Gets / sets an environment variable.
get_current_user()Returns the owner of the current script.
getmypid() / getmyuid() / getmygid() / getmyinode()Process id; user id, group id and inode of the script.
getlastmod()Time of the last modification of the current page.
getrusage([who])Resource usage of the current process.
getopt(short [, long])Command-line options (CLI scripts).
assert(assertion [, description])Checks an assertion (development aid).
assert_options(what [, value])Set assertion flags – deprecated in PHP 8.3; use the php.ini zend.assertions setting.
get_magic_quotes_gpc() / get_magic_quotes_runtime()Removed in PHP 8.0 (magic quotes no longer exist).
set_magic_quotes_runtime()Removed in PHP 7.0.
restore_include_path()Removed in PHP 8.0; use ini_restore('include_path').
php_logo_guid() / zend_logo_guid()Removed in PHP 5.5.
File: htdocs/phpbook/ch28/config.php
<?php
echo "phpversion(): " . phpversion() . "<br>";
echo "zend_version(): " . zend_version() . "<br>";
echo "php_sapi_name(): " . php_sapi_name() . "<br>";
echo "php_uname('s'): " . php_uname("s") . "<br>";
echo "version_compare(PHP_VERSION, '8.0.0', '>='): " . var_export(version_compare(PHP_VERSION, "8.0.0", ">="), true) . "<br>";
echo "ini_get('upload_max_filesize'): " . ini_get("upload_max_filesize") . "<br>";
echo "ini_get('max_execution_time'): " . ini_get("max_execution_time") . "<br>";
ini_set("max_execution_time", "60");
echo "after ini_set: " . ini_get("max_execution_time") . ", get_cfg_var: " . get_cfg_var("max_execution_time") . "<br>";
echo "extension_loaded('mysqli'): " . var_export(extension_loaded("mysqli"), true) . "<br>";
echo "Number of loaded extensions: " . count(get_loaded_extensions()) . "<br>";
echo "mysqli functions: " . count(get_extension_funcs("mysqli")) . "<br>";
echo "Memory used: " . round(memory_get_usage() / 1024) . " KB<br>";
echo "Script owner: " . get_current_user() . ", PID: " . (getmypid() > 0 ? "a number" : "?") . "<br>";
echo "M_PI constant: " . get_defined_constants(true)['standard']['M_PI'];
?>
OUTPUT browser · http://localhost/phpbook/ch28/config.php
phpversion(): 8.3.6
zend_version(): 4.3.6
php_sapi_name(): apache2handler
php_uname('s'): Linux
version_compare(PHP_VERSION, '8.0.0', '>='): true
ini_get('upload_max_filesize'): 40M
ini_get('max_execution_time'): 30
after ini_set: 60, get_cfg_var: 30
extension_loaded('mysqli'): true
Number of loaded extensions: 57
mysqli functions: 106
Memory used: 352 KB
Script owner: root, PID: a number
M_PI constant: 3.1415926535898
Session Functions

Sessions are explained in detail in Chapter 31. The functions are:

FunctionPurpose
session_start([options])Starts a new session or resumes the existing one.
session_status()Returns PHP_SESSION_DISABLED, PHP_SESSION_NONE or PHP_SESSION_ACTIVE.
session_id([id])Gets or sets the current session id.
session_name([name])Gets or sets the session name (cookie name, default PHPSESSID).
session_regenerate_id([delete_old])Generates a new session id, keeping the session data – use after login.
session_create_id([prefix])Creates a new, unused session id.
session_unset()Frees all session variables (empties $_SESSION).
session_destroy()Destroys all data registered to the session.
session_write_close()Writes the session data and ends the session. session_commit() is an alias.
session_abort() / session_reset()Discards changes / re-reads the original session data.
session_encode() / session_decode(data)Encodes the session data as a string / decodes a string into the session.
session_save_path([path])Gets or sets the folder where session files are saved.
session_get_cookie_params() / session_set_cookie_params(...)Gets / sets the lifetime, path, domain, secure, httponly and samesite options of the session cookie.
session_cache_expire([minutes]) / session_cache_limiter([value])Gets or sets the cache expiry and cache limiter.
session_module_name([module])Gets or sets the session storage module (files, …).
session_set_save_handler(...)Sets user-level session storage functions (e.g. to store sessions in a database).
session_gc()Performs session garbage collection.
session_register(name, ...) / session_unregister(name) / session_is_registered(name)Registered / unregistered / checked session variables – removed in PHP 5.4; use $_SESSION['name'], unset($_SESSION['name']) and isset($_SESSION['name']).
File: htdocs/phpbook/ch28/sessionfuncs.php
<?php
session_name("PHPBOOKSESS");
session_start();
$_SESSION['user'] = "Asha";
$_SESSION['role'] = "student";
echo "session_status(): " . (session_status() === PHP_SESSION_ACTIVE ? "PHP_SESSION_ACTIVE" : "other") . "<br>";
echo "session_name(): " . session_name() . "<br>";
echo "session_id() length: " . strlen(session_id()) . " characters<br>";
echo "session_encode(): " . session_encode() . "<br>";
$p = session_get_cookie_params();
echo "cookie lifetime: {$p['lifetime']}, path: {$p['path']}, httponly: " . var_export($p['httponly'], true) . "<br>";
$old = session_id();
session_regenerate_id(true);
echo "Id changed after regenerate: " . var_export($old !== session_id(), true) . "<br>";
session_unset();
echo "After session_unset, items in \$_SESSION: " . count($_SESSION) . "<br>";
session_destroy();
echo "After session_destroy: " . (session_status() === PHP_SESSION_NONE ? "PHP_SESSION_NONE" : "active");
?>
OUTPUT browser · http://localhost/phpbook/ch28/sessionfuncs.php
session_status(): PHP_SESSION_ACTIVE
session_name(): PHPBOOKSESS
session_id() length: 26 characters
session_encode(): user|s:4:"Asha";role|s:7:"student";
cookie lifetime: 0, path: /, httponly: false
Id changed after regenerate: true
After session_unset, items in $_SESSION: 0
After session_destroy: PHP_SESSION_NONE
Key Takeaways
  • Network functions convert host names and IP addresses, look up services and protocols, query DNS and open sockets.
  • Output buffering (ob_start, ob_get_clean, ob_end_flush …) lets you capture, change or discard output before it is sent.
  • Configuration functions read and change settings (ini_get, ini_set) and report on PHP (phpversion, php_sapi_name, extension_loaded, memory_get_usage).
  • Magic-quotes functions, php_logo_guid() and restore_include_path() no longer exist; assert_options() is deprecated in 8.3.
  • Session functions manage the session; session_register() & co. were removed in 5.4 – use $_SESSION.
Program File

Extract the ZIP into C:\xampp\htdocs. It creates the folder phpbook/ch28 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 : gethostbyname() returns the IPv4 address of a host name; gethostbyaddr() returns the host name of an IP address.

Answer : They convert IPv4 addresses to integers and back, which makes it easy to store addresses in a database and to compare IP ranges.

Answer : 80 – the port number of the HTTP service over TCP.

Answer : To open a raw TCP/UDP or Unix socket connection to a host and port, so that the script can talk to another server directly with fwrite()/fgets().

Answer : A mechanism in which PHP stores output in a memory buffer instead of sending it immediately, so it can be modified, captured or discarded and headers can still be sent.

Answer : ob_end_flush() sends the buffer contents to the browser and turns buffering off; ob_end_clean() discards the contents and turns buffering off.

Answer : ob_start(); include "file.php"; $html = ob_get_clean();

Answer : It starts buffering and passes the buffered output through the callback function before it is sent, e.g. to compress or modify it (ob_gzhandler compresses).

Answer : With ini_set("option", "value"); ini_get() reads the current value, and get_cfg_var() still returns the php.ini value.

Answer : extension_loaded("mysqli") returns true if it is loaded; function_exists("mysqli_connect") also works.

Answer : "apache2handler", because PHP runs as an Apache module; from the command line it returns "cli".

Answer : get_magic_quotes_gpc()/get_magic_quotes_runtime() (removed in 8.0) and set_magic_quotes_runtime() (7.0) because magic quotes were removed; restore_include_path() was removed in 8.0; php_logo_guid()/zend_logo_guid() in 5.5.

Answer : It gives the current session a new id while keeping its data; it should be called after login to prevent session fixation attacks.

Answer : session_unset() empties all session variables but keeps the session; session_destroy() destroys the session data on the server.

Answer : The $_SESSION superglobal: $_SESSION['name'] = value; unset($_SESSION['name']) and isset($_SESSION['name']) replace session_register(), session_unregister() and session_is_registered().
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. ip2long("192.168.1.10") returns:

Show Answer

Correct Answer : B. An integer
It converts the address into an integer.

Q2. Which function returns the buffer contents and deletes the buffer?

Show Answer

Correct Answer : B. ob_get_clean()
ob_get_clean() = get contents + end clean.

Q3. Which function changes a php.ini setting for the current script only?

Show Answer

Correct Answer : B. ini_set()
ini_set() changes the option at run time.

Q4. What does php_sapi_name() return under XAMPP's Apache?

Show Answer

Correct Answer : B. apache2handler
PHP runs as an Apache module.

Q5. Which session function was removed in PHP 5.4?

Show Answer

Correct Answer : B. session_register()
Use $_SESSION instead.

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 – Network Functions (header, setcookie). https://www.php.net/manual/en/ref.network.php
  2. The PHP Group. (n.d.). PHP Manual – Output Control Functions. https://www.php.net/manual/en/ref.outcontrol.php
  3. The PHP Group. (n.d.). PHP Manual – PHP Options/Info Functions. https://www.php.net/manual/en/ref.info.php
  4. The PHP Group. (n.d.). PHP Manual – Session Functions. https://www.php.net/manual/en/ref.session.php
  5. The PHP Group. (n.d.). PHP Manual – Deprecated features in PHP 8.3. https://www.php.net/manual/en/migration83.deprecated.php