SlideShare a Scribd company logo
1 of 81
Download to read offline
 Idea originating in 1950’s
                 Standard way to get Input and Output
                 A source or sink of data
Definitions




                 C – stdin, stderr, stdout
                 C++ iostream
Who uses them




                 Perl IO
                 Python io
                 Java
                 C#
These are the people you can blame for the PHP streams implementation
 We will write code (in pairs)
 There will be a quiz (with prizes)
 You get out what you put in – participate!

This is really 3 talks in one -
 Streams
 Filters
 Sockets
Abstracting I/O
 Access input and output generically
 Can write and read linearly
 May or may not be seekable
 Comes in chunks of data
 EVERYTHING
 include/require _once
 stream functions
 file system functions
 many other extensions
Stream
         Contexts

             Stream    Stream
ALL IO
              Filter   Wrapper
   Stream
    › Resource that exhibits a flow or succession of
     data
   Wrapper
    › Tells a stream how to handle specific
     protocols and encodings
   Context
    › A set of parameters and options to tell a
     stream (or filter) how to behave
   Scheme
    › The name of the wrapper to be used. file, http, https, ftp,
      etc.
   Target
    › Depends on the wrapper, filesystem uses a string path
      name, ssh2 uses a PHP resource

    home/bar/foo.txt
    file:///home/bar/foo.txt
    http://www.example.com/foo.txt
    ftp://user:pass@ftp.example.com/foo.txt

    php://filter/read=string.toupper|string.rot13/resource
    =http://www.example.com
 flock
 wrapper limitations
 non-existent pointers (infinite loops can
  and will happen)
 error handling
 Parameters
 Options
 Modify or enhance a stream


 stream_context_set_param
 stream_context_set_option
 stream_context_create
Streams available by default
 file://
 http://
 ftp://
 data://
 glob://
   SSL                     Phar
    ›   https://             › phar://
    ›   ftps://             Zlib
    ›   ssl://               › compress.zlib://
    ›   tls://               › zlib://
   SSH                     Bzip
    ›   ssh2.shell://        › compress.bz2://
    ›   ssh2.exec://
    ›   ssh2.tunnel://
    ›   ssh2.sftp://
    ›   ssh2.scp://
 Pipes
 STDIN, STDOUT, STDERR
 proc_open
 popen
 php://stdin
 php://stdout
 php://stderr
 php://output
 php://input
 php://filter (5.0.0)
 php://memory (5.1.0)
 php://temp (5.1.0)
1.   Get a Feed from Flickr -
     http://www.flickr.com/services/feeds/

2. No curl installed, allow_url_fopen is on
3. Display however you would like
Grab the feed as xml, pop it through
 simplexml, loop and display the output
 to a webpage
Userland Filters and Streams
 There are no interfaces
 Implement as though there were an
  interface
 Seekable is optional
 Flushable is optional
 Directory support is optional
 fopen
               file_get_contents

Information


                 Return true or false
                 $this->context will have any context
                  metadata
Code
   fread
                 fgets
                 file_get_contents
Information
                 etc…


                 Return string data or false
                 $this->context will have any context
                  metadata
Code
 fwrite
               file_put_contents

Information


                 get in a string of data to deal with
                 return how many bytes you wrote
Code
   feof
                 file_get_contents
                 fread
Information
                 etc…


                 Return true or false
                 $this->context will have any context
                  metadata
Code
 fclose
               file_get_contents

Information


                 Don’t return anything
                 any cleanup should go here
Code
 fstat calls stream_stat
 EVERYTHING ELSE uses url_stat
 Good idea to do both




   Return an array of data identical to stat()
 stream_seek
 stream_tell




   stream_flush
 mkdir
 rmdir
 dir_closedir
 dir_opendir
 dir_readdir
 dir_rewinddir
 stream_lock
 stream_cast
 rename
 unlink
Create a custom wrapper for any kind of
  network or shared memory storage you
  want (except s3 which is way overdone)

Implement at least the basics – extra points
  for more features
Wrapper for wincache (btw, porting this to
 apc would be a breeze)

Does basics + seek + flush (since we’re
 caching) + rename + unlink

No directories
Use Case land – when streams
make sense
 Data in s3
 Data locally during development
 Easy switch out if alternative storage is
  ever desired
 Storing image files
 Existing Zend Framework Code
 Register the s3:// wrapper
 Use a configuration setting for the stream
  to use for all images on the system
 Store and edit template files in a
  database
 Have the snappiness of including from
  disk
 Minimal Configuration
 db:// stream
 simple stream wrapper that looks for the
  template in the db, and writes it to the
  filesystem before returning the data
 The cached location is FIRST in the
  include path, so if it fails, the db stream
  gets hit
 Talk to mercurial (hg binary)
 hg communicates via command line
 continue to pipe additional commands
 Use proc_open to keep a pipe to the
  binary going
 Pass commands through stdin pipe as
  necessary
 Abstract this out to other binaries that
  are used by the system
1. Name 3 Built in PHP streams.
2. What is a Context? A Wrapper? A
   Stream?
3. How do you identify a stream?
4. Name two extensions that provide
   additional PHP streams.
 http://php.net/streams
 http://php.net/filesystem
 http://ciaranmcnulty.com/blog/2009/04/
  simplifying-file-operations-using-php-
  stream-wrappers
Because everyone needs to rot13
a file they open on the fly
 Performs operations on stream data
 Can be prepended or appended (even
  on the fly)
 Can be attached to read or write
 When a filter is added for read and write,
  two instances of the filter are created.
 Data has an input and output state
 When reading in chunks, you may need
  to cache in between reads to make
  filters useful
 Use the right tool for the job
   string filters
    › string.rot13
    › string.toupper
    › string.tolower
    › string.strip_tags
   convert filters
    › convert.*
       base64-encode
       base64-decode
       quoted-printable-encode
       quoted-printable-decode
   dechunk
    › decode remote HTTP chunked encoding
      streams
   consumed
    › eats data (that’s all it does)
 bzip.compress and bzip.compress
 convert.iconv.*
 zlib.inflate and zlib.deflate
 mcrypt.* and mdecrypt.*
 Extend an internal class php_user_filter
 It’s not abstract…
 Yes that’s a horrible name
 Remember this pre-dates php 5.0
  decisions
 onCreate
               basically a constructor
               Called every time PHP needs a new filter
Information
                (on every stream)

                 return true or false
Code
   php_user_filter
    › $this->filtername
    › $this->params
    › $this->stream
 onClose
               basically a destructor

Information




                 no return
Code
   MUST return
                  › PSFS_PASS_ON
                  › PSFS_FEED_ME
Information       › PSFS_ERR_FATAL
                 You get buckets of data and do stuff to
                  them
Code
 $in and $out are “bucket brigades”
  containing opaque “buckets” of data
 You can only touch buckets and
  brigades with the stream_bucket_*
  functions
 You get a bucket using
  stream_bucket_make_writeable
 Given a list of bad words (we’ll use the 7
  bad words), write a filter to remove them
  from text
 Given a commonly misspelled word, fix
  the spelling in the text
 I only did the bad words one, and
  created an extremely naïve regex that
  stripped the “bad” words from whatever
  text it finds.
 It buffers the entirety of the text before
  doing the replacement – this could be
  done by looking for word boundaries
  and doing it piecemeal to improve
  performance
1. What term is used to describe data
   handling in filters?
2. Name two built in filters you should be
   using and why.
3. What is the default mode filters are
   appended with?
4. What is the difference between
   appending and prepending a filter?
 http://php.net/streams
 http://php.net/filters
Putter about the network with me
   Socket
    › Bidirectional network stream that speaks a
      protocol
   Transport
    › Tells a network stream how to communicate
   Wrapper
    › Tells a stream how to handle specific
      protocols and encodings
 Network Stream, Network Transport,
  Socket Transport
 Slightly different behavior from a file
  stream
 Bi-directional data
   Sockets block
    › stream_set_blocking
    › stream_set_timeout
    › stream_select
 feof means “connection_closed”?
 huge reads or writes (think 8K)
 stream_get_meta_data is READ ONLY
 New APIS in streams and filesystem
  functions are replacements
 Extension is old and not really kept up to
  date (bit rot)
 Extension is more low level


 stream_socket_server
 stream_socket_client
 tcp
 udp
 unix
 udg
 SSL extension
    ›   ssl
    ›   sslv2
    ›   sslv3
    ›   tls
 Given two files of quotes, write a server
  with PHP streams methods to return
  random quotes, optionally allow client to
  pick which file to retrieve quotes from
 Given a simple tcp server that will return
  a random quote – make a client that
  pulls quotes for users
 socket_server.php – uses
  stream_socket_server and
  stream_accept
 socket_client.php – uses
  stream_socket_client and a bit of loop
  magic to make a little “cli” app
1. How is a socket different from a stream?
2. What transports does PHP provide by
   default?
3. Name the two most commonly used
   stream socket functions.
4. How can a user add additional
   transports to PHP?
 http://php.net/streams
 http://php.net/transports
 http://wikipedia.org/wiki/Unix_domain_s
  ocket
 http://tools.ietf.org/html/rfc1122
 Set of interfaces for streams
 Improved based filter class
 Wrappers for chmod and touch
 More tests!
 Any you have?
 http://emsmith.net
 http://joind.in/3439
 auroraeosrose@gmail.com
 IRC – freenode – auroraeosrose
 #php-gtk #coapp

More Related Content

What's hot

Php on the Web and Desktop
Php on the Web and DesktopPhp on the Web and Desktop
Php on the Web and DesktopElizabeth Smith
 
Writing and using php streams and sockets
Writing and using php streams and socketsWriting and using php streams and sockets
Writing and using php streams and socketsElizabeth Smith
 
Understanding PHP objects
Understanding PHP objectsUnderstanding PHP objects
Understanding PHP objectsjulien pauli
 
Programming in Computational Biology
Programming in Computational BiologyProgramming in Computational Biology
Programming in Computational BiologyAtreyiB
 
Puppet Camp Berlin 2014: Manageable puppet infrastructure
Puppet Camp Berlin 2014: Manageable puppet infrastructurePuppet Camp Berlin 2014: Manageable puppet infrastructure
Puppet Camp Berlin 2014: Manageable puppet infrastructurePuppet
 
Doing It Wrong with Puppet -
Doing It Wrong with Puppet - Doing It Wrong with Puppet -
Doing It Wrong with Puppet - Puppet
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Alena Holligan
 

What's hot (20)

Php on the Web and Desktop
Php on the Web and DesktopPhp on the Web and Desktop
Php on the Web and Desktop
 
Writing and using php streams and sockets
Writing and using php streams and socketsWriting and using php streams and sockets
Writing and using php streams and sockets
 
Understanding PHP objects
Understanding PHP objectsUnderstanding PHP objects
Understanding PHP objects
 
IO Streams, Files and Directories
IO Streams, Files and DirectoriesIO Streams, Files and Directories
IO Streams, Files and Directories
 
Power of Puppet 4
Power of Puppet 4Power of Puppet 4
Power of Puppet 4
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 
Programming in Computational Biology
Programming in Computational BiologyProgramming in Computational Biology
Programming in Computational Biology
 
Puppet @ Seat
Puppet @ SeatPuppet @ Seat
Puppet @ Seat
 
Puppet Camp Berlin 2014: Manageable puppet infrastructure
Puppet Camp Berlin 2014: Manageable puppet infrastructurePuppet Camp Berlin 2014: Manageable puppet infrastructure
Puppet Camp Berlin 2014: Manageable puppet infrastructure
 
rtwerewr
rtwerewrrtwerewr
rtwerewr
 
Doing It Wrong with Puppet -
Doing It Wrong with Puppet - Doing It Wrong with Puppet -
Doing It Wrong with Puppet -
 
Anatomy of a reusable module
Anatomy of a reusable moduleAnatomy of a reusable module
Anatomy of a reusable module
 
05php
05php05php
05php
 
Perl Programming - 01 Basic Perl
Perl Programming - 01 Basic PerlPerl Programming - 01 Basic Perl
Perl Programming - 01 Basic Perl
 
Php on Windows
Php on WindowsPhp on Windows
Php on Windows
 
Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016Demystifying Object-Oriented Programming - ZendCon 2016
Demystifying Object-Oriented Programming - ZendCon 2016
 
PHP - Introduction to PHP
PHP -  Introduction to PHPPHP -  Introduction to PHP
PHP - Introduction to PHP
 
Hacking with hhvm
Hacking with hhvmHacking with hhvm
Hacking with hhvm
 
System Programming and Administration
System Programming and AdministrationSystem Programming and Administration
System Programming and Administration
 
Puppet modules for Fun and Profit
Puppet modules for Fun and ProfitPuppet modules for Fun and Profit
Puppet modules for Fun and Profit
 

Similar to Writing and using php streams and sockets tek11

Tips
TipsTips
Tipsmclee
 
Github.com anton terekhov-orientdb-php
Github.com anton terekhov-orientdb-phpGithub.com anton terekhov-orientdb-php
Github.com anton terekhov-orientdb-phpSan jay
 
Most Popular Hadoop Interview Questions and Answers
Most Popular Hadoop Interview Questions and AnswersMost Popular Hadoop Interview Questions and Answers
Most Popular Hadoop Interview Questions and AnswersSprintzeal
 
Php 7 compliance workshop singapore
Php 7 compliance workshop singaporePhp 7 compliance workshop singapore
Php 7 compliance workshop singaporeDamien Seguy
 
Computer network (10)
Computer network (10)Computer network (10)
Computer network (10)NYversity
 
Static analysis saved my code tonight
Static analysis saved my code tonightStatic analysis saved my code tonight
Static analysis saved my code tonightDamien Seguy
 
MidwestPHP Symfony2 Internals
MidwestPHP Symfony2 InternalsMidwestPHP Symfony2 Internals
MidwestPHP Symfony2 InternalsRaul Fraile
 
Spl in the wild - zendcon2012
Spl in the wild - zendcon2012Spl in the wild - zendcon2012
Spl in the wild - zendcon2012Elizabeth Smith
 
Php Best Practices
Php Best PracticesPhp Best Practices
Php Best PracticesAnsar Ahmed
 
Php Best Practices
Php Best PracticesPhp Best Practices
Php Best PracticesAnsar Ahmed
 
Php extensions workshop
Php extensions workshopPhp extensions workshop
Php extensions workshopjulien pauli
 

Similar to Writing and using php streams and sockets tek11 (20)

Tips
TipsTips
Tips
 
Github.com anton terekhov-orientdb-php
Github.com anton terekhov-orientdb-phpGithub.com anton terekhov-orientdb-php
Github.com anton terekhov-orientdb-php
 
Most Popular Hadoop Interview Questions and Answers
Most Popular Hadoop Interview Questions and AnswersMost Popular Hadoop Interview Questions and Answers
Most Popular Hadoop Interview Questions and Answers
 
John's Top PECL Picks
John's Top PECL PicksJohn's Top PECL Picks
John's Top PECL Picks
 
PHP 5.3
PHP 5.3PHP 5.3
PHP 5.3
 
Php 7 compliance workshop singapore
Php 7 compliance workshop singaporePhp 7 compliance workshop singapore
Php 7 compliance workshop singapore
 
Computer network (10)
Computer network (10)Computer network (10)
Computer network (10)
 
Php manish
Php manishPhp manish
Php manish
 
Static analysis saved my code tonight
Static analysis saved my code tonightStatic analysis saved my code tonight
Static analysis saved my code tonight
 
Wikilims Road4
Wikilims Road4Wikilims Road4
Wikilims Road4
 
Linux
LinuxLinux
Linux
 
MidwestPHP Symfony2 Internals
MidwestPHP Symfony2 InternalsMidwestPHP Symfony2 Internals
MidwestPHP Symfony2 Internals
 
Spl in the wild - zendcon2012
Spl in the wild - zendcon2012Spl in the wild - zendcon2012
Spl in the wild - zendcon2012
 
Ch23 system administration
Ch23 system administration Ch23 system administration
Ch23 system administration
 
Download It
Download ItDownload It
Download It
 
Php Best Practices
Php Best PracticesPhp Best Practices
Php Best Practices
 
Php Best Practices
Php Best PracticesPhp Best Practices
Php Best Practices
 
Files nts
Files ntsFiles nts
Files nts
 
Php’s guts
Php’s gutsPhp’s guts
Php’s guts
 
Php extensions workshop
Php extensions workshopPhp extensions workshop
Php extensions workshop
 

More from Elizabeth Smith

More from Elizabeth Smith (20)

Welcome to the internet
Welcome to the internetWelcome to the internet
Welcome to the internet
 
Database theory and modeling
Database theory and modelingDatabase theory and modeling
Database theory and modeling
 
Taming the resource tiger
Taming the resource tigerTaming the resource tiger
Taming the resource tiger
 
Modern sql
Modern sqlModern sql
Modern sql
 
Php extensions
Php extensionsPhp extensions
Php extensions
 
Taming the resource tiger
Taming the resource tigerTaming the resource tiger
Taming the resource tiger
 
Php internal architecture
Php internal architecturePhp internal architecture
Php internal architecture
 
Taming the tiger - pnwphp
Taming the tiger - pnwphpTaming the tiger - pnwphp
Taming the tiger - pnwphp
 
Php extensions
Php extensionsPhp extensions
Php extensions
 
Php extensions
Php extensionsPhp extensions
Php extensions
 
Lexing and parsing
Lexing and parsingLexing and parsing
Lexing and parsing
 
Security is not a feature
Security is not a featureSecurity is not a feature
Security is not a feature
 
Using unicode with php
Using unicode with phpUsing unicode with php
Using unicode with php
 
Mentoring developers-php benelux-2014
Mentoring developers-php benelux-2014Mentoring developers-php benelux-2014
Mentoring developers-php benelux-2014
 
Using unicode with php
Using unicode with phpUsing unicode with php
Using unicode with php
 
Socket programming with php
Socket programming with phpSocket programming with php
Socket programming with php
 
Mentoring developers
Mentoring developersMentoring developers
Mentoring developers
 
Do the mentor thing
Do the mentor thingDo the mentor thing
Do the mentor thing
 
Mentoring developers - Zendcon 2012
Mentoring developers - Zendcon 2012Mentoring developers - Zendcon 2012
Mentoring developers - Zendcon 2012
 
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
 

Recently uploaded

Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 

Recently uploaded (20)

Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 

Writing and using php streams and sockets tek11

  • 1.
  • 2.  Idea originating in 1950’s  Standard way to get Input and Output  A source or sink of data Definitions  C – stdin, stderr, stdout  C++ iostream Who uses them  Perl IO  Python io  Java  C#
  • 3. These are the people you can blame for the PHP streams implementation
  • 4.  We will write code (in pairs)  There will be a quiz (with prizes)  You get out what you put in – participate! This is really 3 talks in one -  Streams  Filters  Sockets
  • 6.  Access input and output generically  Can write and read linearly  May or may not be seekable  Comes in chunks of data
  • 7.  EVERYTHING  include/require _once  stream functions  file system functions  many other extensions
  • 8. Stream Contexts Stream Stream ALL IO Filter Wrapper
  • 9. Stream › Resource that exhibits a flow or succession of data  Wrapper › Tells a stream how to handle specific protocols and encodings  Context › A set of parameters and options to tell a stream (or filter) how to behave
  • 10. Scheme › The name of the wrapper to be used. file, http, https, ftp, etc.  Target › Depends on the wrapper, filesystem uses a string path name, ssh2 uses a PHP resource home/bar/foo.txt file:///home/bar/foo.txt http://www.example.com/foo.txt ftp://user:pass@ftp.example.com/foo.txt php://filter/read=string.toupper|string.rot13/resource =http://www.example.com
  • 11.
  • 12.  flock  wrapper limitations  non-existent pointers (infinite loops can and will happen)  error handling
  • 13.  Parameters  Options  Modify or enhance a stream  stream_context_set_param  stream_context_set_option  stream_context_create
  • 14.
  • 16.  file://  http://  ftp://  data://  glob://
  • 17. SSL  Phar › https:// › phar:// › ftps://  Zlib › ssl:// › compress.zlib:// › tls:// › zlib://  SSH  Bzip › ssh2.shell:// › compress.bz2:// › ssh2.exec:// › ssh2.tunnel:// › ssh2.sftp:// › ssh2.scp://
  • 18.
  • 19.
  • 20.
  • 21.  Pipes  STDIN, STDOUT, STDERR  proc_open  popen
  • 22.  php://stdin  php://stdout  php://stderr  php://output  php://input  php://filter (5.0.0)  php://memory (5.1.0)  php://temp (5.1.0)
  • 23.
  • 24. 1. Get a Feed from Flickr - http://www.flickr.com/services/feeds/ 2. No curl installed, allow_url_fopen is on 3. Display however you would like
  • 25. Grab the feed as xml, pop it through simplexml, loop and display the output to a webpage
  • 26.
  • 28.  There are no interfaces  Implement as though there were an interface  Seekable is optional  Flushable is optional  Directory support is optional
  • 29.  fopen  file_get_contents Information  Return true or false  $this->context will have any context metadata Code
  • 30. fread  fgets  file_get_contents Information  etc…  Return string data or false  $this->context will have any context metadata Code
  • 31.  fwrite  file_put_contents Information  get in a string of data to deal with  return how many bytes you wrote Code
  • 32. feof  file_get_contents  fread Information  etc…  Return true or false  $this->context will have any context metadata Code
  • 33.  fclose  file_get_contents Information  Don’t return anything  any cleanup should go here Code
  • 34.  fstat calls stream_stat  EVERYTHING ELSE uses url_stat  Good idea to do both  Return an array of data identical to stat()
  • 36.  mkdir  rmdir  dir_closedir  dir_opendir  dir_readdir  dir_rewinddir
  • 38. Create a custom wrapper for any kind of network or shared memory storage you want (except s3 which is way overdone) Implement at least the basics – extra points for more features
  • 39. Wrapper for wincache (btw, porting this to apc would be a breeze) Does basics + seek + flush (since we’re caching) + rename + unlink No directories
  • 40. Use Case land – when streams make sense
  • 41.  Data in s3  Data locally during development  Easy switch out if alternative storage is ever desired  Storing image files
  • 42.  Existing Zend Framework Code  Register the s3:// wrapper  Use a configuration setting for the stream to use for all images on the system
  • 43.  Store and edit template files in a database  Have the snappiness of including from disk  Minimal Configuration
  • 44.  db:// stream  simple stream wrapper that looks for the template in the db, and writes it to the filesystem before returning the data  The cached location is FIRST in the include path, so if it fails, the db stream gets hit
  • 45.  Talk to mercurial (hg binary)  hg communicates via command line  continue to pipe additional commands
  • 46.  Use proc_open to keep a pipe to the binary going  Pass commands through stdin pipe as necessary  Abstract this out to other binaries that are used by the system
  • 47. 1. Name 3 Built in PHP streams. 2. What is a Context? A Wrapper? A Stream? 3. How do you identify a stream? 4. Name two extensions that provide additional PHP streams.
  • 48.  http://php.net/streams  http://php.net/filesystem  http://ciaranmcnulty.com/blog/2009/04/ simplifying-file-operations-using-php- stream-wrappers
  • 49.
  • 50. Because everyone needs to rot13 a file they open on the fly
  • 51.  Performs operations on stream data  Can be prepended or appended (even on the fly)  Can be attached to read or write  When a filter is added for read and write, two instances of the filter are created.
  • 52.
  • 53.  Data has an input and output state  When reading in chunks, you may need to cache in between reads to make filters useful  Use the right tool for the job
  • 54. string filters › string.rot13 › string.toupper › string.tolower › string.strip_tags
  • 55. convert filters › convert.*  base64-encode  base64-decode  quoted-printable-encode  quoted-printable-decode  dechunk › decode remote HTTP chunked encoding streams  consumed › eats data (that’s all it does)
  • 56.  bzip.compress and bzip.compress  convert.iconv.*  zlib.inflate and zlib.deflate  mcrypt.* and mdecrypt.*
  • 57.  Extend an internal class php_user_filter  It’s not abstract…  Yes that’s a horrible name  Remember this pre-dates php 5.0 decisions
  • 58.  onCreate  basically a constructor  Called every time PHP needs a new filter Information (on every stream)  return true or false Code
  • 59. php_user_filter › $this->filtername › $this->params › $this->stream
  • 60.  onClose  basically a destructor Information  no return Code
  • 61. MUST return › PSFS_PASS_ON › PSFS_FEED_ME Information › PSFS_ERR_FATAL  You get buckets of data and do stuff to them Code
  • 62.
  • 63.  $in and $out are “bucket brigades” containing opaque “buckets” of data  You can only touch buckets and brigades with the stream_bucket_* functions  You get a bucket using stream_bucket_make_writeable
  • 64.  Given a list of bad words (we’ll use the 7 bad words), write a filter to remove them from text  Given a commonly misspelled word, fix the spelling in the text
  • 65.  I only did the bad words one, and created an extremely naïve regex that stripped the “bad” words from whatever text it finds.  It buffers the entirety of the text before doing the replacement – this could be done by looking for word boundaries and doing it piecemeal to improve performance
  • 66.
  • 67. 1. What term is used to describe data handling in filters? 2. Name two built in filters you should be using and why. 3. What is the default mode filters are appended with? 4. What is the difference between appending and prepending a filter?
  • 69. Putter about the network with me
  • 70. Socket › Bidirectional network stream that speaks a protocol  Transport › Tells a network stream how to communicate  Wrapper › Tells a stream how to handle specific protocols and encodings
  • 71.  Network Stream, Network Transport, Socket Transport  Slightly different behavior from a file stream  Bi-directional data
  • 72. Sockets block › stream_set_blocking › stream_set_timeout › stream_select  feof means “connection_closed”?  huge reads or writes (think 8K)  stream_get_meta_data is READ ONLY
  • 73.  New APIS in streams and filesystem functions are replacements  Extension is old and not really kept up to date (bit rot)  Extension is more low level  stream_socket_server  stream_socket_client
  • 74.
  • 75.  tcp  udp  unix  udg  SSL extension › ssl › sslv2 › sslv3 › tls
  • 76.  Given two files of quotes, write a server with PHP streams methods to return random quotes, optionally allow client to pick which file to retrieve quotes from  Given a simple tcp server that will return a random quote – make a client that pulls quotes for users
  • 77.  socket_server.php – uses stream_socket_server and stream_accept  socket_client.php – uses stream_socket_client and a bit of loop magic to make a little “cli” app
  • 78. 1. How is a socket different from a stream? 2. What transports does PHP provide by default? 3. Name the two most commonly used stream socket functions. 4. How can a user add additional transports to PHP?
  • 79.  http://php.net/streams  http://php.net/transports  http://wikipedia.org/wiki/Unix_domain_s ocket  http://tools.ietf.org/html/rfc1122
  • 80.  Set of interfaces for streams  Improved based filter class  Wrappers for chmod and touch  More tests!  Any you have?
  • 81.  http://emsmith.net  http://joind.in/3439  auroraeosrose@gmail.com  IRC – freenode – auroraeosrose  #php-gtk #coapp