Introduction to PHP streams

Streams is a feature of PHP that was introduced in PHP 4.3 to unify the methods for working on files, sockets, and other similar resources. PHP 4.3 came out a long time ago, but many PHP developers never learned how to properly use streams in PHP, much to my dismay. Many use cURL for accessing HTTP resources, but I’m not a huge fan of cURL, because it has an awful interface in PHP and it presents yet another dependency. While the HTTP stream handler in PHP isn’t perfect, it works very well for most situations.

To begin, let’s consider what examples of streams could be:

  • A file on a hard drive
  • A HTTP connection to a website
  • A UDP connection to a server
  • A ZIP file
  • A SSH tunnel
  • A Vorbis/OGG file

What are some common operations on all of those? Primarily, they share the ability to be read from and written to. The power of PHP’s streams is that you can access all of them using the same set of functions, and if there’s something you wish to “stream-ify,” you can write your own “stream wrapper.” In addition to reading and writing, the streams framework in PHP also allows for other operations, such as renaming and deleting.

Continue reading

Basic word wrapping with Imagick

The following is a simple greedy word-wrapping algorithm for ImageMagick in PHP.

Released under public domain.

$words = explode(" ", $msg);
$lines = array();
$current_line = "";
foreach ($words as $word) {
  if ($current_line == "") {
    $test = $word;
  } else {
    $test = "$current_line $word";
  }
  $metrics = $image->queryFontMetrics($draw, $test);
  if ($metrics['textWidth'] > $max_width) {
    if ($current_line == "") {
      $lines[] = $test;
      $current_line = "";
    } else {
      $lines[] = $current_line;
      $current_line = $word;
    }
  } else {
    $current_line = $test;
  }
}
if ($current_line != "") {
  $lines[] = $current_line;
}
$msg = implode("\n", $lines);

PHP function to draw wrapped text

Here’s a PHP code snippet that draws text bounded by a textbox. You’ll need GD with TrueType support.

The snippet supports rotation, vertical and horizontal alignments, configurable line heights and leading, word wrap, character wrap, and text outlining.

Continue reading