ResponseFile.php 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace KarmaFW\App;
  3. class ResponseFile extends Response
  4. {
  5. protected $file_path;
  6. public function __construct($file_path)
  7. {
  8. parent::__construct('', null);
  9. $this->file_path = $file_path;
  10. }
  11. public function sendHeaders()
  12. {
  13. if ($this->headers_sent) {
  14. // Warning: headers already sent
  15. //error_log("Warning: headers already sent");
  16. //return;
  17. }
  18. if (! is_file($this->file_path)) {
  19. // File not found
  20. $this->headers['Content-Length'] = 0;
  21. } else {
  22. $this->headers['Content-Length'] = filesize($this->file_path);
  23. $this->headers['Content-Type'] = "application/octet-stream";
  24. $this->headers['Content-Transfer-Encoding'] = "Binary";
  25. $this->headers['Content-disposition'] = 'attachment; filename="' . basename($this->file_path) . '"';
  26. }
  27. parent::sendHeaders();
  28. }
  29. public function send()
  30. {
  31. if (! is_file($this->file_path)) {
  32. // ERROR 404
  33. $this->setStatus(404);
  34. }
  35. if ($this->headers_sent) {
  36. // Warning: redirect may not work
  37. }
  38. $this->sendHeaders();
  39. if (is_file($this->file_path)) {
  40. readfile($this->file_path);
  41. } else {
  42. echo "File not found";
  43. }
  44. }
  45. }