|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Application\Handler; |
|
6
|
|
|
|
|
7
|
|
|
use Ecodev\Felix\Handler\AbstractHandler; |
|
8
|
|
|
use Laminas\Diactoros\Response; |
|
9
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
10
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
|
11
|
|
|
|
|
12
|
|
|
class DownloadFile extends AbstractHandler |
|
13
|
|
|
{ |
|
14
|
|
|
public const COUNTER_PATH = 'data/download-file-counter/counter.txt'; |
|
15
|
|
|
|
|
16
|
|
|
public function handle(ServerRequestInterface $request): ResponseInterface |
|
17
|
|
|
{ |
|
18
|
|
|
$path = 'data/download-file-counter/file.pdf'; |
|
19
|
|
|
$cookie_name = 'artisans_pdf_download_1'; |
|
20
|
|
|
|
|
21
|
|
|
// Increment counter if no cookie = first visit |
|
22
|
|
|
if (!isset($_COOKIE[$cookie_name])) { |
|
23
|
|
|
$download_count = 0; |
|
24
|
|
|
if (file_exists(self::COUNTER_PATH)) { |
|
25
|
|
|
$download_count = (int) (file_get_contents(self::COUNTER_PATH)); |
|
26
|
|
|
} |
|
27
|
|
|
++$download_count; |
|
28
|
|
|
file_put_contents(self::COUNTER_PATH, $download_count); |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
// Flag cookie |
|
32
|
|
|
setcookie($cookie_name, 'true', time() + (86400 * 60), '/'); // 60 days |
|
33
|
|
|
|
|
34
|
|
|
if (!is_readable($path)) { |
|
35
|
|
|
return $this->createError('File not found on disk, or not readable'); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
$resource = fopen($path, 'rb'); |
|
39
|
|
|
if ($resource === false) { |
|
40
|
|
|
return $this->createError('Cannot open file on disk'); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
$size = filesize($path); |
|
44
|
|
|
$response = new Response($resource, 200, [ |
|
45
|
|
|
'content-type' => 'application/pdf', |
|
46
|
|
|
'Content-Disposition' => 'attachment; filename="' . basename($path) . '"', |
|
47
|
|
|
'content-length' => $size, |
|
48
|
|
|
]); |
|
49
|
|
|
|
|
50
|
|
|
return $response; |
|
51
|
|
|
} |
|
52
|
|
|
} |
|
53
|
|
|
|