ResponseFile.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. $content_type = mime_content_type($this->file_path);
  23. if (empty($content_type)) {
  24. $content_type = "application/octet-stream";
  25. }
  26. $this->headers['Content-Length'] = filesize($this->file_path);
  27. $this->headers['Content-Type'] = $content_type;
  28. $this->headers['Content-Transfer-Encoding'] = "Binary";
  29. $this->headers['Content-disposition'] = 'attachment; filename="' . basename($this->file_path) . '"';
  30. }
  31. parent::sendHeaders();
  32. }
  33. public function send()
  34. {
  35. if (! is_file($this->file_path)) {
  36. // ERROR 404
  37. $this->setStatus(404);
  38. }
  39. if ($this->headers_sent) {
  40. // Warning: redirect may not work
  41. }
  42. $this->sendHeaders();
  43. if (is_file($this->file_path)) {
  44. readfile($this->file_path);
  45. } else {
  46. echo "File not found";
  47. }
  48. }
  49. }