Download.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. /**
  3. *
  4. * Cube Framework $Id$ bF6RH8EP0LAOZVfnlUv5tEoyYYq2MVtovWbFWj2gqWk=
  5. *
  6. * @link http://codecu.be/framework
  7. * @copyright Copyright (c) 2014 CodeCube SRL
  8. * @license http://codecu.be/framework/license Commercial License
  9. *
  10. * @version 1.0
  11. */
  12. /**
  13. * download file class
  14. */
  15. namespace Cube\Http;
  16. use Cube\Controller\Response\AbstractResponse;
  17. class Download extends AbstractResponse
  18. {
  19. /**
  20. *
  21. * real path to the file or false if the file does not exist
  22. *
  23. * @var string|false
  24. */
  25. protected $_filePath = false;
  26. /**
  27. *
  28. * class constructor
  29. *
  30. * @param string|null $file
  31. */
  32. public function __construct($file = null)
  33. {
  34. if ($file !== null) {
  35. $this->setFilePath($file);
  36. }
  37. }
  38. /**
  39. *
  40. * set real path to the file to be downloaded
  41. *
  42. * @param string $filePath
  43. * @return $this
  44. */
  45. public function setFilePath($filePath)
  46. {
  47. $this->_filePath = realpath($filePath);
  48. return $this;
  49. }
  50. /**
  51. *
  52. * get real file path
  53. *
  54. * @return string
  55. */
  56. public function getFilePath()
  57. {
  58. return $this->_filePath;
  59. }
  60. /**
  61. *
  62. * if the file exists, create a download request and stop all other executions
  63. *
  64. * @return null|mixed
  65. */
  66. public function send()
  67. {
  68. if (($filePath = $this->getFilePath()) !== false) {
  69. $this->setHeader('Content-Type: application/octet-stream')
  70. ->addHeader('Content-Disposition: attachment; filename="' . basename($filePath) . '"')
  71. ->addHeader('Content-Length: ' . filesize($filePath));
  72. $this->setBody(
  73. readfile($filePath));
  74. parent::send();
  75. exit(0);
  76. }
  77. return null;
  78. }
  79. }