SlideShare a Scribd company logo
1 of 25
Download to read offline
Deliver Files With PHP
Thomas Weinert
About me
   Application Developer
     ▹   PHP
     ▹   XSLT/XPath
     ▹   (some) Javascript

    papaya CMS
     ▹   PHP based Content Management System
     ▹   uses XSLT for Templates


Thomas Weinert, papaya Software GmbH
Steps
   Block                                 Send
   Check                                  ▹   At Once
     ▹   Filename                          ▹   Piece By Piece
     ▹   File                              ▹   Limit

    Tell                               
                                           Optimize
     ▹   Date                              ▹   Traffic
     ▹   Size                              ▹   Performance
     ▹   Type                              ▹   Flash
     ▹   Name
Thomas Weinert, papaya Software GmbH
                                       
                                           Problems
Block
   Move outside document root


    .htaccess
     ▹   Deny From All

    Rewrite?




Thomas Weinert, papaya Software GmbH
Check Filename
   dirname(), basename()
   preg_match

    strrpos() + substr()


    against database
     ▹   Use hashed random strings for id
     ▹   Split at chars
     ▹   virtual directory structure
Thomas Weinert, papaya Software GmbH
Check File
   file_exists()
     ▹   return true for directories

    is_file()

    is_readable()




Thomas Weinert, papaya Software GmbH
Check File Type
   getimagesize() (no GD needed)
   /usr/bin/file

    ext/fileinfo (PHP 5.3)




Thomas Weinert, papaya Software GmbH
Tell Date
   Last change

    header('Last-modified: '.
      gmdate('D, d M Y H:i:s', $fileDate.' GMT');



    Valid until

 header('Expires: '.
   gmdate('D, d M Y H:i:s', $expireTime).' GMT');


Thomas Weinert, papaya Software GmbH
Tell Size
   Size
     ▹   Show progress in browser


         header('Content-length: '.$fileSize);




Thomas Weinert, papaya Software GmbH
Tell Type
   File Mime Type

           header('Content-type: '.$mimeType);




    Rewrite Filenames
     ▹   IE check filename



Thomas Weinert, papaya Software GmbH
Force Download
    IE and Opera

    header('Content-type: application/octetstream');


 
     Others

 header('Content-type: application/octet-stream');



Thomas Weinert, papaya Software GmbH
Tell Filename
    For files in browser or IE

 header('Content-disposition: inline; filename=quot;'.
   $data['file_name'].'quot;');


 
     For downloads - except IE

     header('Content-disposition: attachment; filename=quot;'.
       $data['file_name'].'quot;');


    Escape “ and  in filename with 
Thomas Weinert, papaya Software GmbH
Send – At Once
   fpassthru()
   readfile()


    Pro:
     ▹    Easy

    Contra:
     ▹   Less control

Thomas Weinert, papaya Software GmbH
Send - Piece By Piece
   fread()
   fseek()

    echo, print()

    flush()




Thomas Weinert, papaya Software GmbH
Send – Piece By Piece
<?php
if ($fh = fopen($localFileName, 'r')) {
   while (!feof($fh) &&
          connection_status() == 0) {
     echo fread($fh, $bytesPerStep);
     flush();
   }
   fclose($fh);
}
?>



Thomas Weinert, papaya Software GmbH
Send – Piece By Piece
<?php
if ($fh = fopen($localFileName, 'r')) {
   //seek file to start position
   if ($fileOffset > 0) {
       fseek($fh, $fileOffset);
   }
   while (!feof($fh) &&
                connection_status() == 0) {
       echo fread($fh, $bytesPerStep);
       flush();
   }
   fclose($fh);
}
?> Weinert, papaya Software GmbH
Thomas
Optimize - Traffic
   Range-Header
     ▹   Send:
          ▪   header('Accept-Ranges: bytes');
     ▹   Receive:
          ▪   $_SERVER['HTTP_RANGE']
          ▪   bytes=[start1][]-[stop1][,start2][-][stop2][...]:
     ▹   Send:
          ▪   header('Accept-Ranges: bytes');
          ▪   header('HTTP/1.1 206 Partial Content');
          ▪   header(sprintf('Content-Range: bytes %d-%d/
              %d', ...);
Thomas Weinert, papaya Software GmbH
Send – Bandwidth Limit
   Track time and send bytes
   Sleep some time if sent to fast
     ▹   usleep(), sleep()

    Send first bytes without limit


    Why?
     ▹   Video-Streaming
     ▹   User don't need all data
Thomas Weinert, papaya Software GmbH
if ($shapeRequest) {
  $bytesSend += $bytesPerStep;
  if ($bytesSend > $shapeLimitStart) {
    $timeDiff = microtime(TRUE) - $timeStart;
    $rate = ($bytesSend - $shapeLimitStart)
      / $timeDiff;

        if ($rate > $shapeLimitRate) {
          $sleepFunction($sleepTime);
        }
    }
}

Thomas Weinert, papaya Software GmbH
Optimize - Performance
   Close Sessions
     ▹   session_write_close()


   X-Sendfile
     ▹   header('X-Sendfile: '.$localFileName);


     ▹   Header for Lighttpd
     ▹   Apache Extension

Thomas Weinert, papaya Software GmbH
Optimize – Flash I
   Byte offset tables in video file
     ▹   ffmpeg ... -g 500 ...

    Special player sends GET parameter
     ▹   JW FLV Player

    Server checks GET parameter
     ▹   PHP script
     ▹   Lighttpd module


Thomas Weinert, papaya Software GmbH
Optimize – Flash – Meta Data




Thomas Weinert, papaya Software GmbH
Optimize – Flash II
   Check for GET parameters
     ▹   start, pos, position

    Output magic bytes
     ▹   $flashHeader = 'FLV'.pack('CCNN', 1, 5, 9, 0);

     ▹   01 (version) 05 (audio and video)
         00 00 00 09 (header size)
         00 00 00 00 (size of previous tag)

    Seek file

    Output file
Thomas Weinert, papaya Software GmbH
Problems
   will disable flush() / cause buffering
     ▹   ob_start()
     ▹   session.use_trans_sid
     ▹   zlib.output_compression


     ▹   http:/www.php.net/flush (Comments)



    Adobe Acrobat Reader in IE has buggy Range
    headers support
Thomas Weinert, papaya Software GmbH
Links
   X-Sendfile
     ▹   http://blog.lighttpd.net/articles/2006/07/02/x-
         sendfile
     ▹   http://tn123.ath.cx/mod_xsendfile/



    Flash
     ▹   http://www.jeroenwijering.com/
     ▹   http://ffmpeg.mplayerhq.hu/
     ▹
Thomas Weinert, papaya Software GmbH

    http://www.abasketfulofpapayas.de/

More Related Content

What's hot

Php file upload, cookies & session
Php file upload, cookies & sessionPhp file upload, cookies & session
Php file upload, cookies & session
Jamshid Hashimi
 

What's hot (20)

Caching and tuning fun for high scalability @ PHPTour
Caching and tuning fun for high scalability @ PHPTourCaching and tuning fun for high scalability @ PHPTour
Caching and tuning fun for high scalability @ PHPTour
 
File upload php
File upload phpFile upload php
File upload php
 
eZ Publish Cluster Unleashed
eZ Publish Cluster UnleashedeZ Publish Cluster Unleashed
eZ Publish Cluster Unleashed
 
Filesystem Abstraction with Flysystem
Filesystem Abstraction with FlysystemFilesystem Abstraction with Flysystem
Filesystem Abstraction with Flysystem
 
Firefox OS + Raspberry Pi
Firefox OS + Raspberry PiFirefox OS + Raspberry Pi
Firefox OS + Raspberry Pi
 
Uploading a file with php
Uploading a file with phpUploading a file with php
Uploading a file with php
 
05 File Handling Upload Mysql
05 File Handling Upload Mysql05 File Handling Upload Mysql
05 File Handling Upload Mysql
 
Php with my sql
Php with my sqlPhp with my sql
Php with my sql
 
Php hacku
Php hackuPhp hacku
Php hacku
 
Introducation to php for beginners
Introducation to php for beginners Introducation to php for beginners
Introducation to php for beginners
 
phptek13 - Caching and tuning fun tutorial
phptek13 - Caching and tuning fun tutorialphptek13 - Caching and tuning fun tutorial
phptek13 - Caching and tuning fun tutorial
 
Sa
SaSa
Sa
 
Fun with processes - lightning talk
Fun with processes - lightning talkFun with processes - lightning talk
Fun with processes - lightning talk
 
WP HTTP API
WP HTTP APIWP HTTP API
WP HTTP API
 
File include
File includeFile include
File include
 
PHP language presentation
PHP language presentationPHP language presentation
PHP language presentation
 
Beyond php - it's not (just) about the code
Beyond php - it's not (just) about the codeBeyond php - it's not (just) about the code
Beyond php - it's not (just) about the code
 
dNFS for DBA's
dNFS for DBA'sdNFS for DBA's
dNFS for DBA's
 
Php file upload, cookies & session
Php file upload, cookies & sessionPhp file upload, cookies & session
Php file upload, cookies & session
 
Php File Upload
Php File UploadPhp File Upload
Php File Upload
 

Viewers also liked (9)

Php Form
Php FormPhp Form
Php Form
 
PHP - Introduction to PHP Cookies and Sessions
PHP - Introduction to PHP Cookies and SessionsPHP - Introduction to PHP Cookies and Sessions
PHP - Introduction to PHP Cookies and Sessions
 
Chapter 07 php forms handling
Chapter 07   php forms handlingChapter 07   php forms handling
Chapter 07 php forms handling
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and Sessions
 
PHP Files: An Introduction
PHP Files: An IntroductionPHP Files: An Introduction
PHP Files: An Introduction
 
3 php forms
3 php forms3 php forms
3 php forms
 
PHP Cookies, Sessions and Authentication
PHP Cookies, Sessions and AuthenticationPHP Cookies, Sessions and Authentication
PHP Cookies, Sessions and Authentication
 
Form Processing In Php
Form Processing In PhpForm Processing In Php
Form Processing In Php
 
Php forms
Php formsPhp forms
Php forms
 

Similar to Deliver Files With PHP

Optimizing Your Frontend Performance
Optimizing Your Frontend PerformanceOptimizing Your Frontend Performance
Optimizing Your Frontend Performance
Thomas Weinert
 
Website releases made easy with the PEAR installer, OSCON 2009
Website releases made easy with the PEAR installer, OSCON 2009Website releases made easy with the PEAR installer, OSCON 2009
Website releases made easy with the PEAR installer, OSCON 2009
Helgi Þormar Þorbjörnsson
 
Employing Custom Fonts
Employing Custom FontsEmploying Custom Fonts
Employing Custom Fonts
Paul Irish
 
Parches en Drupal - Creación y Aplicación
Parches en Drupal - Creación y AplicaciónParches en Drupal - Creación y Aplicación
Parches en Drupal - Creación y Aplicación
Franco Cedillo
 
Website releases made easy with the PEAR installer - Barcelona 2008
Website releases made easy with the PEAR installer - Barcelona 2008Website releases made easy with the PEAR installer - Barcelona 2008
Website releases made easy with the PEAR installer - Barcelona 2008
Helgi Þormar Þorbjörnsson
 
Jordan Hubbard Talk @ LISA
Jordan Hubbard Talk @ LISAJordan Hubbard Talk @ LISA
Jordan Hubbard Talk @ LISA
guest4c923d
 

Similar to Deliver Files With PHP (20)

Optimizing Your Frontend Performance
Optimizing Your Frontend PerformanceOptimizing Your Frontend Performance
Optimizing Your Frontend Performance
 
PHP 5.3/6
PHP 5.3/6PHP 5.3/6
PHP 5.3/6
 
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!
 
Website releases made easy with the PEAR installer, OSCON 2009
Website releases made easy with the PEAR installer, OSCON 2009Website releases made easy with the PEAR installer, OSCON 2009
Website releases made easy with the PEAR installer, OSCON 2009
 
Bubbles & Trees with jQuery
Bubbles & Trees with jQueryBubbles & Trees with jQuery
Bubbles & Trees with jQuery
 
Employing Custom Fonts
Employing Custom FontsEmploying Custom Fonts
Employing Custom Fonts
 
Php
PhpPhp
Php
 
RPM: Speed up your deploy
RPM: Speed up your deployRPM: Speed up your deploy
RPM: Speed up your deploy
 
Parches en Drupal - Creación y Aplicación
Parches en Drupal - Creación y AplicaciónParches en Drupal - Creación y Aplicación
Parches en Drupal - Creación y Aplicación
 
Automating a Vendor File Load Process with Perl and Shell Scripting
Automating a Vendor File Load Process with Perl and Shell ScriptingAutomating a Vendor File Load Process with Perl and Shell Scripting
Automating a Vendor File Load Process with Perl and Shell Scripting
 
Kommons
KommonsKommons
Kommons
 
Website releases made easy with the PEAR installer - Barcelona 2008
Website releases made easy with the PEAR installer - Barcelona 2008Website releases made easy with the PEAR installer - Barcelona 2008
Website releases made easy with the PEAR installer - Barcelona 2008
 
Centralized + Unified Logging
Centralized + Unified LoggingCentralized + Unified Logging
Centralized + Unified Logging
 
PHP Presentation
PHP PresentationPHP Presentation
PHP Presentation
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
Perl 1997 Paper
Perl 1997 PaperPerl 1997 Paper
Perl 1997 Paper
 
Flash templates for Joomla!
Flash templates for Joomla!Flash templates for Joomla!
Flash templates for Joomla!
 
Flash Templates- Joomla!Days NL 2009 #jd09nl
Flash Templates- Joomla!Days NL 2009 #jd09nlFlash Templates- Joomla!Days NL 2009 #jd09nl
Flash Templates- Joomla!Days NL 2009 #jd09nl
 
Jordan Hubbard Talk @ LISA
Jordan Hubbard Talk @ LISAJordan Hubbard Talk @ LISA
Jordan Hubbard Talk @ LISA
 
APACHE 2 HTTPS.ppt
APACHE 2 HTTPS.pptAPACHE 2 HTTPS.ppt
APACHE 2 HTTPS.ppt
 

More from Thomas Weinert (12)

PHPUG CGN: Controlling Arduino With PHP
PHPUG CGN: Controlling Arduino With PHPPHPUG CGN: Controlling Arduino With PHP
PHPUG CGN: Controlling Arduino With PHP
 
Controlling Arduino With PHP
Controlling Arduino With PHPControlling Arduino With PHP
Controlling Arduino With PHP
 
Decoupling Objects With Standard Interfaces
Decoupling Objects With Standard InterfacesDecoupling Objects With Standard Interfaces
Decoupling Objects With Standard Interfaces
 
Asynchronous I/O in PHP
Asynchronous I/O in PHPAsynchronous I/O in PHP
Asynchronous I/O in PHP
 
Lumberjack XPath 101
Lumberjack XPath 101Lumberjack XPath 101
Lumberjack XPath 101
 
FluentDom
FluentDomFluentDom
FluentDom
 
Optimizing Your Frontend Performance
Optimizing Your Frontend PerformanceOptimizing Your Frontend Performance
Optimizing Your Frontend Performance
 
Experiences With Pre Commit Hooks
Experiences With Pre Commit HooksExperiences With Pre Commit Hooks
Experiences With Pre Commit Hooks
 
The Lumber Mill - XSLT For Your Templates
The Lumber Mill  - XSLT For Your TemplatesThe Lumber Mill  - XSLT For Your Templates
The Lumber Mill - XSLT For Your Templates
 
The Lumber Mill Xslt For Your Templates
The Lumber Mill   Xslt For Your TemplatesThe Lumber Mill   Xslt For Your Templates
The Lumber Mill Xslt For Your Templates
 
SVN Hook
SVN HookSVN Hook
SVN Hook
 
Optimizing Your Frontend Performance
Optimizing Your Frontend PerformanceOptimizing Your Frontend Performance
Optimizing Your Frontend Performance
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Recently uploaded (20)

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
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
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
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
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
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
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
 
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...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
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
 

Deliver Files With PHP

  • 1. Deliver Files With PHP Thomas Weinert
  • 2. About me  Application Developer ▹ PHP ▹ XSLT/XPath ▹ (some) Javascript  papaya CMS ▹ PHP based Content Management System ▹ uses XSLT for Templates Thomas Weinert, papaya Software GmbH
  • 3. Steps  Block  Send  Check ▹ At Once ▹ Filename ▹ Piece By Piece ▹ File ▹ Limit  Tell  Optimize ▹ Date ▹ Traffic ▹ Size ▹ Performance ▹ Type ▹ Flash ▹ Name Thomas Weinert, papaya Software GmbH  Problems
  • 4. Block  Move outside document root  .htaccess ▹ Deny From All  Rewrite? Thomas Weinert, papaya Software GmbH
  • 5. Check Filename  dirname(), basename()  preg_match  strrpos() + substr()  against database ▹ Use hashed random strings for id ▹ Split at chars ▹ virtual directory structure Thomas Weinert, papaya Software GmbH
  • 6. Check File  file_exists() ▹ return true for directories  is_file()  is_readable() Thomas Weinert, papaya Software GmbH
  • 7. Check File Type  getimagesize() (no GD needed)  /usr/bin/file  ext/fileinfo (PHP 5.3) Thomas Weinert, papaya Software GmbH
  • 8. Tell Date  Last change header('Last-modified: '. gmdate('D, d M Y H:i:s', $fileDate.' GMT');  Valid until header('Expires: '. gmdate('D, d M Y H:i:s', $expireTime).' GMT'); Thomas Weinert, papaya Software GmbH
  • 9. Tell Size  Size ▹ Show progress in browser header('Content-length: '.$fileSize); Thomas Weinert, papaya Software GmbH
  • 10. Tell Type  File Mime Type header('Content-type: '.$mimeType);  Rewrite Filenames ▹ IE check filename Thomas Weinert, papaya Software GmbH
  • 11. Force Download  IE and Opera header('Content-type: application/octetstream');  Others header('Content-type: application/octet-stream'); Thomas Weinert, papaya Software GmbH
  • 12. Tell Filename  For files in browser or IE header('Content-disposition: inline; filename=quot;'. $data['file_name'].'quot;');  For downloads - except IE header('Content-disposition: attachment; filename=quot;'. $data['file_name'].'quot;');  Escape “ and in filename with Thomas Weinert, papaya Software GmbH
  • 13. Send – At Once  fpassthru()  readfile()  Pro: ▹ Easy  Contra: ▹ Less control Thomas Weinert, papaya Software GmbH
  • 14. Send - Piece By Piece  fread()  fseek()  echo, print()  flush() Thomas Weinert, papaya Software GmbH
  • 15. Send – Piece By Piece <?php if ($fh = fopen($localFileName, 'r')) { while (!feof($fh) && connection_status() == 0) { echo fread($fh, $bytesPerStep); flush(); } fclose($fh); } ?> Thomas Weinert, papaya Software GmbH
  • 16. Send – Piece By Piece <?php if ($fh = fopen($localFileName, 'r')) { //seek file to start position if ($fileOffset > 0) { fseek($fh, $fileOffset); } while (!feof($fh) && connection_status() == 0) { echo fread($fh, $bytesPerStep); flush(); } fclose($fh); } ?> Weinert, papaya Software GmbH Thomas
  • 17. Optimize - Traffic  Range-Header ▹ Send: ▪ header('Accept-Ranges: bytes'); ▹ Receive: ▪ $_SERVER['HTTP_RANGE'] ▪ bytes=[start1][]-[stop1][,start2][-][stop2][...]: ▹ Send: ▪ header('Accept-Ranges: bytes'); ▪ header('HTTP/1.1 206 Partial Content'); ▪ header(sprintf('Content-Range: bytes %d-%d/ %d', ...); Thomas Weinert, papaya Software GmbH
  • 18. Send – Bandwidth Limit  Track time and send bytes  Sleep some time if sent to fast ▹ usleep(), sleep()  Send first bytes without limit  Why? ▹ Video-Streaming ▹ User don't need all data Thomas Weinert, papaya Software GmbH
  • 19. if ($shapeRequest) { $bytesSend += $bytesPerStep; if ($bytesSend > $shapeLimitStart) { $timeDiff = microtime(TRUE) - $timeStart; $rate = ($bytesSend - $shapeLimitStart) / $timeDiff; if ($rate > $shapeLimitRate) { $sleepFunction($sleepTime); } } } Thomas Weinert, papaya Software GmbH
  • 20. Optimize - Performance  Close Sessions ▹ session_write_close()  X-Sendfile ▹ header('X-Sendfile: '.$localFileName); ▹ Header for Lighttpd ▹ Apache Extension Thomas Weinert, papaya Software GmbH
  • 21. Optimize – Flash I  Byte offset tables in video file ▹ ffmpeg ... -g 500 ...  Special player sends GET parameter ▹ JW FLV Player  Server checks GET parameter ▹ PHP script ▹ Lighttpd module Thomas Weinert, papaya Software GmbH
  • 22. Optimize – Flash – Meta Data Thomas Weinert, papaya Software GmbH
  • 23. Optimize – Flash II  Check for GET parameters ▹ start, pos, position  Output magic bytes ▹ $flashHeader = 'FLV'.pack('CCNN', 1, 5, 9, 0); ▹ 01 (version) 05 (audio and video) 00 00 00 09 (header size) 00 00 00 00 (size of previous tag)  Seek file  Output file Thomas Weinert, papaya Software GmbH
  • 24. Problems  will disable flush() / cause buffering ▹ ob_start() ▹ session.use_trans_sid ▹ zlib.output_compression ▹ http:/www.php.net/flush (Comments)  Adobe Acrobat Reader in IE has buggy Range headers support Thomas Weinert, papaya Software GmbH
  • 25. Links  X-Sendfile ▹ http://blog.lighttpd.net/articles/2006/07/02/x- sendfile ▹ http://tn123.ath.cx/mod_xsendfile/  Flash ▹ http://www.jeroenwijering.com/ ▹ http://ffmpeg.mplayerhq.hu/ ▹ Thomas Weinert, papaya Software GmbH  http://www.abasketfulofpapayas.de/