SendFile.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author linkec<linkec@live.com>
  10. * @copyright linkec<linkec@live.com>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace Workerman\Lib;
  15. use Workerman\Events\EventInterface;
  16. use Workerman\Worker;
  17. use Exception;
  18. class SendFile
  19. {
  20. private $connection = null;
  21. private $handle = null;
  22. private $offset = 0;
  23. private $fileSize = 0;
  24. private $chunkSize = 1048576;
  25. function __construct($connection,$file)
  26. {
  27. $this->connection = $connection;
  28. if(!file_exists($file)){
  29. return;
  30. }
  31. $this->fileSize = filesize($file);
  32. $this->handle = fopen($file,"rb");
  33. }
  34. public function _sendFile($socket)
  35. {
  36. if($this->offset>$this->fileSize){
  37. //release handle and remove event
  38. fclose($this->handle);
  39. Worker::$globalEvent->del($socket, EventInterface::EV_WRITE);
  40. return;
  41. }
  42. eio_sendfile($socket,$this->handle,$this->offset,$this->chunkSize);
  43. $this->offset += $this->chunkSize;
  44. eio_event_loop();
  45. }
  46. public function send(){
  47. if(!$this->handle){
  48. $header = "HTTP/1.1 404 Content Not Found\r\n";
  49. $header .= "Content-Type: text/html;\r\n";
  50. $header .= "Server: workerman/" . Worker::VERSION . "\r\n";
  51. $header .= "\r\n";
  52. $content = '<h1>404 Content Not Found!</h1>';
  53. $this->connection->send($header.$content,true);
  54. return;
  55. }
  56. // Default http-code.
  57. if (!isset(\Workerman\Protocols\HttpCache::$header['Http-Code'])) {
  58. $header = "HTTP/1.1 200 OK\r\n";
  59. } else {
  60. $header = \Workerman\Protocols\HttpCache::$header['Http-Code'] . "\r\n";
  61. unset(\Workerman\Protocols\HttpCache::$header['Http-Code']);
  62. }
  63. // Content-Type
  64. if (!isset(\Workerman\Protocols\HttpCache::$header['Content-Type'])) {
  65. $header .= "Content-Type: application/octet-stream;\r\n";
  66. }
  67. // header
  68. $header .= "Server: workerman/" . Worker::VERSION . "\r\n";
  69. $header .= "Content-Length: ". $this->fileSize .";\r\n";
  70. $header .= "\r\n";
  71. $this->connection->send($header,true);
  72. //regist event
  73. Worker::$globalEvent->add($this->connection->getSocket(), EventInterface::EV_WRITE, array($this, '_sendFile'));
  74. }
  75. }