Day 27 – Advanced Streams

Zend PHP Certification

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_options = stream_context_create(array(
  1.   'http' => array('user_agent' => "Firefox.. kinda")
  2. ));
  3.  
  4. $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:

// Server
  1. $sock = stream_socket_sever("tcp://0.0.0.0:6652");
  2. while ($conn = stream_socket_accept($sock)) {
  3.   fwrite($conn, "Hi there!\n");
  4.   fclose($conn);
  5. }
  6. fclose($sock);
  7.  
  8. // Client
  9. $sock = stream_socket_client("tcp://0.0.0.0:6652");
  10. while ($line = fread($sock, 100))
  11.   echo $line;
  12.  
  13. 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!

No Comments

Leave a Reply

Allowed tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>



  • Donate

    If my work has helped you and you want to return the favor, you could purchase something for me from my Amazon Wish List or send me a donation via PayPal.

  • License

    Unless otherwise noted, all source code and compiled files published on this website are released under the terms of the GNU Lesser General Public License.