microphp/Core/Response.php

88 lines
2.9 KiB
PHP
Raw Normal View History

2023-04-02 10:00:20 +03:00
<?php
include_once "RequestHeader.php";
class Response
{
public static function File($path, $mime = "auto")
{
if($mime == "auto")
{
$mime = mime_content_type($path);
};
2023-04-07 01:02:39 +03:00
$fp = fopen($path, 'rb');
fpassthru($fp);
fclose($fp);
2023-04-02 10:00:20 +03:00
}
public static function Download($path, $mimetrue = false)
{
if($mimetrue == false)
{
RequestHeader::set("Content-Type","application/octet-stream");
}
RequestHeader::set("Content-Transfer-Encoding","Binary");
RequestHeader::set("Content-Disposition",'attachment; filename="'.basename($path).'"');
RequestHeader::set("Content-Length",filesize($path));
2023-04-07 01:02:39 +03:00
$fp = fopen($path, 'rb');
fpassthru($fp);
fclose($fp);
2023-04-02 10:00:20 +03:00
}
public static function Text($content, $encoding = "utf8")
{
RequestHeader::set("Content-Length",strlen($content));
RequestHeader::set("Content-Type","text/plain; charset=$encoding");
echo $content;
}
public static function Json($content, $encoding = "utf8")
{
$content = json_encode($content);
RequestHeader::set("Content-Length",strlen($content));
RequestHeader::set("Content-Type","application/json; charset=$encoding");
echo $content;
}
public static function HTML($content, $encoding = "utf8")
{
RequestHeader::set("Content-Length",strlen($content));
RequestHeader::set("Content-Type","text/html; charset=$encoding");
echo $content;
}
public static function Code($code = 200)
{
http_response_code($code);
}
public static function send($content)
{
switch(gettype($content))
{
case "boolean":
case "integer":
case "double":
case "float":
case "string":{
Response::Text($content);
break;
}
2023-04-02 18:07:52 +03:00
case "object":{
if(method_exists($content, "__toString"))
{
return Response::Text($content->__toString());
}else{
return Response::Json($content);
}
}
2023-04-02 10:00:20 +03:00
case "array":{
Response::Json($content);
break;
}
default:{
throw new Exception("unknown type");
}
}
}
public static function Redirect($path, $code = 307)
{
http_response_code($code);
header("location: $path");
}
2023-04-07 01:02:39 +03:00
};
define("response", new Response(), false);