Yesterday, I was explaining basic built-in streams. Today I’ll be covering the advanced modes. The first thing is basic network access (http, ftp, etc). Normally, you would just use fopen() or file_get_contents(). Well what would happen if you wanted to provide additional parameters to that call, like user agent? Meet stream_context_create():
-
'http' => array('user_agent' => "Firefox.. kinda")
-
));
-
-
$file = file_get_contents("http://www.google.com/", false, $http_options);
There is a LARGE list of options for each of the different stream wrappers (http://php.net/manual/en/context.php) but I’m not going to go into anymore of them. Moving on to the Advanced-Advanced stream access! What if you want to send/receive raw data to and from an TCP or UDP port on the internet? Well here’s your chance.
PHP allows you to create raw socket servers and clients at your leisure. Here is a basic client/server example:
-
$sock = stream_socket_sever("tcp://0.0.0.0:6652");
-
while ($conn = stream_socket_accept($sock)) {
-
fwrite($conn, "Hi there!\n");
-
fclose($conn);
-
}
-
fclose($sock);
-
-
// Client
-
$sock = stream_socket_client("tcp://0.0.0.0:6652");
-
while ($line = fread($sock, 100))
-
echo $line;
-
-
fclose($sock);
In this case, you can run the server from the command-line as a background process. It can then be coded to perform various operations based on the input from the client (be mindful of your max-execution-time).
According to the book, this is all I need to know. Tomorrow I’ll take some more of the practice exams and write down what I’m missing. Till then!

