Files
zhamao-framework/src/ZM/Http/StaticFileHandler.php

35 lines
1020 B
PHP
Raw Normal View History

2020-05-23 17:23:29 +08:00
<?php
declare(strict_types=1);
2020-05-23 17:23:29 +08:00
namespace ZM\Http;
2020-10-03 23:00:18 +08:00
use ZM\Config\ZMConfig;
2020-08-31 10:11:06 +08:00
use ZM\Console\Console;
2020-09-29 15:07:43 +08:00
use ZM\Utils\HttpUtil;
2020-05-23 17:23:29 +08:00
class StaticFileHandler
{
public function __construct($filename, $path)
{
$full_path = realpath($path . '/' . $filename);
2020-05-23 17:23:29 +08:00
$response = ctx()->getResponse();
Console::debug('Full path: ' . $full_path);
2020-05-23 17:23:29 +08:00
if ($full_path !== false) {
if (strpos($full_path, $path) !== 0) {
$response->status(403);
$response->end('403 Forbidden');
2022-04-03 01:47:38 +08:00
return;
}
if (is_file($full_path)) {
$exp = strtolower(pathinfo($full_path)['extension'] ?? 'unknown');
$response->setHeader('Content-Type', ZMConfig::get('file_header')[$exp] ?? 'application/octet-stream');
$response->end(file_get_contents($full_path));
2022-04-03 01:47:38 +08:00
return;
2020-05-23 17:23:29 +08:00
}
}
$response->status(404);
2020-09-29 15:07:43 +08:00
$response->end(HttpUtil::getHttpCodePage(404));
2020-05-23 17:23:29 +08:00
}
}