SlideShare uma empresa Scribd logo
1 de 25
Baixar para ler 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/

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Destaque

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
 

Destaque (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
 

Semelhante a 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- 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
 
Flash templates for Joomla!
Flash templates for Joomla!Flash templates for Joomla!
Flash templates for Joomla!Herman Peeren
 
Jordan Hubbard Talk @ LISA
Jordan Hubbard Talk @ LISAJordan Hubbard Talk @ LISA
Jordan Hubbard Talk @ LISAguest4c923d
 

Semelhante a 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- 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
 
Flash templates for Joomla!
Flash templates for Joomla!Flash templates for Joomla!
Flash templates for Joomla!
 
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
 

Mais de 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
 

Mais de 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
 

Último

Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
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
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
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
 
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
 
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
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 

Último (20)

Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
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
 
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
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
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
 
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
 
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
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 

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/