SlideShare une entreprise Scribd logo
1  sur  43
Télécharger pour lire hors ligne
GET SOAKED
AN IN-DEPTH LOOK AT STREAMS
DAVEY SHAFIK
                    Applications Developer for
                  Higher Education
                     Author of Zend PHP 5
                  Certification Study Guide &
                  Sitepoints PHP Anthology: 101
                  Essential Tips, Tricks & Hacks
Davey Shafik.com




                    A long time contributor to
                  PEAR, phpdoc; new contributor
                  to internals, FCKEditor
                    Original Contributor to Zend
                  Framework
                    Hard of hearing. Speak up!
                    (Buy my books!)
STREAM BASICS
                        IN
Davey Shafik.com




                    5 MINUTES
PHP STREAMS LAYER
                                 ALL
                              Input/Ouput




                             PHP Streams
                                Layer
Davey Shafik.com




                             Stream Filters




                   Stream      Stream
                   Context     Wrapper




                                Stream
                               Transport
Davey Shafik.com




            INPUT/OUTPUT
INPUT/OUTPUT

                    include/require, and _once variants
Davey Shafik.com




                     fopen, fread, fgets, fgetcsv, fputcsv, fwrite,
                  fclose, feof, etc
                    file_get_contents, file_put_contents,
                  readfile, file
                    mkdir, rename, unlink
                    EVERYTHING!
STREAM FILTERS
Davey Shafik.com




                      [SUCK!]
STREAM FILTERS [SUCK!]
                    Modify Data on-the-fly as it passes through
                  the stream
                     Appended/Removed on-the-fly
                      To the top and bottom of the stack
                     Can be chained
Davey Shafik.com




                     Defaults:
                      string.* (useless)
                      convert.* (near-useless)
                      zlib.*, bzip2.* (not-quite useless)
                     mcrypt.*, mdecrypt.* (unfortunately, the
                    most useful of the lot)
STREAM WRAPPERS
Davey Shafik.com
STREAM WRAPPERS
                  Several Built-in by default
                   file:, http:, ftp:, data: (5.2+), glob: (5.3+)
Davey Shafik.com




                   With openssl extension: https:, ftps:
                   With zlib extension: zlib:
                   Special php:// stream
                     stdin/stdout/stderr/input/output
                     memory/temp
                     filter
STREAM TRANSPORTS
Davey Shafik.com
STREAM TRANSPORTS

                  TCP
Davey Shafik.com




                  UTP
                  UNIX/UDG
                  + SSL, SSLv2, SSLv3 or TLS
                   HTTPS is TCP+SSL (1, 2, or 3)
STREAM CONTEXTS
Davey Shafik.com
STREAM CONTEXTS
                  Provides Context (duh) to stream wrappers
                   Configuration (options)
Davey Shafik.com




                    Request Type (HEAD, POST, GET)
                    Login Credentials
                    Headers, etc
                   Parameters
                    notification (callbacks)
                    ... options (as in, the same as above!)
Davey Shafik.com




            USING STREAMS
HEAD REQUEST
                  <?php
                  // Define our context options
                  $options = array(
                      // We use a nested array like:
                      // $options['stream_wrapper']['option'] = 'value';
                      'http' => array(
Davey Shafik.com




                          'method' => 'HEAD'
                      )
                  );

                  // Create the stream context
                  $context = stream_context_create($options);

                  // Pass it into readfile()
                  readfile(quot;http://daveyshafik.comquot;, false, $context);

                  // Check out the headers
                  var_dump($http_response_header);
                  ?>
array(12) {
                    [0]=>
                    string(15)   quot;HTTP/1.1 200 OKquot;
                    [1]=>
                    string(35)   quot;Date: Sun, 20 Apr 2008 20:50:35 GMTquot;
                    [2]=>
                    string(55)   quot;Server: Apache/2.2.6 (Debian) DAV/2 SVN/1.4.2 PHP/5.2.5quot;
                    [3]=>
                    string(23)   quot;X-Powered-By: PHP/5.2.5quot;
                    [4]=>
                    string(62)   quot;Set-Cookie: PHPSESSID=11581e823753213e5c8f36730f034; path=/quot;
                    [5]=>
Davey Shafik.com




                    string(10)   quot;Expires: 0quot;
                    [6]=>
                    string(50)   quot;Cache-Control: no-cache, pre-check=0, post-check=0quot;
                    [7]=>
                    string(16)   quot;Pragma: no-cachequot;
                    [8]=>
                    string(22)   quot;X-Session-Reinit: truequot;
                    [9]=>
                    string(19)   quot;X-Blog: Serendipityquot;
                    [10]=>
                    string(17)   quot;Connection: closequot;
                    [11]=>
                    string(43)   quot;Content-Type: text/html; charset=ISO-8859-1quot;
                  }
HEAD REQUEST (2)
                  <?php
                  $options = array(
                      'http' => array(
                          'method' => 'HEAD'
                      )
                  );
Davey Shafik.com




                  $context = stream_context_create($options);

                  // This time we use fopen()
                  $stream = fopen(
                              quot;http://daveyshafik.comquot;, quot;rquot;,
                              null, $context);

                  // and stream_get_meta_data()
                  $meta = stream_get_meta_data($stream);

                  var_dump($meta);
                  ?>
array(10) {
                    [quot;wrapper_dataquot;]=>
                    array(12) {
                      // The same as before
                    }
                    [quot;wrapper_typequot;]=>
                    string(4) quot;httpquot;
                    [quot;stream_typequot;]=>
                    string(10) quot;tcp_socketquot;
                    [quot;modequot;]=>
                    string(2) quot;r+quot;
Davey Shafik.com




                    [quot;unread_bytesquot;]=>
                    int(0)
                    [quot;seekablequot;]=>
                    bool(false)
                    [quot;uriquot;]=>
                    string(27) quot;http://pixelated-dreams.comquot;
                    [quot;timed_outquot;]=>
                    bool(false)
                    [quot;blockedquot;]=>
                    bool(true)
                    [quot;eofquot;]=>
                    bool(true)
                  }
POST REQUEST
                  <?php
                  // The data to send
                  $data = array('username' => 'davey', 'password' => 'example');

                  // Our context options array
                  $options = array (
                      'http' => array (
Davey Shafik.com




                          'method' => 'POST',
                          'header'=>
                          quot;Content-type: application/x-www-form-urlencodedrnquot;
                          . quot;Content-Length: quot; . strlen($urlencoded) . quot;rnquot;,
                          'content' => http_build_query($data)
                      )
                  );

                  $context = stream_context_create($options);

                  $url = $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'];

                  echo file_get_contents(quot;http://example.orgquot;, false, $context);
                  ?>
FTP APPEND TO FILE
                  <?php
                  $user = quot;phpquot;;
                  $pass = quot;streamsquot;;
                  $host = quot;localhostquot;;
                  $file = quot;example/lipsum.txtquot;;
                  $scheme = (extension_loaded('openssl')) ? 'ftps' : 'ftp';
Davey Shafik.com




                  $data = 'Donec condimentum leo id mi. Ut luctus mi pellentesque lor
                  em.';

                  $r = file_put_contents(
                                          quot;$scheme://$user:$pass@$host/$filequot;,
                                           $data,
                                          FILE_APPEND
                                      );

                  if ($r === false) {
                      echo quot;An error occured!quot;;
                  }
                  ?>
FTP FILE PERMISSIONS
                  <?php
                  $user = quot;phpquot;;
                  $pass = quot;streamsquot;;
                  $host = quot;localhostquot;;
                  $file = quot;example/lipsum.txtquot;;
                  $scheme = (extension_loaded('openssl')) ? 'ftps' : 'ftp';
Davey Shafik.com




                  $file = quot;$scheme://$user:$pass@$host/$filequot;;

                  if (is_readable($file)) {
                      echo quot;We can read the file, quot;;
                      if (is_writable($file)) {
                          echo quot;and we can write to it too!quot;;
                      } else {
                          echo quot;but we can't write to it!quot;;
                      }
                  } else {
                      echo quot;We canna read the file cap'n!quot;;
                  }
                  ?>
[NOT SO] PRACTICAL
                  EXAMPLE — TWITTER
Davey Shafik.com




                        CLIENT
WOULDN’T IT BE
Davey Shafik.com




                     NICE...
<html>
                      <head>
                          <meta http-equiv=quot;Content-Typequot; content=quot;text/html; charset=utf-8quot;>
                      </head>
                      <body>
                          <h1>Tweets</h1>
                          <h2>Public Tweets</h2>
                          <ul>
                          <?php
                          foreach (file(quot;tweet://publicquot;) as $tweet) {
                              echo quot;<li>quot; .$tweet. quot;</li>quot;;
                          }
                          ?>
                          </ul>
                          <h2>Search for #works</h2>
Davey Shafik.com




                          <ul>
                          <?php
                              foreach (file(quot;tweet://search/#worksquot;) as $tweet) {
                                  echo quot;<li>quot; .$tweet. quot;</li>quot;;
                              }
                          ?>
                          </ul>
                          <h2>Search for PHP and Python</h2>
                          <ul>
                          <?php
                              foreach (file(quot;tweet://search/php/pythonquot;) as $tweet) {
                                  echo quot;<li>quot; .$tweet. quot;</li>quot;;
                              }
                          ?>
                          </ul>
                      </body>
                  </html>
Output: http://daveyshafik.com/~davey/
                  twitter.html
Davey Shafik.com




                    Source: http://daveyshafik.com/~davey/
                  twitter.phps
SOMETHING MORE
Davey Shafik.com




                   PRACTICAL? OK!
Davey Shafik.com




            INTERFACES
<?php
                  interface Stream_Interface {
                      public function stream_open($path,$mode,$options,&$opened_path);

                      public function stream_close();

                      public function stream_read($count);

                      public function stream_write($data);
Davey Shafik.com




                      public function stream_eof();

                      public function stream_tell();

                      public function stream_seek($offset, $whence);

                      public function stream_stat();

                      public function url_stat($path, $flags);
                  }
                  ?>
<?php
                  interface Stream_Interface_Directory {
                      public function dir_opendir($path, $options);
                      
                      public function dir_readdir();
                      
Davey Shafik.com




                      public function dir_rewinddir();
                      
                      public function dir_closedir();
                      
                      public function mkdir($path, $mode, $options);
                      
                      public function rmdir($path, $options);
                  }
                  ?>
<?php
                  interface Stream_Interface_RenameUnlink {
Davey Shafik.com




                      public function rename($path_from, $path_to);
                      
                      public function unlink($path);
                  }
                  ?>
<?php
Davey Shafik.com




                  interface Stream_Interface_Flush {
                      public function stream_flush();
                  }
                  ?>
Davey Shafik.com




            CACHING
<?php
                  // Set the Context
                  // The 'cache' directory in the current dir
                  $dsn = 'file://' .realpath('./') .DIRECTORY_SEPARATOR. 'cache';
                  $options = array(
                      'cache' => array(
                          'dsn' => $dsn, // the cache directory
                          'ttl' => 86400, // One day
                      )
                  );

                  // Use stream_context_GET_default() in PHP versions lower than 5.3
                  stream_context_set_default($options);
Davey Shafik.com




                  if (file_exists('cache://blogroll.htm')) {
                      readfile('cache://blogroll.htm');
                  } else {
                      $pdo = new PDO($dsn);
                      $sql = quot;SELECT * FROM blogroll WHERE blog_id=:idquot;;
                      $query = $pdo->prepare($sql);
                      $query->execute(array(':id' => $CONFIG['blog_id']));
                      $html = '';
                      foreach ($query->fetchObj() as $url) {
                          $html .= quot;<a href='$url->link'>$url->name</a>quot;; 
                      }
                      file_put_contents('cache://blogroll.htm', $html);
                      echo $html;
                  }
                  ?>
    public function stream_stat()
                      {
                          // Run the fstat on the actual file
                          $stat = fstat($this->fp);

                          // Determine if the file has expired
                          $ttl = $this->context_options['ttl'];
                          if ($stat && $stat['mtime'] < time() - $ttl) {
                              // Pretend the file doesn't exist
Davey Shafik.com




                              $unlink = unlink($this->file);
                              if ($unlink) {
                                   $msg = __METHOD__ . quot;() Unable to removequot;;
                                  $msg .= quot;stale cache ($this->file)quot;
                                  trigger_error($msg, E_USER_NOTICE);
                              }
                              return false;
                          } else {
                              // Return the real stat
                              return $stat;
                          }
                      }
public function url_stat($path, $flags)
                      {
                          // If there is no context, grab the default
                          if (is_null($this->context)) {
                              $this->context = stream_context_get_default();
                          }
                          
                          // Retrieve just our context
                           $options = stream_context_get_options($this->context);
                          $this->context_options = $options['cache'];
                          
                          $file = $this->context_options['dsn'];
                          $file .= DIRECTORY_SEPARATOR;
                          $file .= str_replace(quot;cache://quot;, quot;quot;, $path);
                          $fp = @fopen($file, quot;rquot;);
Davey Shafik.com




                          
                          if (!$fp) {
                              return false;
                          }
                          
                          $stat = fstat($fp);
                          
                          // If the file's modification time is less than
                          // the current time minus the time to live, the
                          // file has expired.
                          $ttl = $this->context_options['ttl'];
                          if ($stat['mtime'] < (time() - $ttl)) {
                              // Remove the file and pretend the file doesn't exist
                              unlink($file);
                              return false;
                          }

                          return $stat;
                      }
WHAT’S THE POINT?
Davey Shafik.com
<?php
                  // Set the Context
                  // The 'cache' directory in the current dir
                  $dsn = 'mysql://username:password@localhost/cache';
                  $options = array(
                      'cache' => array(
                          'dsn' => $dsn, // the cache directory
                          'ttl' => 86400, // One day
                      )
                  );

                  // Use stream_context_GET_default() in PHP versions lower than 5.3
                  stream_context_set_default($options);
Davey Shafik.com




                  if (file_exists('cache://blogroll.htm')) {
                      readfile('cache://blogroll.htm');
                  } else {
                      $pdo = new PDO($dsn);
                      $sql = quot;SELECT * FROM blogroll WHERE blog_id=:idquot;;
                      $query = $pdo->prepare($sql);
                      $query->execute(array(':id' => $CONFIG['blog_id']));
                      $html = '';
                      foreach ($query->fetchObj() as $url) {
                          $html .= quot;<a href='$url->link'>$url->name</a>quot;; 
                      }
                      file_put_contents('cache://blogroll.htm', $html);
                      echo $html;
                  }
                  ?>
PHP 5.3 CHANGES
Davey Shafik.com




                       STUFF
Streams can be put in the include path:

                     set_include_path(“.:/lib:phar://my.phar”);
Davey Shafik.com




                    PHAR is include by default [woohoo!]

                    stream_context_SET_default() [my first
                  patch :)]
Davey Shafik.com




            PHAR
Phar archives are single-file applications that

                    work without extraction:

                     php blah.phar

                     include 'blah.phar';
Davey Shafik.com




                     include 'phar://blah.phar/internal/file.php';

                    Phar archives are tar, zip, or custom phar file
                  format

                     Native PHAR format is the fastest.

                    Stable: Used for PEAR for a long time!
Comments? http://joind.in/talk/view/30

                  E-mail: davey@php.net
Davey Shafik.com




                  Blog: http://daveyshafik.com

                  Twitter: http://twitter.com/dshafik

Contenu connexe

Tendances

Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128PrinceGuru MS
 
PSGI and Plack from first principles
PSGI and Plack from first principlesPSGI and Plack from first principles
PSGI and Plack from first principlesPerl Careers
 
Php web backdoor obfuscation
Php web backdoor obfuscationPhp web backdoor obfuscation
Php web backdoor obfuscationSandro Zaccarini
 
A reviravolta do desenvolvimento web
A reviravolta do desenvolvimento webA reviravolta do desenvolvimento web
A reviravolta do desenvolvimento webWallace Reis
 
PHP Backdoor: The rise of the vuln
PHP Backdoor: The rise of the vulnPHP Backdoor: The rise of the vuln
PHP Backdoor: The rise of the vulnSandro Zaccarini
 
Practical Testing of Ruby Core
Practical Testing of Ruby CorePractical Testing of Ruby Core
Practical Testing of Ruby CoreHiroshi SHIBATA
 
Ten modules I haven't yet talked about
Ten modules I haven't yet talked aboutTen modules I haven't yet talked about
Ten modules I haven't yet talked aboutacme
 
Code obfuscation, php shells & more
Code obfuscation, php shells & moreCode obfuscation, php shells & more
Code obfuscation, php shells & moreMattias Geniar
 
Php on the desktop and php gtk2
Php on the desktop and php gtk2Php on the desktop and php gtk2
Php on the desktop and php gtk2Elizabeth Smith
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I thinkWim Godden
 
HTTP Caching and PHP
HTTP Caching and PHPHTTP Caching and PHP
HTTP Caching and PHPDavid de Boer
 
The symfony platform: Create your very own framework (PHP Quebec 2008)
The symfony platform: Create your very own framework (PHP Quebec 2008)The symfony platform: Create your very own framework (PHP Quebec 2008)
The symfony platform: Create your very own framework (PHP Quebec 2008)Fabien Potencier
 
The promise of asynchronous php
The promise of asynchronous phpThe promise of asynchronous php
The promise of asynchronous phpWim Godden
 

Tendances (20)

Php tips-and-tricks4128
Php tips-and-tricks4128Php tips-and-tricks4128
Php tips-and-tricks4128
 
PSGI and Plack from first principles
PSGI and Plack from first principlesPSGI and Plack from first principles
PSGI and Plack from first principles
 
Php security3895
Php security3895Php security3895
Php security3895
 
Php web backdoor obfuscation
Php web backdoor obfuscationPhp web backdoor obfuscation
Php web backdoor obfuscation
 
A reviravolta do desenvolvimento web
A reviravolta do desenvolvimento webA reviravolta do desenvolvimento web
A reviravolta do desenvolvimento web
 
PHP Backdoor: The rise of the vuln
PHP Backdoor: The rise of the vulnPHP Backdoor: The rise of the vuln
PHP Backdoor: The rise of the vuln
 
Php on Windows
Php on WindowsPhp on Windows
Php on Windows
 
Practical Testing of Ruby Core
Practical Testing of Ruby CorePractical Testing of Ruby Core
Practical Testing of Ruby Core
 
Ten modules I haven't yet talked about
Ten modules I haven't yet talked aboutTen modules I haven't yet talked about
Ten modules I haven't yet talked about
 
Code obfuscation, php shells & more
Code obfuscation, php shells & moreCode obfuscation, php shells & more
Code obfuscation, php shells & more
 
Php on the desktop and php gtk2
Php on the desktop and php gtk2Php on the desktop and php gtk2
Php on the desktop and php gtk2
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
Little Big Ruby
Little Big RubyLittle Big Ruby
Little Big Ruby
 
Lca05
Lca05Lca05
Lca05
 
Modern Perl
Modern PerlModern Perl
Modern Perl
 
HTTP Caching and PHP
HTTP Caching and PHPHTTP Caching and PHP
HTTP Caching and PHP
 
The Loop
The LoopThe Loop
The Loop
 
The symfony platform: Create your very own framework (PHP Quebec 2008)
The symfony platform: Create your very own framework (PHP Quebec 2008)The symfony platform: Create your very own framework (PHP Quebec 2008)
The symfony platform: Create your very own framework (PHP Quebec 2008)
 
The promise of asynchronous php
The promise of asynchronous phpThe promise of asynchronous php
The promise of asynchronous php
 
Accelerated Stylesheets
Accelerated StylesheetsAccelerated Stylesheets
Accelerated Stylesheets
 

En vedette

Why elasticsearch rocks!
Why elasticsearch rocks!Why elasticsearch rocks!
Why elasticsearch rocks!tlrx
 
Techniques d'accélération des pages web
Techniques d'accélération des pages webTechniques d'accélération des pages web
Techniques d'accélération des pages webJean-Pierre Vincent
 
Automation using-phing
Automation using-phingAutomation using-phing
Automation using-phingRajat Pandit
 
Electrify your code with PHP Generators
Electrify your code with PHP GeneratorsElectrify your code with PHP Generators
Electrify your code with PHP GeneratorsMark Baker
 
The quest for global design principles (SymfonyLive Berlin 2015)
The quest for global design principles (SymfonyLive Berlin 2015)The quest for global design principles (SymfonyLive Berlin 2015)
The quest for global design principles (SymfonyLive Berlin 2015)Matthias Noback
 
Top tips my_sql_performance
Top tips my_sql_performanceTop tips my_sql_performance
Top tips my_sql_performanceafup Paris
 
Understanding Craftsmanship SwanseaCon2015
Understanding Craftsmanship SwanseaCon2015Understanding Craftsmanship SwanseaCon2015
Understanding Craftsmanship SwanseaCon2015Marcello Duarte
 
Si le tdd est mort alors pratiquons une autopsie mix-it 2015
Si le tdd est mort alors pratiquons une autopsie mix-it 2015Si le tdd est mort alors pratiquons une autopsie mix-it 2015
Si le tdd est mort alors pratiquons une autopsie mix-it 2015Bruno Boucard
 
Writing infinite scalability web applications with PHP and PostgreSQL
Writing infinite scalability web applications with PHP and PostgreSQLWriting infinite scalability web applications with PHP and PostgreSQL
Writing infinite scalability web applications with PHP and PostgreSQLGabriele Bartolini
 
L'ABC du BDD (Behavior Driven Development)
L'ABC du BDD (Behavior Driven Development)L'ABC du BDD (Behavior Driven Development)
L'ABC du BDD (Behavior Driven Development)Arnauld Loyer
 
Performance serveur et apache
Performance serveur et apachePerformance serveur et apache
Performance serveur et apacheafup Paris
 
TDD with PhpSpec - Lone Star PHP 2016
TDD with PhpSpec - Lone Star PHP 2016TDD with PhpSpec - Lone Star PHP 2016
TDD with PhpSpec - Lone Star PHP 2016CiaranMcNulty
 
The Wonderful World of Symfony Components
The Wonderful World of Symfony ComponentsThe Wonderful World of Symfony Components
The Wonderful World of Symfony ComponentsRyan Weaver
 
PHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4DevelopersPHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4DevelopersKacper Gunia
 

En vedette (20)

Why elasticsearch rocks!
Why elasticsearch rocks!Why elasticsearch rocks!
Why elasticsearch rocks!
 
Techniques d'accélération des pages web
Techniques d'accélération des pages webTechniques d'accélération des pages web
Techniques d'accélération des pages web
 
Diving deep into twig
Diving deep into twigDiving deep into twig
Diving deep into twig
 
Elastic Searching With PHP
Elastic Searching With PHPElastic Searching With PHP
Elastic Searching With PHP
 
Automation using-phing
Automation using-phingAutomation using-phing
Automation using-phing
 
PHP5.5 is Here
PHP5.5 is HerePHP5.5 is Here
PHP5.5 is Here
 
Electrify your code with PHP Generators
Electrify your code with PHP GeneratorsElectrify your code with PHP Generators
Electrify your code with PHP Generators
 
The quest for global design principles (SymfonyLive Berlin 2015)
The quest for global design principles (SymfonyLive Berlin 2015)The quest for global design principles (SymfonyLive Berlin 2015)
The quest for global design principles (SymfonyLive Berlin 2015)
 
Top tips my_sql_performance
Top tips my_sql_performanceTop tips my_sql_performance
Top tips my_sql_performance
 
Mocking Demystified
Mocking DemystifiedMocking Demystified
Mocking Demystified
 
Understanding Craftsmanship SwanseaCon2015
Understanding Craftsmanship SwanseaCon2015Understanding Craftsmanship SwanseaCon2015
Understanding Craftsmanship SwanseaCon2015
 
Si le tdd est mort alors pratiquons une autopsie mix-it 2015
Si le tdd est mort alors pratiquons une autopsie mix-it 2015Si le tdd est mort alors pratiquons une autopsie mix-it 2015
Si le tdd est mort alors pratiquons une autopsie mix-it 2015
 
Writing infinite scalability web applications with PHP and PostgreSQL
Writing infinite scalability web applications with PHP and PostgreSQLWriting infinite scalability web applications with PHP and PostgreSQL
Writing infinite scalability web applications with PHP and PostgreSQL
 
L'ABC du BDD (Behavior Driven Development)
L'ABC du BDD (Behavior Driven Development)L'ABC du BDD (Behavior Driven Development)
L'ABC du BDD (Behavior Driven Development)
 
Caching on the Edge
Caching on the EdgeCaching on the Edge
Caching on the Edge
 
Performance serveur et apache
Performance serveur et apachePerformance serveur et apache
Performance serveur et apache
 
Behat 3.0 meetup (March)
Behat 3.0 meetup (March)Behat 3.0 meetup (March)
Behat 3.0 meetup (March)
 
TDD with PhpSpec - Lone Star PHP 2016
TDD with PhpSpec - Lone Star PHP 2016TDD with PhpSpec - Lone Star PHP 2016
TDD with PhpSpec - Lone Star PHP 2016
 
The Wonderful World of Symfony Components
The Wonderful World of Symfony ComponentsThe Wonderful World of Symfony Components
The Wonderful World of Symfony Components
 
PHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4DevelopersPHPSpec - the only Design Tool you need - 4Developers
PHPSpec - the only Design Tool you need - 4Developers
 

Similaire à Get Soaked - An In Depth Look At PHP Streams

Express Presentation
Express PresentationExpress Presentation
Express Presentationaaronheckmann
 
Apache and PHP: Why httpd.conf is your new BFF!
Apache and PHP: Why httpd.conf is your new BFF!Apache and PHP: Why httpd.conf is your new BFF!
Apache and PHP: Why httpd.conf is your new BFF!Jeff Jones
 
Quick Intro To JRuby
Quick Intro To JRubyQuick Intro To JRuby
Quick Intro To JRubyFrederic Jean
 
Open Source Ajax Solution @OSDC.tw 2009
Open Source Ajax  Solution @OSDC.tw 2009Open Source Ajax  Solution @OSDC.tw 2009
Open Source Ajax Solution @OSDC.tw 2009Robbie Cheng
 
All I Need to Know I Learned by Writing My Own Web Framework
All I Need to Know I Learned by Writing My Own Web FrameworkAll I Need to Know I Learned by Writing My Own Web Framework
All I Need to Know I Learned by Writing My Own Web FrameworkBen Scofield
 
My First Rails Plugin - Usertext
My First Rails Plugin - UsertextMy First Rails Plugin - Usertext
My First Rails Plugin - Usertextfrankieroberto
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebookguoqing75
 
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...BradNeuberg
 
Using and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareUsing and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareAlona Mekhovova
 
Charla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo WebCharla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo WebMikel Torres Ugarte
 
Scalalable Language for a Scalable Web
Scalalable Language for a Scalable WebScalalable Language for a Scalable Web
Scalalable Language for a Scalable WebTimothy Perrett
 
Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统yiditushe
 
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHPKing Foo
 
PHP Basics and Demo HackU
PHP Basics and Demo HackUPHP Basics and Demo HackU
PHP Basics and Demo HackUAnshu Prateek
 

Similaire à Get Soaked - An In Depth Look At PHP Streams (20)

Rack Middleware
Rack MiddlewareRack Middleware
Rack Middleware
 
Express Presentation
Express PresentationExpress Presentation
Express Presentation
 
Apache and PHP: Why httpd.conf is your new BFF!
Apache and PHP: Why httpd.conf is your new BFF!Apache and PHP: Why httpd.conf is your new BFF!
Apache and PHP: Why httpd.conf is your new BFF!
 
Quick Intro To JRuby
Quick Intro To JRubyQuick Intro To JRuby
Quick Intro To JRuby
 
Sinatra
SinatraSinatra
Sinatra
 
Open Source Ajax Solution @OSDC.tw 2009
Open Source Ajax  Solution @OSDC.tw 2009Open Source Ajax  Solution @OSDC.tw 2009
Open Source Ajax Solution @OSDC.tw 2009
 
All I Need to Know I Learned by Writing My Own Web Framework
All I Need to Know I Learned by Writing My Own Web FrameworkAll I Need to Know I Learned by Writing My Own Web Framework
All I Need to Know I Learned by Writing My Own Web Framework
 
Php Security
Php SecurityPhp Security
Php Security
 
My First Rails Plugin - Usertext
My First Rails Plugin - UsertextMy First Rails Plugin - Usertext
My First Rails Plugin - Usertext
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook
 
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
Beyond Cookies, Persistent Storage For Web Applications Web Directions North ...
 
Using and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareUsing and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middleware
 
Memcached Study
Memcached StudyMemcached Study
Memcached Study
 
Charla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo WebCharla EHU Noviembre 2014 - Desarrollo Web
Charla EHU Noviembre 2014 - Desarrollo Web
 
Pecl Picks
Pecl PicksPecl Picks
Pecl Picks
 
Scalalable Language for a Scalable Web
Scalalable Language for a Scalable WebScalalable Language for a Scalable Web
Scalalable Language for a Scalable Web
 
Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统
 
Smarty
SmartySmarty
Smarty
 
Implementing Comet using PHP
Implementing Comet using PHPImplementing Comet using PHP
Implementing Comet using PHP
 
PHP Basics and Demo HackU
PHP Basics and Demo HackUPHP Basics and Demo HackU
PHP Basics and Demo HackU
 

Dernier

Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioChristian Posta
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxGDSC PJATK
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaborationbruanjhuli
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostMatt Ray
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPathCommunity
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding TeamAdam Moalla
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesMd Hossain Ali
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?IES VE
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024D Cloud Solutions
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAshyamraj55
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXTarek Kalaji
 

Dernier (20)

Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and Istio
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptx
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
201610817 - edge part1
201610817 - edge part1201610817 - edge part1
201610817 - edge part1
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation Developers
 
20150722 - AGV
20150722 - AGV20150722 - AGV
20150722 - AGV
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
 
VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBX
 

Get Soaked - An In Depth Look At PHP Streams

  • 1. GET SOAKED AN IN-DEPTH LOOK AT STREAMS
  • 2. DAVEY SHAFIK Applications Developer for Higher Education Author of Zend PHP 5 Certification Study Guide & Sitepoints PHP Anthology: 101 Essential Tips, Tricks & Hacks Davey Shafik.com A long time contributor to PEAR, phpdoc; new contributor to internals, FCKEditor Original Contributor to Zend Framework Hard of hearing. Speak up! (Buy my books!)
  • 3. STREAM BASICS IN Davey Shafik.com 5 MINUTES
  • 4. PHP STREAMS LAYER ALL Input/Ouput PHP Streams Layer Davey Shafik.com Stream Filters Stream Stream Context Wrapper Stream Transport
  • 5. Davey Shafik.com INPUT/OUTPUT
  • 6. INPUT/OUTPUT include/require, and _once variants Davey Shafik.com fopen, fread, fgets, fgetcsv, fputcsv, fwrite, fclose, feof, etc file_get_contents, file_put_contents, readfile, file mkdir, rename, unlink EVERYTHING!
  • 8. STREAM FILTERS [SUCK!] Modify Data on-the-fly as it passes through the stream Appended/Removed on-the-fly To the top and bottom of the stack Can be chained Davey Shafik.com Defaults: string.* (useless) convert.* (near-useless) zlib.*, bzip2.* (not-quite useless) mcrypt.*, mdecrypt.* (unfortunately, the most useful of the lot)
  • 10. STREAM WRAPPERS Several Built-in by default file:, http:, ftp:, data: (5.2+), glob: (5.3+) Davey Shafik.com With openssl extension: https:, ftps: With zlib extension: zlib: Special php:// stream stdin/stdout/stderr/input/output memory/temp filter
  • 12. STREAM TRANSPORTS TCP Davey Shafik.com UTP UNIX/UDG + SSL, SSLv2, SSLv3 or TLS HTTPS is TCP+SSL (1, 2, or 3)
  • 14. STREAM CONTEXTS Provides Context (duh) to stream wrappers Configuration (options) Davey Shafik.com Request Type (HEAD, POST, GET) Login Credentials Headers, etc Parameters notification (callbacks) ... options (as in, the same as above!)
  • 15. Davey Shafik.com USING STREAMS
  • 16. HEAD REQUEST <?php // Define our context options $options = array(     // We use a nested array like:     // $options['stream_wrapper']['option'] = 'value';     'http' => array( Davey Shafik.com         'method' => 'HEAD'     ) ); // Create the stream context $context = stream_context_create($options); // Pass it into readfile() readfile(quot;http://daveyshafik.comquot;, false, $context); // Check out the headers var_dump($http_response_header); ?>
  • 17. array(12) { [0]=> string(15) quot;HTTP/1.1 200 OKquot; [1]=> string(35) quot;Date: Sun, 20 Apr 2008 20:50:35 GMTquot; [2]=> string(55) quot;Server: Apache/2.2.6 (Debian) DAV/2 SVN/1.4.2 PHP/5.2.5quot; [3]=> string(23) quot;X-Powered-By: PHP/5.2.5quot; [4]=> string(62) quot;Set-Cookie: PHPSESSID=11581e823753213e5c8f36730f034; path=/quot; [5]=> Davey Shafik.com string(10) quot;Expires: 0quot; [6]=> string(50) quot;Cache-Control: no-cache, pre-check=0, post-check=0quot; [7]=> string(16) quot;Pragma: no-cachequot; [8]=> string(22) quot;X-Session-Reinit: truequot; [9]=> string(19) quot;X-Blog: Serendipityquot; [10]=> string(17) quot;Connection: closequot; [11]=> string(43) quot;Content-Type: text/html; charset=ISO-8859-1quot; }
  • 18. HEAD REQUEST (2) <?php $options = array(     'http' => array(         'method' => 'HEAD'     ) ); Davey Shafik.com $context = stream_context_create($options); // This time we use fopen() $stream = fopen( quot;http://daveyshafik.comquot;, quot;rquot;, null, $context); // and stream_get_meta_data() $meta = stream_get_meta_data($stream); var_dump($meta); ?>
  • 19. array(10) { [quot;wrapper_dataquot;]=> array(12) { // The same as before } [quot;wrapper_typequot;]=> string(4) quot;httpquot; [quot;stream_typequot;]=> string(10) quot;tcp_socketquot; [quot;modequot;]=> string(2) quot;r+quot; Davey Shafik.com [quot;unread_bytesquot;]=> int(0) [quot;seekablequot;]=> bool(false) [quot;uriquot;]=> string(27) quot;http://pixelated-dreams.comquot; [quot;timed_outquot;]=> bool(false) [quot;blockedquot;]=> bool(true) [quot;eofquot;]=> bool(true) }
  • 20. POST REQUEST <?php // The data to send $data = array('username' => 'davey', 'password' => 'example'); // Our context options array $options = array (     'http' => array ( Davey Shafik.com         'method' => 'POST',         'header'=>         quot;Content-type: application/x-www-form-urlencodedrnquot;         . quot;Content-Length: quot; . strlen($urlencoded) . quot;rnquot;,         'content' => http_build_query($data)     ) ); $context = stream_context_create($options); $url = $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME']; echo file_get_contents(quot;http://example.orgquot;, false, $context); ?>
  • 21. FTP APPEND TO FILE <?php $user = quot;phpquot;; $pass = quot;streamsquot;; $host = quot;localhostquot;; $file = quot;example/lipsum.txtquot;; $scheme = (extension_loaded('openssl')) ? 'ftps' : 'ftp'; Davey Shafik.com $data = 'Donec condimentum leo id mi. Ut luctus mi pellentesque lor em.'; $r = file_put_contents(                         quot;$scheme://$user:$pass@$host/$filequot;,                          $data,                         FILE_APPEND                     ); if ($r === false) {     echo quot;An error occured!quot;; } ?>
  • 22. FTP FILE PERMISSIONS <?php $user = quot;phpquot;; $pass = quot;streamsquot;; $host = quot;localhostquot;; $file = quot;example/lipsum.txtquot;; $scheme = (extension_loaded('openssl')) ? 'ftps' : 'ftp'; Davey Shafik.com $file = quot;$scheme://$user:$pass@$host/$filequot;; if (is_readable($file)) {     echo quot;We can read the file, quot;;     if (is_writable($file)) {         echo quot;and we can write to it too!quot;;     } else {         echo quot;but we can't write to it!quot;;     } } else {     echo quot;We canna read the file cap'n!quot;; } ?>
  • 23. [NOT SO] PRACTICAL EXAMPLE — TWITTER Davey Shafik.com CLIENT
  • 24. WOULDN’T IT BE Davey Shafik.com NICE...
  • 25. <html>     <head>         <meta http-equiv=quot;Content-Typequot; content=quot;text/html; charset=utf-8quot;>     </head>     <body>         <h1>Tweets</h1>         <h2>Public Tweets</h2>         <ul>         <?php         foreach (file(quot;tweet://publicquot;) as $tweet) {             echo quot;<li>quot; .$tweet. quot;</li>quot;;         }         ?>         </ul>         <h2>Search for #works</h2> Davey Shafik.com         <ul>         <?php             foreach (file(quot;tweet://search/#worksquot;) as $tweet) {                 echo quot;<li>quot; .$tweet. quot;</li>quot;;             }         ?>         </ul>         <h2>Search for PHP and Python</h2>         <ul>         <?php             foreach (file(quot;tweet://search/php/pythonquot;) as $tweet) {                 echo quot;<li>quot; .$tweet. quot;</li>quot;;             }         ?>         </ul>     </body> </html>
  • 26. Output: http://daveyshafik.com/~davey/ twitter.html Davey Shafik.com Source: http://daveyshafik.com/~davey/ twitter.phps
  • 28. Davey Shafik.com INTERFACES
  • 29. <?php interface Stream_Interface {     public function stream_open($path,$mode,$options,&$opened_path);     public function stream_close();     public function stream_read($count);     public function stream_write($data); Davey Shafik.com     public function stream_eof();     public function stream_tell();     public function stream_seek($offset, $whence);     public function stream_stat();     public function url_stat($path, $flags); } ?>
  • 30. <?php interface Stream_Interface_Directory {     public function dir_opendir($path, $options);          public function dir_readdir();      Davey Shafik.com     public function dir_rewinddir();          public function dir_closedir();          public function mkdir($path, $mode, $options);          public function rmdir($path, $options); } ?>
  • 31. <?php interface Stream_Interface_RenameUnlink { Davey Shafik.com     public function rename($path_from, $path_to);          public function unlink($path); } ?>
  • 32. <?php Davey Shafik.com interface Stream_Interface_Flush {     public function stream_flush(); } ?>
  • 33. Davey Shafik.com CACHING
  • 34. <?php // Set the Context // The 'cache' directory in the current dir $dsn = 'file://' .realpath('./') .DIRECTORY_SEPARATOR. 'cache'; $options = array(     'cache' => array(         'dsn' => $dsn, // the cache directory         'ttl' => 86400, // One day     ) ); // Use stream_context_GET_default() in PHP versions lower than 5.3 stream_context_set_default($options); Davey Shafik.com if (file_exists('cache://blogroll.htm')) {     readfile('cache://blogroll.htm'); } else {     $pdo = new PDO($dsn);     $sql = quot;SELECT * FROM blogroll WHERE blog_id=:idquot;;     $query = $pdo->prepare($sql);     $query->execute(array(':id' => $CONFIG['blog_id']));     $html = '';     foreach ($query->fetchObj() as $url) {         $html .= quot;<a href='$url->link'>$url->name</a>quot;;      }     file_put_contents('cache://blogroll.htm', $html);     echo $html; } ?>
  • 35.     public function stream_stat()     {         // Run the fstat on the actual file         $stat = fstat($this->fp);         // Determine if the file has expired         $ttl = $this->context_options['ttl'];         if ($stat && $stat['mtime'] < time() - $ttl) {             // Pretend the file doesn't exist Davey Shafik.com             $unlink = unlink($this->file);             if ($unlink) { $msg = __METHOD__ . quot;() Unable to removequot;;                 $msg .= quot;stale cache ($this->file)quot;                 trigger_error($msg, E_USER_NOTICE);             }             return false;         } else {             // Return the real stat             return $stat;         }     }
  • 36. public function url_stat($path, $flags)     {         // If there is no context, grab the default         if (is_null($this->context)) {             $this->context = stream_context_get_default();         }                  // Retrieve just our context          $options = stream_context_get_options($this->context);         $this->context_options = $options['cache'];                  $file = $this->context_options['dsn'];         $file .= DIRECTORY_SEPARATOR;         $file .= str_replace(quot;cache://quot;, quot;quot;, $path);         $fp = @fopen($file, quot;rquot;); Davey Shafik.com                  if (!$fp) {             return false;         }                  $stat = fstat($fp);                  // If the file's modification time is less than         // the current time minus the time to live, the         // file has expired.         $ttl = $this->context_options['ttl'];         if ($stat['mtime'] < (time() - $ttl)) {             // Remove the file and pretend the file doesn't exist             unlink($file);             return false;         }         return $stat;     }
  • 38. <?php // Set the Context // The 'cache' directory in the current dir $dsn = 'mysql://username:password@localhost/cache'; $options = array(     'cache' => array(         'dsn' => $dsn, // the cache directory         'ttl' => 86400, // One day     ) ); // Use stream_context_GET_default() in PHP versions lower than 5.3 stream_context_set_default($options); Davey Shafik.com if (file_exists('cache://blogroll.htm')) {     readfile('cache://blogroll.htm'); } else {     $pdo = new PDO($dsn);     $sql = quot;SELECT * FROM blogroll WHERE blog_id=:idquot;;     $query = $pdo->prepare($sql);     $query->execute(array(':id' => $CONFIG['blog_id']));     $html = '';     foreach ($query->fetchObj() as $url) {         $html .= quot;<a href='$url->link'>$url->name</a>quot;;      }     file_put_contents('cache://blogroll.htm', $html);     echo $html; } ?>
  • 39. PHP 5.3 CHANGES Davey Shafik.com STUFF
  • 40. Streams can be put in the include path: set_include_path(“.:/lib:phar://my.phar”); Davey Shafik.com PHAR is include by default [woohoo!] stream_context_SET_default() [my first patch :)]
  • 42. Phar archives are single-file applications that work without extraction: php blah.phar include 'blah.phar'; Davey Shafik.com include 'phar://blah.phar/internal/file.php'; Phar archives are tar, zip, or custom phar file format Native PHAR format is the fastest. Stable: Used for PEAR for a long time!
  • 43. Comments? http://joind.in/talk/view/30 E-mail: davey@php.net Davey Shafik.com Blog: http://daveyshafik.com Twitter: http://twitter.com/dshafik