PHP Network

Beginner
10 min read
Updated: Nov 2026
3 examples
DNS, headers & IP

Definition and Usage

PHP Network functions help you talk about hosts, responses, and addresses in plain PHP. You can ask DNS whether a name has an A or MX record, turn a host name into an IP address, send HTTP headers and cookies before any page output, convert IPv4 and IPv6 addresses, open a TCP socket, or write a line to the system log.

DNS helpers such as checkdnsrr(), gethostbyname(), and dns_get_record() answer questions about names and records. On the web side, header(), http_response_code(), and setcookie() shape the response the browser sees.

For addresses, ip2long() and long2ip() work with IPv4 numbers, while inet_pton() and inet_ntop() also cover IPv6. Raw connections use fsockopen() or the persistent pfsockopen(). Logging uses openlog(), syslog(), and closelog().

This page explains the ideas. The Network Functions index lists all 37 function guides.

Headers come first.

Call header() and setcookie() before you print anything. Once the body starts, headers_sent() is true and new headers cannot go out.

Aliases and PHP 8.4.

Some names are aliases (dns_check_record() for checkdnsrr(), getmxrr() for dns_get_mx(), and the socket_* names for stream helpers). PHP 8.4 adds http_get_last_response_headers(), http_clear_last_response_headers(), and request_parse_body().

PHP Syntax

The usual pattern: look up a host, set response headers early, convert addresses when you store or compare them:

PHP
// DNS and hosts
$ok   = checkdnsrr('example.com', 'A');     // bool
$ip   = gethostbyname('localhost');         // string IP, or the name on failure
$ips  = gethostbynamel('localhost');        // array of IPs, or false
$name = gethostname();                      // this machine's host name
$recs = dns_get_record('example.com', DNS_A);

// HTTP response (before any output)
header('Content-Type: text/plain; charset=UTF-8');
http_response_code(200);
setcookie('theme', 'dark', ['path' => '/', 'httponly' => true]);
$list = headers_list();                     // array of header strings
$sent = headers_sent();                     // bool

// IPv4 and packed addresses
$num  = ip2long('127.0.0.1');               // int|false
$back = long2ip($num);                      // string
$bin  = inet_pton('127.0.0.1');             // binary string|false
$text = inet_ntop($bin);                    // string|false

// Socket (close when done)
$fp = fsockopen('127.0.0.1', 80, $errno, $errstr, 5.0);
if ($fp) { fclose($fp); }

// Syslog
openlog('codetofun', LOG_PID | LOG_PERROR, LOG_USER);
syslog(LOG_INFO, 'Network tutorial ready');
closelog();

Core Ideas

What to remember when you work with PHP Network functions:

IdeaFunctionRemember
DNS exists?checkdnsrr()Returns true or false for a record type; dns_check_record() is the same call
Name to IPgethostbyname()One IPv4 address as a string; on failure it returns the host name unchanged—compare carefully
All IPv4sgethostbynamel()Array of IPv4 addresses, or false; use this when a name can have more than one A record
Full DNS rowsdns_get_record()Returns an array of associative records; pick a type with constants such as DNS_A or DNS_MX
Send a headerheader()Must run before body output; use header_remove() to drop one you set earlier
Status codehttp_response_code()Set with an integer, or call with no argument to read the current code
Cookiessetcookie()Also a header; setrawcookie() skips URL-encoding the value
IPv4 numberip2long() / long2ip()Useful for ranges and storage; on 32-bit builds the result can look negative for high addresses
Packed IPinet_pton() / inet_ntop()Works for IPv4 and IPv6; prefer these when you need both families
TCP streamfsockopen()Returns a stream resource; pfsockopen() keeps the connection across requests when possible

Protocol tables and logging

Map names and numbers with getprotobyname(), getprotobynumber(), getservbyname(), and getservbyport(). For the system log, open a channel with openlog(), write with syslog(), then closelog(). On a stream from fsockopen(), the older names socket_get_status(), socket_set_blocking(), and socket_set_timeout() are aliases of the stream helpers.

Function Groups at a Glance

The Network section is one family with several jobs. Use this map to pick the right group before you open a function page:

GroupTypical jobStart here
DNS & hostsAsk whether a name exists, resolve A/MX, reverse-lookup an IPcheckdnsrr(), gethostbyname()
HTTP headersStatus line, Content-Type, redirects, inspect what you already sentheader(), headers-list()
CookiesSet or clear browser cookies as response headerssetcookie()
IP conversionStore, compare, or pack addresses; list local interfacesip2long(), inet_pton()
SocketsOpen a TCP/SSL stream and tune blocking or timeoutfsockopen()
SyslogWrite structured messages to the system loggeropenlog(), syslog()

Neighboring tutorials that often sit next to this work: SimpleXML for parsing API XML, Variables for types and casting, Filesystem for local files beside network I/O, and JSON for API payloads.

PHP Examples

Three short scripts that show the core Network ideas. The first uses local host helpers so the sample stays easy to follow; the second and third are fully self-contained. Each block includes a fixed View Output panel that matches this tutorial layout.

Example 1 — DNS lookup helpers

Resolve localhost, reverse-look up the loopback address, and show how checkdnsrr() answers a yes/no DNS question.

PHP
<?php
echo 'localhost IP: ', gethostbyname('localhost'), PHP_EOL;

$ips = gethostbynamel('localhost');
echo 'localhost list: ', $ips ? implode(', ', $ips) : 'none', PHP_EOL;

echo 'reverse 127.0.0.1: ', gethostbyaddr('127.0.0.1'), PHP_EOL;

// Illustrative public name: result is true/false from DNS
echo 'example.com has A?: ', checkdnsrr('example.com', 'A') ? 'yes' : 'no', PHP_EOL;

echo 'this host: ', gethostname(), PHP_EOL;
?>

How It Works

  1. gethostbyname('localhost') asks for one IPv4 address. On a normal machine that is 127.0.0.1.
  2. gethostbynamel() returns every IPv4 address for the name as an array. Here there is one entry, so implode prints the same address.
  3. gethostbyaddr('127.0.0.1') does the reverse lookup and typically returns localhost.
  4. checkdnsrr('example.com', 'A') returns a boolean: does DNS currently advertise an A record? The sample output shows yes.
  5. gethostname() prints this machine's host name. Your value will differ; the sample uses codetofun-dev as a stand-in.

Example 2 — HTTP headers and cookies

Set a status code and Content-Type, register a cookie, then list the headers PHP has queued (run this before any other output).

PHP
<?php
http_response_code(201);
header('Content-Type: text/plain; charset=UTF-8');
header('X-Tutorial: network');
setcookie('lesson', 'headers', [
    'path'     => '/',
    'httponly' => true,
]);

echo 'status: ', http_response_code(), PHP_EOL;
echo 'sent?: ', headers_sent() ? 'yes' : 'no', PHP_EOL;

foreach (headers_list() as $line) {
    echo $line, PHP_EOL;
}
?>
header() Tutorial

How It Works

  1. http_response_code(201) sets the response status. Calling it again with no argument prints the current code, 201.
  2. header() queues plain header lines. They leave with the response as long as no body was printed yet.
  3. setcookie() adds a Set-Cookie header. The options array sets path and HttpOnly in modern PHP.
  4. headers_sent() is still no here because the echo lines come after the header calls in this script—until the first byte of body is flushed, you can still add headers.
  5. headers_list() returns the headers PHP has prepared. Cookie lines appear as Set-Cookie: ... in that list.

Example 3 — IP address conversion

Convert an IPv4 address to a number and back, then pack and unpack the same address with inet_pton() / inet_ntop().

PHP
<?php
$ip = '127.0.0.1';

$num = ip2long($ip);
echo 'ip2long: ', $num, PHP_EOL;
echo 'long2ip: ', long2ip($num), PHP_EOL;

$bin = inet_pton($ip);
echo 'inet_pton bytes: ', strlen($bin), PHP_EOL;
echo 'inet_ntop: ', inet_ntop($bin), PHP_EOL;

$v6 = inet_pton('::1');
echo 'IPv6 ::1 bytes: ', strlen($v6), PHP_EOL;
echo 'IPv6 text: ', inet_ntop($v6), PHP_EOL;

echo 'bad IPv4?: ', ip2long('999.1.1.1') === false ? 'false' : 'ok', PHP_EOL;
?>

How It Works

  1. ip2long('127.0.0.1') turns the dotted address into the integer 2130706433. long2ip() reverses that exactly.
  2. inet_pton() packs the same IPv4 address into 4 bytes. inet_ntop() turns the binary form back into text.
  3. For IPv6, inet_pton('::1') uses 16 bytes. That is why these two functions are the better choice when both families matter.
  4. ip2long('999.1.1.1') is invalid, so the call returns false. Always check the result before you store or compare it.
  5. When you only need IPv4 ranges in a database column, ip2long() / long2ip() are enough. Reach for inet_* as soon as IPv6 appears.

Next: PHP Network Functions Index

After you know DNS lookups, headers and cookies, and IP conversion, open the functions index for all 37 guides.

Start withWhy
checkdnsrr()Ask DNS whether a host has a given record type
gethostbyname()Resolve a host name to one IPv4 address
header()Send an HTTP response header before any body output
setcookie()Set a cookie as a response header
ip2long()Convert an IPv4 address to an integer
fsockopen()Open a TCP or SSL stream to a remote host
openlog()Open a connection to the system logger

Full list: PHP Network Functions index (/php/network/function).

Frequently Asked Questions

They are the built-in PHP functions for everyday network work: DNS and host lookups, protocol and service name tables, HTTP response headers and cookies, IP address conversion, TCP sockets with fsockopen(), writing to syslog, and (in PHP 8.4) reading the last HTTP response headers and parsing a request body with request_parse_body().
Start with the DNS helpers gethostbyname() and checkdnsrr() so you understand host names versus IP addresses. Then learn header() and setcookie() for web responses, and ip2long() with long2ip() for IPv4 conversion. Open sockets and syslog after those basics feel clear.
None in practice. dns_check_record() is an alias of checkdnsrr(). Both ask the DNS for a record type (A, MX, and so on) and return true or false. Prefer the shorter name checkdnsrr() in new code, and treat the alias page as the same idea.
HTTP headers must leave PHP before any body output. If you echo, print HTML, or have a blank line before <?php, headers_sent() becomes true and later header() or setcookie() calls fail. Call them first, or buffer output with ob_start() when you need to decide headers later.
PHP 8.4 adds http_get_last_response_headers() and http_clear_last_response_headers() to inspect headers from the last HTTP wrapper request, and request_parse_body() to parse multipart or URL-encoded request bodies into $_POST and $_FILES style data. Check your PHP version before you rely on them.
Use fsockopen() or pfsockopen() when you need a raw TCP (or SSL) stream and want to speak a simple protocol yourself. For everyday HTTP APIs, prefer stream wrappers, cURL, or an HTTP client library. The socket_* network aliases are older names for stream helpers such as stream_get_meta_data().

Browse every Network function

Open the functions index for categorized guides with examples and FAQs.

Network Functions Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful