SlideShare une entreprise Scribd logo
1  sur  32
Télécharger pour lire hors ligne
It’s all streams these days



Friday, May 18, 12
GWoo

                     • PHP developer since 1999
                     • CakePHP 2005-2009
                     • Lithium 2009-present
                     • Engineer on Orchestra.io @ EngineYard
                     • On a boat

Friday, May 18, 12
Basics
                     http://php.net/manual/en/book.stream.php




Friday, May 18, 12
Input / Output
                 •   include/require, and *_once variants
                 •    fopen, fread, fgets, fgetcsv, fputcsv, fwrite,
                     fclose, feof, etc
                 •    file_get_contents, file_put_contents,
                     readfile, file
                 •   mkdir, rename, unlink
                 •   EVERYTHING!


Friday, May 18, 12
Layers
                     • Transports
                     • Wrappers
                     • Contexts
                     • Filters



Friday, May 18, 12
ALL
                                Input/Ouput




                               PHP Streams
                                  Layer




                               Stream Filters




                     Stream      Stream
                     Context     Wrapper




                                  Stream
                                 Transport




Friday, May 18, 12
Transports
                     http://php.net/manual/en/transports.php




Friday, May 18, 12
Transports
                     • socket clients
                     • “stream_set_blocking” non-blocking io




Friday, May 18, 12
Transports
                     ~: php -r "print_r(stream_get_transports());"
                     Array
                     (
                        [0] => tcp
                        [1] => udp
                        [2] => unix
                        [3] => udg
                        [4] => ssl
                        [5] => sslv3
                        [6] => sslv2
                        [7] => tls
                     )




Friday, May 18, 12
Example
            ~: php -r '$fp = stream_socket_client("tcp://php.net:80", $errno, $errstr); 
            > fwrite($fp, "HEAD / HTTP/1.0rnHost: php.netrnAccept: */*rnrn"); 
            > print_r(stream_get_contents($fp));'
            HTTP/1.1 200 OK
            Date: Fri, 18 May 2012 07:12:38 GMT
            Server: Apache/1.3.41 (Unix) PHP/5.2.17
            X-Powered-By: PHP/5.2.17
            Content-language: en
            Set-Cookie: COUNTRY=ITA%2C85.42.99.82; expires=Fri, 25-May-2012
            07:12:38 GMT; path=/; domain=.php.net
            Last-Modified: Fri, 18 May 2012 10:20:11 GMT
            Connection: close
            Content-Type: text/html;charset=utf-8



Friday, May 18, 12
Wrappers
                     http://php.net/manual/en/wrappers.php




Friday, May 18, 12
Wrappers
                     ~: php -r "print_r(stream_get_wrappers());"
                     Array
                     (
                        [0] => https
                        [1] => ftps
                        [2] => compress.zlib
                        [3] => compress.bzip2
                        [4] => php
                        [5] => file
                        [6] => glob
                        [7] => data
                        [8] => http
                        [9] => ftp
                        [10] => zip
                        [11] => phar
                     )


Friday, May 18, 12
Example

                     ~: php -r '$fp = fopen("php://temp", "w+"); 
                     > fwrite($fp, "hello world"); 
                     > rewind($fp); 
                     > print_r(stream_get_contents($fp));'
                     hello world




Friday, May 18, 12
Example
                     ~: php -r '$fp = fopen("php://stdout", "w"); 
                     > fwrite($fp, "hello world");'
                     hello world




Friday, May 18, 12
Contexts
                     http://php.net/manual/en/context.php




Friday, May 18, 12
Contexts


                     • A context is a set of parameters and
                       wrapper specific options that modify or
                       enhance the behavior of streams.




Friday, May 18, 12
Contexts
            ~: php -r '$http = array("method" => "HEAD"); 
            > readfile("http://php.net", false, stream_context_create(compact("http"))); 
            > print_r($http_response_header);'
            Array
            (
               [0] => HTTP/1.1 200 OK
               [1] => Date: Fri, 18 May 2012 07:25:32 GMT
               [2] => Server: Apache/1.3.41 (Unix) PHP/5.2.17
               [3] => X-Powered-By: PHP/5.2.17
               [4] => Content-language: en
               [5] => Set-Cookie: COUNTRY=ITA%2C85.42.99.82; expires=Fri, 25-
            May-2012 07:25:34 GMT; path=/; domain=.php.net
               [6] => Last-Modified: Fri, 18 May 2012 10:20:11 GMT
               [7] => Connection: close
               [8] => Content-Type: text/html;charset=utf-8
            )

Friday, May 18, 12
Filters
                     http://php.net/manual/en/filters.php




Friday, May 18, 12
Filters
                     • modify data while reading and/or writing
                     • appended and removed anytime
                     • chain filters as needed




Friday, May 18, 12
Default Filters
                     ~: php -r "print_r(stream_get_filters());"
                     Array
                     (
                        [0] => zlib.*
                        [1] => bzip2.*
                        [2] => convert.iconv.*
                        [3] => string.rot13
                        [4] => string.toupper
                        [5] => string.tolower
                        [6] => string.strip_tags
                        [7] => convert.*
                        [8] => consumed
                        [9] => dechunk
                        [10] => http.*
                     )


Friday, May 18, 12
Example
                $stream = fopen('data://text/plain,' . $body, 'r');
                stream_filter_append($stream, 'dechunk');
                return trim(stream_get_contents($stream));




Friday, May 18, 12
Custom Wrappers
                     http://php.net/manual/en/class.streamwrapper.php




Friday, May 18, 12
streamWrapper {
                        /* Properties */
                        public resource $context ;
                        /* Methods */
                        __construct ( void )
                        __destruct ( void )
                        public bool dir_closedir ( void )
                        public bool dir_opendir ( string $path , int $options )
                        public string dir_readdir ( void )
                        public bool dir_rewinddir ( void )
                        public bool mkdir ( string $path , int $mode , int $options )
                        public bool rename ( string $path_from , string $path_to )
                        public bool rmdir ( string $path , int $options )
                        public resource stream_cast ( int $cast_as )
                        public void stream_close ( void )
                        public bool stream_eof ( void )
                        public bool stream_flush ( void )
                        public bool stream_lock ( mode $operation )
                        public bool stream_metadata ( int $path , int $option , int $var )
                        public bool stream_open ( string $path , string $mode , int $options , string &$opened_path )
                        public string stream_read ( int $count )
                        public bool stream_seek ( int $offset , int $whence = SEEK_SET )
                        public bool stream_set_option ( int $option , int $arg1 , int $arg2 )
                        public array stream_stat ( void )
                        public int stream_tell ( void )
                        public bool stream_truncate ( int $new_size )
                        public int stream_write ( string $data )
                        public bool unlink ( string $path )
                        public array url_stat ( string $path , int $flags )
                     }



Friday, May 18, 12
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);

          	

        public function stream_eof();

          	

        public function stream_tell();

          	

        public function stream_seek($offset, $whence);

          	

        public function stream_stat();

          	

        public function url_stat($path, $flags);
          }


Friday, May 18, 12
class AutoEscapeStream implements Stream_Interface {

      }




Friday, May 18, 12
class AutoEscapeStream implements Stream_Interface {

                     	

   protected $_position = 0;

                     	

   protected $_stats = array();

                     	

   protected $_data = null;

                     	

   protected $_path = null;

                     }




Friday, May 18, 12
class AutoEscapeStream implements Stream_Interface {
                     ...
                         public function stream_open($path, $mode, $options, &$opened_path) {
                     	

    	

   $path = str_replace('escape://', '', $path);

                     	

   	

   if (empty($path)) {
                     	

   	

   	

   return false;
                     	

   	

   }
                     	

   	

   $success = ($this->_data = file_get_contents($path));
                     	

   	

   $this->_stats = stat($path);

                     	

   	

   if ($success === false) {
                     	

   	

   	

    return false;
                     	

   	

   }
                     	

   	

   $escEcho = '/<?=s*$this->(.+?)s*;?s*?>/ms';
                     	

   	

   $this->_data = preg_replace($escEcho, '<?php echo $this->$1; ?>', $this->_data);

                     	

   	

   $echo = '/<?=s*(.+?)s*;?s*?>/ms';
                     	

   	

   $this->_data = preg_replace($echo, '<?php echo $h($1); ?>', $this->_data);
                     	

   	

   return true;
                     	

   }

                     	

   public function stream_read($count) {
                     	

   	

    $result = substr($this->_data, $this->_position, $count);
                     	

   	

    $this->_position += strlen($result);
                     	

   	

    return $result;
                     	

   }

                     	

   public function stream_tell() {
                     	

   	

    return $this->_position;
                     	

   }

                     	

   public function stream_eof() {
                     	

   	

    return ($this->_position >= strlen($this->_data));
                     	

   }
Friday, May 18, 12
class AutoEscapeStream implements Stream_Interface {
                     ...	

                            public function stream_seek($offset, $whence) {
                     	

      	

    switch ($whence) {
                     	

      	

    	

    case SEEK_SET:
                     	

      	

    	

    	

    if ($offset < strlen($this->_data) && $offset >= 0) {
                     	

      	

    	

    	

    	

     $this->_position = $offset;
                     	

      	

    	

    	

    	

     return true;
                     	

      	

    	

    	

    }
                     	

      	

    	

    	

    return false;
                     	

      	

    	

    case SEEK_CUR:
                     	

      	

    	

    	

    if ($offset >= 0) {
                     	

      	

    	

    	

    	

     $this->_position += $offset;
                     	

      	

    	

    	

    	

     return true;
                     	

      	

    	

    	

    }
                     	

      	

    	

    	

    return false;
                     	

      	

    	

    case SEEK_END:
                     	

      	

    	

    	

    if (strlen($this->_data) + $offset >= 0) {
                     	

      	

    	

    	

    	

     $this->_position = strlen($this->_data) + $offset;
                     	

      	

    	

    	

    	

     return true;
                     	

      	

    	

    	

    }
                     	

      	

    	

    	

    return false;
                     	

      	

    	

    default:
                     	

      	

    }
                     	

      	

    return false;
                     	

      }

                     	

   public function stream_stat() {
                     	

   	

    return $this->_stats;
                     	

   }

                     	

   public function url_stat() {
                     	

   	

    return $this->_stats;
                     	

   }
Friday, May 18, 12
Using the Wrapper

                     stream_wrapper_register("escape", "AutoEscapeStream");
                     include("escape://template.php");




Friday, May 18, 12
Demo
                     • Using phar streams
                     • https://github.com/gwoo/sinatrium




Friday, May 18, 12
Questions?



Friday, May 18, 12
@gwoo

                     https://github.com/gwoo

                     THANKS!




Friday, May 18, 12

Contenu connexe

Tendances

Devinsampa nginx-scripting
Devinsampa nginx-scriptingDevinsampa nginx-scripting
Devinsampa nginx-scripting
Tony Fabeen
 
Introduction to PHP 5.3
Introduction to PHP 5.3Introduction to PHP 5.3
Introduction to PHP 5.3
guestcc91d4
 
fastcgi_conf and mime_types
fastcgi_conf and mime_typesfastcgi_conf and mime_types
fastcgi_conf and mime_types
Naoya Nakazawa
 
Github.com anton terekhov-orientdb-php
Github.com anton terekhov-orientdb-phpGithub.com anton terekhov-orientdb-php
Github.com anton terekhov-orientdb-php
San jay
 
Workshop eZ Publish Caching Mechanisms
Workshop eZ Publish Caching MechanismsWorkshop eZ Publish Caching Mechanisms
Workshop eZ Publish Caching Mechanisms
Kaliop-slide
 

Tendances (20)

Utility Modules That You Should Know About
Utility Modules That You Should Know AboutUtility Modules That You Should Know About
Utility Modules That You Should Know About
 
Devinsampa nginx-scripting
Devinsampa nginx-scriptingDevinsampa nginx-scripting
Devinsampa nginx-scripting
 
Introduction to PHP 5.3
Introduction to PHP 5.3Introduction to PHP 5.3
Introduction to PHP 5.3
 
groovy & grails - lecture 4
groovy & grails - lecture 4groovy & grails - lecture 4
groovy & grails - lecture 4
 
PHP language presentation
PHP language presentationPHP language presentation
PHP language presentation
 
On UnQLite
On UnQLiteOn UnQLite
On UnQLite
 
swift-nio のアーキテクチャーと RxHttpClient
swift-nio のアーキテクチャーと RxHttpClientswift-nio のアーキテクチャーと RxHttpClient
swift-nio のアーキテクチャーと RxHttpClient
 
groovy & grails - lecture 2
groovy & grails - lecture 2groovy & grails - lecture 2
groovy & grails - lecture 2
 
Propel Your PHP Applications
Propel Your PHP ApplicationsPropel Your PHP Applications
Propel Your PHP Applications
 
typemap in Perl/XS
typemap in Perl/XS  typemap in Perl/XS
typemap in Perl/XS
 
A History of PHP
A History of PHPA History of PHP
A History of PHP
 
Php7 hhvm and co
Php7 hhvm and coPhp7 hhvm and co
Php7 hhvm and co
 
fastcgi_conf and mime_types
fastcgi_conf and mime_typesfastcgi_conf and mime_types
fastcgi_conf and mime_types
 
Github.com anton terekhov-orientdb-php
Github.com anton terekhov-orientdb-phpGithub.com anton terekhov-orientdb-php
Github.com anton terekhov-orientdb-php
 
OWASP Proxy
OWASP ProxyOWASP Proxy
OWASP Proxy
 
Intro to pl/PHP Oscon2007
Intro to pl/PHP Oscon2007Intro to pl/PHP Oscon2007
Intro to pl/PHP Oscon2007
 
Php basic for vit university
Php basic for vit universityPhp basic for vit university
Php basic for vit university
 
Perl at SkyCon'12
Perl at SkyCon'12Perl at SkyCon'12
Perl at SkyCon'12
 
Workshop eZ Publish Caching Mechanisms
Workshop eZ Publish Caching MechanismsWorkshop eZ Publish Caching Mechanisms
Workshop eZ Publish Caching Mechanisms
 
PHP data structures (and the impact of php 7 on them), phpDay Verona 2015, Italy
PHP data structures (and the impact of php 7 on them), phpDay Verona 2015, ItalyPHP data structures (and the impact of php 7 on them), phpDay Verona 2015, Italy
PHP data structures (and the impact of php 7 on them), phpDay Verona 2015, Italy
 

En vedette

Spl in the wild - zendcon2012
Spl in the wild - zendcon2012Spl in the wild - zendcon2012
Spl in the wild - zendcon2012
Elizabeth Smith
 
Event and Signal Driven Programming Zendcon 2012
Event and Signal Driven Programming Zendcon 2012Event and Signal Driven Programming Zendcon 2012
Event and Signal Driven Programming Zendcon 2012
Elizabeth Smith
 
Mentoring developers - Zendcon 2012
Mentoring developers - Zendcon 2012Mentoring developers - Zendcon 2012
Mentoring developers - Zendcon 2012
Elizabeth Smith
 
Security is not a feature
Security is not a featureSecurity is not a feature
Security is not a feature
Elizabeth Smith
 
Socket programming with php
Socket programming with phpSocket programming with php
Socket programming with php
Elizabeth Smith
 

En vedette (18)

Spl in the wild - zendcon2012
Spl in the wild - zendcon2012Spl in the wild - zendcon2012
Spl in the wild - zendcon2012
 
Event and Signal Driven Programming Zendcon 2012
Event and Signal Driven Programming Zendcon 2012Event and Signal Driven Programming Zendcon 2012
Event and Signal Driven Programming Zendcon 2012
 
Using unicode with php
Using unicode with phpUsing unicode with php
Using unicode with php
 
Mentoring developers
Mentoring developersMentoring developers
Mentoring developers
 
Mentoring developers - Zendcon 2012
Mentoring developers - Zendcon 2012Mentoring developers - Zendcon 2012
Mentoring developers - Zendcon 2012
 
Security is not a feature
Security is not a featureSecurity is not a feature
Security is not a feature
 
Mentoring developers-php benelux-2014
Mentoring developers-php benelux-2014Mentoring developers-php benelux-2014
Mentoring developers-php benelux-2014
 
Do the mentor thing
Do the mentor thingDo the mentor thing
Do the mentor thing
 
Taming the resource tiger
Taming the resource tigerTaming the resource tiger
Taming the resource tiger
 
Taming the tiger - pnwphp
Taming the tiger - pnwphpTaming the tiger - pnwphp
Taming the tiger - pnwphp
 
Hacking with hhvm
Hacking with hhvmHacking with hhvm
Hacking with hhvm
 
Using unicode with php
Using unicode with phpUsing unicode with php
Using unicode with php
 
Mentoring developers
Mentoring developersMentoring developers
Mentoring developers
 
Php’s guts
Php’s gutsPhp’s guts
Php’s guts
 
Lexing and parsing
Lexing and parsingLexing and parsing
Lexing and parsing
 
Php internal architecture
Php internal architecturePhp internal architecture
Php internal architecture
 
Socket programming with php
Socket programming with phpSocket programming with php
Socket programming with php
 
Modern sql
Modern sqlModern sql
Modern sql
 

Similaire à PHP Streams

What's new in PHP 5.5
What's new in PHP 5.5What's new in PHP 5.5
What's new in PHP 5.5
Tom Corrigan
 
Auto-loading of Drupal CCK Nodes
Auto-loading of Drupal CCK NodesAuto-loading of Drupal CCK Nodes
Auto-loading of Drupal CCK Nodes
nihiliad
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
Iftekhar Eather
 
Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统
yiditushe
 
Tips
TipsTips
Tips
mclee
 
On secure application of PHP wrappers
On secure application  of PHP wrappersOn secure application  of PHP wrappers
On secure application of PHP wrappers
Positive Hack Days
 

Similaire à PHP Streams (20)

What's new in PHP 5.5
What's new in PHP 5.5What's new in PHP 5.5
What's new in PHP 5.5
 
Lca05
Lca05Lca05
Lca05
 
Perl Intro 6 Ftp
Perl Intro 6 FtpPerl Intro 6 Ftp
Perl Intro 6 Ftp
 
Auto-loading of Drupal CCK Nodes
Auto-loading of Drupal CCK NodesAuto-loading of Drupal CCK Nodes
Auto-loading of Drupal CCK Nodes
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
わかった気になるgitit-0.8
わかった気になるgitit-0.8わかった気になるgitit-0.8
わかった気になるgitit-0.8
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
 
PHP5.5 is Here
PHP5.5 is HerePHP5.5 is Here
PHP5.5 is Here
 
Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统
 
Pecl Picks
Pecl PicksPecl Picks
Pecl Picks
 
Tips
TipsTips
Tips
 
DevOps in PHP environment
DevOps in PHP environmentDevOps in PHP environment
DevOps in PHP environment
 
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
 
Key features PHP 5.3 - 5.6
Key features PHP 5.3 - 5.6Key features PHP 5.3 - 5.6
Key features PHP 5.3 - 5.6
 
Apache Dispatch
Apache DispatchApache Dispatch
Apache Dispatch
 
Building Testable PHP Applications
Building Testable PHP ApplicationsBuilding Testable PHP Applications
Building Testable PHP Applications
 
TYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase frameworkTYPO3 Extension development using new Extbase framework
TYPO3 Extension development using new Extbase framework
 
On secure application of PHP wrappers
On secure application  of PHP wrappersOn secure application  of PHP wrappers
On secure application of PHP wrappers
 
Configuration Surgery with Augeas
Configuration Surgery with AugeasConfiguration Surgery with Augeas
Configuration Surgery with Augeas
 
Augeas @RMLL 2012
Augeas @RMLL 2012Augeas @RMLL 2012
Augeas @RMLL 2012
 

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Dernier (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 

PHP Streams

  • 1. It’s all streams these days Friday, May 18, 12
  • 2. GWoo • PHP developer since 1999 • CakePHP 2005-2009 • Lithium 2009-present • Engineer on Orchestra.io @ EngineYard • On a boat Friday, May 18, 12
  • 3. Basics http://php.net/manual/en/book.stream.php Friday, May 18, 12
  • 4. Input / Output • include/require, and *_once variants • fopen, fread, fgets, fgetcsv, fputcsv, fwrite, fclose, feof, etc • file_get_contents, file_put_contents, readfile, file • mkdir, rename, unlink • EVERYTHING! Friday, May 18, 12
  • 5. Layers • Transports • Wrappers • Contexts • Filters Friday, May 18, 12
  • 6. ALL Input/Ouput PHP Streams Layer Stream Filters Stream Stream Context Wrapper Stream Transport Friday, May 18, 12
  • 7. Transports http://php.net/manual/en/transports.php Friday, May 18, 12
  • 8. Transports • socket clients • “stream_set_blocking” non-blocking io Friday, May 18, 12
  • 9. Transports ~: php -r "print_r(stream_get_transports());" Array ( [0] => tcp [1] => udp [2] => unix [3] => udg [4] => ssl [5] => sslv3 [6] => sslv2 [7] => tls ) Friday, May 18, 12
  • 10. Example ~: php -r '$fp = stream_socket_client("tcp://php.net:80", $errno, $errstr); > fwrite($fp, "HEAD / HTTP/1.0rnHost: php.netrnAccept: */*rnrn"); > print_r(stream_get_contents($fp));' HTTP/1.1 200 OK Date: Fri, 18 May 2012 07:12:38 GMT Server: Apache/1.3.41 (Unix) PHP/5.2.17 X-Powered-By: PHP/5.2.17 Content-language: en Set-Cookie: COUNTRY=ITA%2C85.42.99.82; expires=Fri, 25-May-2012 07:12:38 GMT; path=/; domain=.php.net Last-Modified: Fri, 18 May 2012 10:20:11 GMT Connection: close Content-Type: text/html;charset=utf-8 Friday, May 18, 12
  • 11. Wrappers http://php.net/manual/en/wrappers.php Friday, May 18, 12
  • 12. Wrappers ~: php -r "print_r(stream_get_wrappers());" Array ( [0] => https [1] => ftps [2] => compress.zlib [3] => compress.bzip2 [4] => php [5] => file [6] => glob [7] => data [8] => http [9] => ftp [10] => zip [11] => phar ) Friday, May 18, 12
  • 13. Example ~: php -r '$fp = fopen("php://temp", "w+"); > fwrite($fp, "hello world"); > rewind($fp); > print_r(stream_get_contents($fp));' hello world Friday, May 18, 12
  • 14. Example ~: php -r '$fp = fopen("php://stdout", "w"); > fwrite($fp, "hello world");' hello world Friday, May 18, 12
  • 15. Contexts http://php.net/manual/en/context.php Friday, May 18, 12
  • 16. Contexts • A context is a set of parameters and wrapper specific options that modify or enhance the behavior of streams. Friday, May 18, 12
  • 17. Contexts ~: php -r '$http = array("method" => "HEAD"); > readfile("http://php.net", false, stream_context_create(compact("http"))); > print_r($http_response_header);' Array ( [0] => HTTP/1.1 200 OK [1] => Date: Fri, 18 May 2012 07:25:32 GMT [2] => Server: Apache/1.3.41 (Unix) PHP/5.2.17 [3] => X-Powered-By: PHP/5.2.17 [4] => Content-language: en [5] => Set-Cookie: COUNTRY=ITA%2C85.42.99.82; expires=Fri, 25- May-2012 07:25:34 GMT; path=/; domain=.php.net [6] => Last-Modified: Fri, 18 May 2012 10:20:11 GMT [7] => Connection: close [8] => Content-Type: text/html;charset=utf-8 ) Friday, May 18, 12
  • 18. Filters http://php.net/manual/en/filters.php Friday, May 18, 12
  • 19. Filters • modify data while reading and/or writing • appended and removed anytime • chain filters as needed Friday, May 18, 12
  • 20. Default Filters ~: php -r "print_r(stream_get_filters());" Array ( [0] => zlib.* [1] => bzip2.* [2] => convert.iconv.* [3] => string.rot13 [4] => string.toupper [5] => string.tolower [6] => string.strip_tags [7] => convert.* [8] => consumed [9] => dechunk [10] => http.* ) Friday, May 18, 12
  • 21. Example $stream = fopen('data://text/plain,' . $body, 'r'); stream_filter_append($stream, 'dechunk'); return trim(stream_get_contents($stream)); Friday, May 18, 12
  • 22. Custom Wrappers http://php.net/manual/en/class.streamwrapper.php Friday, May 18, 12
  • 23. streamWrapper { /* Properties */ public resource $context ; /* Methods */ __construct ( void ) __destruct ( void ) public bool dir_closedir ( void ) public bool dir_opendir ( string $path , int $options ) public string dir_readdir ( void ) public bool dir_rewinddir ( void ) public bool mkdir ( string $path , int $mode , int $options ) public bool rename ( string $path_from , string $path_to ) public bool rmdir ( string $path , int $options ) public resource stream_cast ( int $cast_as ) public void stream_close ( void ) public bool stream_eof ( void ) public bool stream_flush ( void ) public bool stream_lock ( mode $operation ) public bool stream_metadata ( int $path , int $option , int $var ) public bool stream_open ( string $path , string $mode , int $options , string &$opened_path ) public string stream_read ( int $count ) public bool stream_seek ( int $offset , int $whence = SEEK_SET ) public bool stream_set_option ( int $option , int $arg1 , int $arg2 ) public array stream_stat ( void ) public int stream_tell ( void ) public bool stream_truncate ( int $new_size ) public int stream_write ( string $data ) public bool unlink ( string $path ) public array url_stat ( string $path , int $flags ) } Friday, May 18, 12
  • 24. 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); public function stream_eof(); public function stream_tell(); public function stream_seek($offset, $whence); public function stream_stat(); public function url_stat($path, $flags); } Friday, May 18, 12
  • 25. class AutoEscapeStream implements Stream_Interface { } Friday, May 18, 12
  • 26. class AutoEscapeStream implements Stream_Interface { protected $_position = 0; protected $_stats = array(); protected $_data = null; protected $_path = null; } Friday, May 18, 12
  • 27. class AutoEscapeStream implements Stream_Interface { ... public function stream_open($path, $mode, $options, &$opened_path) { $path = str_replace('escape://', '', $path); if (empty($path)) { return false; } $success = ($this->_data = file_get_contents($path)); $this->_stats = stat($path); if ($success === false) { return false; } $escEcho = '/<?=s*$this->(.+?)s*;?s*?>/ms'; $this->_data = preg_replace($escEcho, '<?php echo $this->$1; ?>', $this->_data); $echo = '/<?=s*(.+?)s*;?s*?>/ms'; $this->_data = preg_replace($echo, '<?php echo $h($1); ?>', $this->_data); return true; } public function stream_read($count) { $result = substr($this->_data, $this->_position, $count); $this->_position += strlen($result); return $result; } public function stream_tell() { return $this->_position; } public function stream_eof() { return ($this->_position >= strlen($this->_data)); } Friday, May 18, 12
  • 28. class AutoEscapeStream implements Stream_Interface { ... public function stream_seek($offset, $whence) { switch ($whence) { case SEEK_SET: if ($offset < strlen($this->_data) && $offset >= 0) { $this->_position = $offset; return true; } return false; case SEEK_CUR: if ($offset >= 0) { $this->_position += $offset; return true; } return false; case SEEK_END: if (strlen($this->_data) + $offset >= 0) { $this->_position = strlen($this->_data) + $offset; return true; } return false; default: } return false; } public function stream_stat() { return $this->_stats; } public function url_stat() { return $this->_stats; } Friday, May 18, 12
  • 29. Using the Wrapper stream_wrapper_register("escape", "AutoEscapeStream"); include("escape://template.php"); Friday, May 18, 12
  • 30. Demo • Using phar streams • https://github.com/gwoo/sinatrium Friday, May 18, 12
  • 32. @gwoo https://github.com/gwoo THANKS! Friday, May 18, 12