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

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 @ PHPTourWim Godden
 
eZ Publish Cluster Unleashed
eZ Publish Cluster UnleashedeZ Publish Cluster Unleashed
eZ Publish Cluster UnleashedBertrand Dunogier
 
Filesystem Abstraction with Flysystem
Filesystem Abstraction with FlysystemFilesystem Abstraction with Flysystem
Filesystem Abstraction with FlysystemFrank de Jonge
 
Firefox OS + Raspberry Pi
Firefox OS + Raspberry PiFirefox OS + Raspberry Pi
Firefox OS + Raspberry PiEnsekiTT
 
05 File Handling Upload Mysql
05 File Handling Upload Mysql05 File Handling Upload Mysql
05 File Handling Upload MysqlGeshan Manandhar
 
Introducation to php for beginners
Introducation to php for beginners Introducation to php for beginners
Introducation to php for beginners musrath mohammad
 
phptek13 - Caching and tuning fun tutorial
phptek13 - Caching and tuning fun tutorialphptek13 - Caching and tuning fun tutorial
phptek13 - Caching and tuning fun tutorialWim Godden
 
Fun with processes - lightning talk
Fun with processes - lightning talkFun with processes - lightning talk
Fun with processes - lightning talkPaweł Dawczak
 
File include
File includeFile include
File includeRoy
 
PHP language presentation
PHP language presentationPHP language presentation
PHP language presentationAnnujj Agrawaal
 
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 codeWim Godden
 
Php file upload, cookies & session
Php file upload, cookies & sessionPhp file upload, cookies & session
Php file upload, cookies & sessionJamshid 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

Php Form
Php FormPhp Form
Php Formlotlot
 
Chapter 07 php forms handling
Chapter 07   php forms handlingChapter 07   php forms handling
Chapter 07 php forms handlingDhani Ahmad
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and SessionsNisa Soomro
 
PHP Files: An Introduction
PHP Files: An IntroductionPHP Files: An Introduction
PHP Files: An IntroductionJacques Woodcock
 
PHP Cookies, Sessions and Authentication
PHP Cookies, Sessions and AuthenticationPHP Cookies, Sessions and Authentication
PHP Cookies, Sessions and AuthenticationGerard Sychay
 
Form Processing In Php
Form Processing In PhpForm Processing In Php
Form Processing In PhpHarit Kothari
 

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 PerformanceThomas Weinert
 
Apache and PHP: Why httpd.conf is your new BFF!
Apache and PHP: Why httpd.conf is your new BFF!Apache and PHP: Why httpd.conf is your new BFF!
Apache and PHP: Why httpd.conf is your new BFF!Jeff Jones
 
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 2009Helgi Þormar Þorbjörnsson
 
Bubbles & Trees with jQuery
Bubbles & Trees with jQueryBubbles & Trees with jQuery
Bubbles & Trees with jQueryBastian Feder
 
Employing Custom Fonts
Employing Custom FontsEmploying Custom Fonts
Employing Custom FontsPaul Irish
 
RPM: Speed up your deploy
RPM: Speed up your deployRPM: Speed up your deploy
RPM: Speed up your deployfcrippa
 
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ónFranco Cedillo
 
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 ScriptingRoy Zimmer
 
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 2008Helgi Þormar Þorbjörnsson
 
Centralized + Unified Logging
Centralized + Unified LoggingCentralized + Unified Logging
Centralized + Unified LoggingGabor Kozma
 
PHP Presentation
PHP PresentationPHP Presentation
PHP PresentationAnkush Jain
 
Flash templates for Joomla!
Flash templates for Joomla!Flash templates for Joomla!
Flash templates for Joomla!Herman Peeren
 
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 #jd09nlJoomla!Days Netherlands
 
Jordan Hubbard Talk @ LISA
Jordan Hubbard Talk @ LISAJordan Hubbard Talk @ LISA
Jordan Hubbard Talk @ LISAguest4c923d
 

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

PHPUG CGN: Controlling Arduino With PHP
PHPUG CGN: Controlling Arduino With PHPPHPUG CGN: Controlling Arduino With PHP
PHPUG CGN: Controlling Arduino With PHPThomas Weinert
 
Controlling Arduino With PHP
Controlling Arduino With PHPControlling Arduino With PHP
Controlling Arduino With PHPThomas Weinert
 
Decoupling Objects With Standard Interfaces
Decoupling Objects With Standard InterfacesDecoupling Objects With Standard Interfaces
Decoupling Objects With Standard InterfacesThomas Weinert
 
Asynchronous I/O in PHP
Asynchronous I/O in PHPAsynchronous I/O in PHP
Asynchronous I/O in PHPThomas Weinert
 
Optimizing Your Frontend Performance
Optimizing Your Frontend PerformanceOptimizing Your Frontend Performance
Optimizing Your Frontend PerformanceThomas Weinert
 
Experiences With Pre Commit Hooks
Experiences With Pre Commit HooksExperiences With Pre Commit Hooks
Experiences With Pre Commit HooksThomas Weinert
 
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 TemplatesThomas Weinert
 
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 TemplatesThomas Weinert
 
Optimizing Your Frontend Performance
Optimizing Your Frontend PerformanceOptimizing Your Frontend Performance
Optimizing Your Frontend PerformanceThomas Weinert
 

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

Connecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAKConnecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAKUXDXConf
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxJennifer Lim
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityScyllaDB
 
Agentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfAgentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfChristopherTHyatt
 
Introduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationIntroduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationZilliz
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...CzechDreamin
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoTAnalytics
 
AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101vincent683379
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...CzechDreamin
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfFIDO Alliance
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsStefano
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeCzechDreamin
 
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FIDO Alliance
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfFIDO Alliance
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераMark Opanasiuk
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...FIDO Alliance
 
Top 10 Symfony Development Companies 2024
Top 10 Symfony Development Companies 2024Top 10 Symfony Development Companies 2024
Top 10 Symfony Development Companies 2024TopCSSGallery
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomCzechDreamin
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka DoktorováCzechDreamin
 

Recently uploaded (20)

Connecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAKConnecting the Dots in Product Design at KAYAK
Connecting the Dots in Product Design at KAYAK
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
 
Optimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through ObservabilityOptimizing NoSQL Performance Through Observability
Optimizing NoSQL Performance Through Observability
 
Agentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdfAgentic RAG What it is its types applications and implementation.pdf
Agentic RAG What it is its types applications and implementation.pdf
 
Introduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG EvaluationIntroduction to Open Source RAG and RAG Evaluation
Introduction to Open Source RAG and RAG Evaluation
 
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
Behind the Scenes From the Manager's Chair: Decoding the Secrets of Successfu...
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024
 
AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101
 
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
SOQL 201 for Admins & Developers: Slice & Dice Your Org’s Data With Aggregate...
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
 
PLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. StartupsPLAI - Acceleration Program for Generative A.I. Startups
PLAI - Acceleration Program for Generative A.I. Startups
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
 
Top 10 Symfony Development Companies 2024
Top 10 Symfony Development Companies 2024Top 10 Symfony Development Companies 2024
Top 10 Symfony Development Companies 2024
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdf
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
 

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/