In the Internet of Things machines talk to machines. How can we use PHP on the command line to get the server talk to another machine? The answer is sockets. A network socket is a communication flow across a computer network. Minimal requirements: an IP number and a port number. Based on Unix BSD sockets, the PHP functions socket_create(), socket_connect() do just that.

In the following example the index page of google.nl is requested from one of the Google servers. The parameter AF_INET means the type is IPv4 for the IP number used, the parameter SOCK_STREAM means the protocol used is TCP. Once the connection is established, a HTTP GET request is sent and the response is stored in the buffer.

$sock = socket_create(AF_INET, SOCK_STREAM, 0);
socket_connect($sock , '173.194.65.113' , 80);
$out = "GET / HTTP/1.1\r\n";
$out .= "Host: www.google.nl\r\n";
$out .= "Connection: Close\r\n\r\n";
 
socket_send ( $sock , $out , strlen($out) , 0);
socket_recv ( $sock , $buf , 2045 , MSG_WAITALL );
echo $buf;

The response is a collection of response headers followed by the actual HTML content of the page. The header section looks like this:

HTTP/1.1 200 OK
Date: Sat, 19 Apr 2014 20:37:09 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=ISO-8859-1
Set-Cookie: PREF=ID=ee515721b9771324:FF=0:TM=1397939829:LM=1397939829:S=mLPvRWMGWW2QEHtk; expires=Mon, 18-Apr-2016 20:37:09 GMT; path=/; domain=.google.nl
Set-Cookie: NID=67=uOfzhPIUCiPdc2TOHMY10ZHfJ6Nb42rDxJFB4C6zNj34xMTGIJebSGLLi3povw5w0IiryTp0CKzjtHJWtxN7q_ogNXf4iM1Inh6bHD5gDOvnApTqrnUh1YqutrcV3yn3; expires=Sun, 19-Oct-2014 20:37:09 GMT; path=/; domain=.google.nl; HttpOnly
P3P: CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."
Server: gws
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Alternate-Protocol: 80:quic
Connection: close

This socket connection can not be used to create ssl connections.

The fsockopen() function is a socket_create() implementation. Requires less code to write but is also slower.

$fp = fsockopen("www.google.nl", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)
\n"; } else { $out = "GET / HTTP/1.1\r\n"; $out .= "Host: www.google.nl\r\n"; $out .= "Connection: Close\r\n\r\n"; fwrite($fp, $out); while (!feof($fp)) { echo fgets($fp, 128); } fclose($fp); }

On the other hand it is possible to create ssl connections. Simply use the ssl:// prefix as in $host = “ssl://” . $hostName. Be aware that ssl connections do not close! If you ask to code to continue to the end-of-file (feof) you will wait for eternity. The solution is presented here and boils down to continuing to read lines until a specific response is returned.

The function pfsockopen() is similar to fsockopen and adds persistence (connection stays open after script execution but in another way) to the connection.

The function fopen() does not open connections to other servers but will open a stream to a file for example for reading. This file can be an external file. The following code will again return the content of google.nl:

$fp = fopen("http://www.google.nl","r");
if (!$fp) {
    echo "$errstr ($errno)
\n"; } else { while (!feof($fp)) { echo fgets($fp, 128); } fclose($fp); }

This is different from the HTTP request issued by fsockopen() where the headers are returned first.

There is also the stream_socket_client() function that takes the same arguments as fsockopen(). It returns a stream resource so that other methods like fgets() and fputs() can work on it. Other functions that can directly read external files are file_get_contents() and readfile(). These functions can be modified with a context provided by stream_context_create() for adding header fields:

$opts = array(
  'http'=>array(
    'method'=>"POST",
    'header'  => 'Content-type: application/x-www-form-urlencoded',
'content' => 'comment=hi'
  )
);

$context = stream_context_create($opts);
$file = file_get_contents('http://www.example.com/', false, $context);

Via stream_context_create() it is also possible to use ssl in combination with a certificate.

cURL is a general-purpose command-line tool for transferring data with different protocols. PHP has several built-in curl functions provided the libcurl package is installed.

A cURL session is initiated by curl_init(), multiple options can be set by curl_setopt(), the session is performed using curl_exec() and closed with curl_close().

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.google.nl");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$output = curl_exec($ch);
curl_close($ch);
echo $output;

cURL allows posting to url’s and can handle ssl traffic.

Advertisements