Sunday, 26 August 2007

PHP Basics (Section 4) - Files

  1. Files provide a simple temporary to permanent data store.
  2. PHP5 presents two functions which make handling files, namely file_get_contents() and file_put_contents().
  3. For large amounts of data, or in issues where a race condition is possible a database would be a better data store.
  4. Steams are the way that PHP handles working with network resources.
  5. Whenever you open up a file PHP creates a stream in the background.
  6. Each stream consists of several components: file wrapper, one or two pipe-lines, an optional context, metadata about the stream.
  7. Files can be locked to prevent race conditions:
    flock($fp, LOCK_SH); //Place Shared lock
    flock($fp, LOCK_EX); //
    Place Exclusive (write) Lock
    flock($fp, LOCK_UN); //Release lock
  8. Placing and removing locks can inhibit performance as traffic increases, consider using a different data store.
  9. Using stream context and a few other techniques a lot can be done without resorting to sockets, however for more detailed control sockets can be used.
  10. Sockets allow read/write access to various socket connections, while things like HTTP may seem read only, at the protocol level information is being sent to identify the desired resource. Example:
    $fp = fsockopen
    ("", 80, $errno, $errstr, 30)
    if (!$fp) {
    echo "$errstr ($errno)\n";
    } else {
    $out = "GET / HTTP/1.1\r\n";
    $out .= "Host:\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);
    while (!feof($fp)) {
    echo fgets($fp, 128);
For more information, please read my another post Amazon S3 Makes My Document Management System Easier

No comments: