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

[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
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
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 

Último (20)

[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 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
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 

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/