PHP - tutorial - 10 - network functions

revision:


Network functions let you manipulate information sent to the browser by the Web server.

checkdnsrr() - checks DNS records for type corresponding to host.

Syntax: checkdnsrr(host, type)

Parameter values:

host : required. Specifies an IP address or host name to check.

type : optional. Specifies the type. Can be one of the following: A, MX (default), NS, SOA, PTR, CNAME, AAAA, A6, SRV, NAPTR,TXT, ANY

example: check DNS records

Passed
code:
                <?php
                    $domain="w3schools.com";
                    if(checkdnsrr($domain,"MX")) {
                    echo "Passed";
                    } else {
                    echo "Failed";
                    }
                ?>
            

closelog() - closes the connection of system logger.

Syntax: closelog()

example:

code:
                <?php
                    function _log($text) {
                        openlog("phperrors", LOG_PID | LOG_PERROR);
                        syslog(LOG_ERR, $text);
                        closelog();
                        
                    }
                ?>

            

define_syslog_variables() - deprecated and removed in PHP 5.4. Initializes the variables used in syslog functions.

deprecated and removed in PHP 5.4

dns_check_record() - alias of checkdnsrr().

Syntax: dns_check_record(host, type)

Parameter values:

host : required. Specifies an IP address or host name to check.

type : optional. Specifies the type. Can be one of the following: A, MX (default), NS, SOA, PTR, CNAME, AAAA, A6, SRV, NAPTR,TXT, ANY

example:

Passed
code:
                <?php
                    $domain="w3schools.com";
                    if(dns_check_record($domain,"MX")) {
                    echo "Passed";
                    } else {
                    echo "Failed";
                    }
                ?>
            

dns_get_mx() - alias of getmxrr().

Syntax: dns_get_mx(host, mxhosts, weight)

Parameter values:

host : required. Specifies the host name

mxhosts : required. An array that specifies a list of MX records found

weight : optional. An array that specifies the weight information gathered

example:

0 => alt1.aspmx.l.google.com
1 => alt3.aspmx.l.google.com
2 => alt2.aspmx.l.google.com
3 => aspmx.l.google.com
4 => alt4.aspmx.l.google.com
5 => feedback-smtp.eu-west-1.amazonses.com
code:
                <?php
                    $domain="w3schools.com";
                    if(dns_get_mx($domain,$mx_details)){
                        foreach($mx_details as $key=>$value){
                            echo "$key => $value <br>";
                        }
                    }
                ?>

            

dns_get_record() - gets the DNS resource records associated with the specified hostname.

Syntax: dns_get_record(hostname, type, authns, addtl, raw)

Parameter values:

hostname : required. Specifies a hostname (like "www.w3schools.com")

type : optional. Specifies the resource record type to search for. Can be one of the following: DNS_A, DNS_CNAME, DNS_HINFO,DNS_CAA, DNS_MX, DNS_NS, DNS_PTR, DNS_SOA, DNS_TXT, DNS_AAAA, DNS_SRV, DNS_NAPTR, DNS_A6, DNS_ALL, DNS_ANY (default)

authns : optional. Passed by reference and, if set, it will be populated with Resource Records for the Authoritative Name Servers

addtl : optional. Passed by reference and, if set, it will be populated with any Additional Records

: optional. A Boolean value. If set to TRUE, it queries only the requested type instead of looping type-by-type before getting the info stuff. Default is FALSE

example:

Array ( [0] => Array ( [host] => w3schools.com [class] => IN [ttl] => 60 [type] => MX [pri] => 1 [target] => aspmx.l.google.com ) [1] => Array ( [host] => w3schools.com [class] => IN [ttl] => 60 [type] => MX [pri] => 5 [target] => alt1.aspmx.l.google.com ) [2] => Array ( [host] => w3schools.com [class] => IN [ttl] => 60 [type] => MX [pri] => 5 [target] => alt2.aspmx.l.google.com ) [3] => Array ( [host] => w3schools.com [class] => IN [ttl] => 60 [type] => MX [pri] => 10 [target] => alt3.aspmx.l.google.com ) [4] => Array ( [host] => w3schools.com [class] => IN [ttl] => 60 [type] => MX [pri] => 10 [target] => alt4.aspmx.l.google.com ) [5] => Array ( [host] => w3schools.com [class] => IN [ttl] => 60 [type] => MX [pri] => 10 [target] => feedback-smtp.eu-west-1.amazonses.com ) )
code:
                <?php
                    print_r(dns_get_record("w3schools.com", DNS_MX));
                ?>

            

fsockopen() - opens an Internet or Unix domain socket connection.

Syntax: fsockopen(hostname, port, errno, errstr, timeout)

Parameter values:

hostname : required. Specifies a hostname (like "www.w3schools.com"). ssl:// or tls:// works over TCP/IP to connect to the remote host

port : optional. Specifies the port number. Use -1 for transports that do not use ports, like unix://

errno : optional. Specifies the system level error number

errstr : optional. Specifies the error message as a string

timeout : optional. Specifies the connection timeout (in seconds)

example:

HTTP/1.1 200 OK Date: Sun, 29 Sep 2024 01:28:44 GMT Server: Apache/2 Upgrade: h2,h2c Connection: Upgrade, close Last-Modified: Thu, 28 Nov 2019 20:00:45 GMT ETag: "2c-5986d91a572a5" Accept-Ranges: bytes Content-Length: 44 Vary: User-Agent Content-Type: text/html Apache is functioning normally
code:
                <?php
                    $fp = fsockopen("www.lwitters.com", 80, $errno, $errstr, 20);
                    if (!$fp) {
                        echo "$errstr ($errno)<br>";
                    } else {
                        $out = "GET / HTTP/1.1\r\n";
                        $out .= "Host: www.w3schools.com\r\n";
                        $out .= "Connection: Close\r\n\r\n";
                        fwrite($fp, $out);
                        while (!feof($fp)) {
                            echo fgets($fp, 128);
                        }
                        fclose($fp);
                    }
                ?>

            

gethostbyaddr() - returns the domain name for a given IP address.

Syntax: gethostbyaddr(ipaddress)

Parameter values:

ipaddress : required. Specifies an IP address

example:

ec2-18-189-178-53.us-east-2.compute.amazonaws.com
code:
                <?php
                    $host = gethostbyaddr($_SERVER["REMOTE_ADDR"]);
                    echo $host;
                ?>

            

gethostbyname() - returns the IPv4 address for a given domain/host name.

Syntax: gethostbyname(hostname)

Parameter values:

hostname : required. Specifies a hostname (like "www.w3schools.com")

example:

192.229.173.207
code:
                <?php
                    $ip = gethostbyname("www.w3schools.com");
                    echo $ip;
                ?>

            

gethostbynamel() - returns a list of IPv4 address for a given domain/host name.

Syntax: gethostbynamel(hostname)

Parameter values:

hostname : required. Specifies a hostname (like "www.w3schools.com")

example:

Array ( [0] => 192.229.173.207 )
code:
                <?php
                    $hostlist = gethostbynamel("www.w3schools.com");
                    print_r($hostlist);
                ?>

            

gethostname() - returns the host name.

Syntax: gethostname()

example:

dallas-1.anuson.net
code:
                <?php
                    echo gethostname(); 
                ?>

            

getmxrr() - returns the MX records for the specified internet host name.

Syntax: getmxrr(host, mxhosts, weight)

Parameter values:

host : required. Specifies the host name

mxhosts : required. An array that specifies a list of MX records found

weight : otional. An array that specifies the weight information gathered

example:

0 => aspmx.l.google.com
1 => alt3.aspmx.l.google.com
2 => alt4.aspmx.l.google.com
3 => feedback-smtp.eu-west-1.amazonses.com
4 => alt1.aspmx.l.google.com
5 => alt2.aspmx.l.google.com
code:
                <?php
                    $domain="w3schools.com";
                    if(getmxrr($domain,$mx_details)){
                    foreach($mx_details as $key=>$value){
                        echo "$key => $value <br>";
                    }
                    }
                ?>
            

getprotobyname() - returns the protocol number for a given protocol name.

Syntax: getprotobyname(protocolname)

Parameter values:

protocolname : required. Specifies a protocol name (like "tcp")

example:

6
code:
                <?php
                    $protocolnum = getprotobyname("tcp");
                    echo $protocolnum;
                ?>

            

getprotobynumber() - returns the protocol name for a given protocol number.

Syntax: getprotobynumber(protocolnumber)

Parameter values:

protocolnumber : required. Specifies a protocol number (like 17)

example:

tcp
code:
                <?php
                    $protocolname = getprotobynumber(6);
                    echo $protocolname;
                ?>

            

getservbyname() - returns the port number for a given Internet service and protocol.

Syntax: getservbyname(service, protocol)

Parameter values:

service : required. Specifies the Internet service name (like "http")

protocol : required. Specifies a protocol name (like "tcp" or "udp")

example:

80
code:
                <?php
                    $portnum = getservbyname("http", "tcp");
                    echo $portnum;
                ?>

            

getservbyport() - returns the Internet service for a given port and protocol.

Syntax: getservbyport(port, protocol)

Parameter values:

port : required. Specifies the port number (like 80)

protocol : required. Specifies a protocol name (like "tcp" or "udp")

example:

http
code:
                <?php
                    $intservname = getservbyport(80, "tcp");
                    echo $intservname;
                ?>

            

header_register_callback() - calls a header function.

Syntax: header_register_callback(callback)

Parameter values:

callback : required. Specifies a callback function

example:

header_remove() - removes an HTTP header previously set with the header() function.

Syntax: header_remove(headername)

Parameter values:

headername : optional. Specifies a header name to be removed. If omitted, all previously set headers are removed

example:

code:
                <?php
                    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
                    header("Cache-Control: no-cache");
                    header("Pragma: no-cache");

                    header_remove("Pragma");
                ?>
            

header() - sends a raw HTTP header to a client.

Syntax: header(header, replace, http_response_code)

Parameter values:

header : required. Specifies the header string to send

replace : optional. Indicates whether the header should replace a previous similar header or add a new header of the same type. Default is TRUE (will replace). FALSE allows multiple headers of the same type

http_response_code : optional. Forces the HTTP response code to the specified value

It is important to notice that the header() function must be called before any actual output is sent!

example:

code:
                <?php
                    // Date in the past
                    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
                    header("Cache-Control: no-cache");
                    header("Pragma: no-cache");
                ?>

            

headers_list() - returns a list of response headers to be sent to the browser.

example:

code:
                <?php
                    setcookie("TestCookie","SomeValue");
                    header("X-Sample-Test: foo");
                    header("Content-type: text/plain");
                ?>
                <?php
                    var_dump(headers_list());
                ?>
            

headers_sent() - checks if/where headers have been sent.

Syntax: headers_sent(file,line)

Parameter values:

file : optional. If the file and line parameters are set, headers_sent() will put the PHP source file name and line number where output started in the file and line variables

line : optional. Specifies the line number where the output started

example:

code:
                <?php
                    if (!headers_sent()) {
                        header("Location: https://www.w3schools.com/");
                        exit;
                    }   
                ?>
            

http_response_code() - sets or returns the HTTP response status code.

Syntax: http_response_code(code)

Parameter values:

code : optional. Specifies a response code (like 404)

example:

code:
                <?php
                    http_response_code(404);
                ?>
            

inet_ntop() - converts a 32bit IPv4 or 128bit IPv6 address into a readable format.

Syntax: inet_ntop(address)

Parameter values:

address : required. Specifies a 32bit IPv4 or 128bit IPv6 address

example:

127.0.1.1
code:
                <?php
                    $addr = chr(127) . chr(0) . chr(1) . chr(1);
                    $exp = inet_ntop($addr);
                    echo $exp; 
                ?>

            

inet_pton() - converts a readable IP address into a packed 32bit IPv4 or 128bit IPv6 format.

Syntax: inet_pton(address)

Parameter values:

address : required. Specifies a readable IP address

example:


code:
                <?php
                    $addr = inet_pton("127.0.1.1");
                    echo $addr;
                ?>

            

ip2long() - converts an IPv4 address into a long integer.

Syntax: ip2long(address)

Parameter values:

address : required. Specifies a readable IP address

example:

The following URLs are equivalent:
https://www.w3schools.com/, https://192.229.173.207/, and https://3236277711/
code:
                <?php
                    $ip = gethostbyname("www.w3schools.com");
                    $out = "The following URLs are equivalent:<br>";
                    $out .= "https://www.w3schools.com/, https://" . $ip . "/, and https://" . sprintf("%u", ip2long($ip)) . "/";
                    echo $out;
                ?>

            

long2ip() - converts a long integer address into a string in IPv4 format.

Syntax: long2ip(address)

Parameter values:

address : required. Specifies a long integer that represents an IP address

example:

41.148.72.0
code:
                <?php
                    echo(long2ip(344294967296));
                ?>

            

openlog() - opens the connection of system logger.

Syntax: openlog(ident, option, facility)

Parameter values:

ident : required. Specifies a string ident that is added to each message

option : required. Specifies what logging options will be used when generating a log message. Can be one or more of the following options (separated with |): LOG_CONS, LOG_NDELAY, LOG_ODELAY, LOG_PERROR, LOG_PID

facility : required. Specifies what type of program is logging the message:LOG_AUTH, LOG_AUTHPRIV, LOG_CRON, LOG_DAEMON, LOG_KERN, LOG_LOCAL0...LOG_LOCAL7, LOG_LPR, LOG_MAIL, LOG_NEWS, LOG_SYSLOG, LOG_USER - (is the only valid log type for Windows OS), LOG_UUCP

example:

code:
                <?php
                    function _log($text) {
                        openlog("phperrors", LOG_PID | LOG_PERROR);
                        syslog(LOG_ERR, $text);
                        closelog();
                    }
                ?>

            

pfsockopen() - opens a persistent Internet or Unix domain socket connection.

Syntax: pfsockopen(hostname, port, errno, errstr, timeout)

Parameter values:

hostname : required. Specifies a hostname (like "www.w3schools.com"). ssl:// or tls:// works over TCP/IP to connect to the remote host

port : optional. Specifies the port number. Use -1 for transports that do not use ports, like unix://

errno : optional. Specifies the system level error number

errstr : optional. Specifies the error message as a string

timeout : optional. Specifies the connection timeout (in seconds)

example:

HTTP/1.1 301 Moved Permanently Date: Sun, 29 Sep 2024 01:28:45 GMT Server: Apache/2 Location: https://www.lwitters.com/ Content-Length: 233 Connection: close Content-Type: text/html; charset=iso-8859-1 301 Moved Permanently

Moved Permanently

The document has moved here.

code:
                <?php
                    $fp = pfsockopen("www.lwitters.com", 80, $errno, $errstr, 20);
                    if (!$fp) {
                        echo "$errstr ($errno)<br>";
                    } else {
                        $out = "GET / HTTP/1.1\r\n";
                        $out .= "Host: www.lwitters.com\r\n";
                        $out .= "Connection: Close\r\n\r\n";
                        fwrite($fp, $out);
                        while (!feof($fp)) {
                        echo fgets($fp, 128);
                        }
                        fclose($fp);
                    } 
                ?>

            

setcookie() - defines a cookie to be sent along with the rest of the HTTP headers.

Syntax: setcookie(name, value, expire, path, domain, secure, httponly);

Parameter values:

name : required. Specifies the name of the cookie

value : optional. Specifies the value of the cookie

expire : optional. Specifies when the cookie expires. The value: time()+86400*30, will set the cookie to expire in 30 days. If this parameter is omitted or set to 0, the cookie will expire at the end of the session (when the browser closes). Default is 0

path : optional. Specifies the server path of the cookie. If set to "/", the cookie will be available within the entire domain. If set to "/php/", the cookie will only be available within the php directory and all sub-directories of php. The default value is the current directory that the cookie is being set in

domain : optional. Specifies the domain name of the cookie. To make the cookie available on all subdomains of example.com, set domain to "example.com". Setting it to www.example.com will make the cookie only available in the www subdomain

secure : optional. Specifies whether or not the cookie should only be transmitted over a secure HTTPS connection. TRUE indicates that the cookie will only be set if a secure connection exists. Default is FALSE

httponly : optional. If set to TRUE the cookie will be accessible only through the HTTP protocol (the cookie will not be accessible by scripting languages). This setting can help to reduce identity theft through XSS attacks. Default is FALSE

example:

code:
                <?php
                    $cookie_name = "user";
                    $cookie_value = "John Doe";
                    setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
                    ?>
                    <html>
                    <body>

                    <?php
                    if(!isset($_COOKIE[$cookie_name])) {
                        echo "Cookie named '" . $cookie_name . "' is not set!";
                    } else {
                        echo "Cookie '" . $cookie_name . "' is set!<br>";
                        echo "Value is: " . $_COOKIE[$cookie_name];
                    }
                
                ?>

            

setrawcookie() - defines a cookie (without URL encoding) to be sent along with the rest of the HTTP headers.

Syntax: setrawcookie(name, value, expire, path, domain, secure);

Parameter values:

name : required. Specifies the name of the cookie

value : optional. Specifies the value of the cookie

expire : optional. Specifies when the cookie expires. The value: time()+86400*30, will set the cookie to expire in 30 days. If this parameter is omitted or set to 0, the cookie will expire at the end of the session (when the browser closes). Default is 0

path : optional. Specifies the server path of the cookie. If set to "/", the cookie will be available within the entire domain. If set to "/php/", the cookie will only be available within the php directory and all sub-directories of php. The default value is the current directory that the cookie is being set in

domain : optional. Specifies the domain name of the cookie. To make the cookie available on all subdomains of example.com, set domain to "example.com". Setting it to www.example.com will make the cookie only available in the www subdomain

secure : optional. Specifies whether or not the cookie should only be transmitted over a secure HTTPS connection. TRUE indicates that the cookie will only be set if a secure connection exists. Default is FALSE

example:

code:
                <?php
                $cookie_name = "user";
                $cookie_value = "John";
                setrawcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
                // 86400 = 1 day
                ?>
                <html>
                <body>

                <?php
                    echo "Cookie is set.";
                ?>
            

socket_get_status() - alias of stream_get_meta_data().

socket_set_blocking() - alias of stream_set_blocking().

socket_set_timeout() - alias of stream_set_timeout().

syslog() - generates a system log message.

Syntax: syslog(priority, message)

Parameter values:

priority : required. Specifies ... Can be one of the following options:LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG

message : required. Specifies the message to send

example:

code:
                <?php
                    function _log($text) {
                        openlog("phperrors", LOG_PID | LOG_PERROR);
                        syslog(LOG_ERR, $text);
                        closelog(); 
                    }
                ?>