Skip to content

Instantly share code, notes, and snippets.

@noodlehaus
Last active December 25, 2015 14:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noodlehaus/882d4e6c6c8d780f8bc4 to your computer and use it in GitHub Desktop.
Save noodlehaus/882d4e6c6c8d780f8bc4 to your computer and use it in GitHub Desktop.
badphp\context
<?php
require __DIR__.'/request.php';
require __DIR__.'/response.php';
use badphp\context\request;
use badphp\context\response;
/**
* Request handling examples
*/
// get cookies, headers, and files
$cookie = request\cookies('id');
$header = request\headers('x-auth-token');
$upload = request\attachment('photo');
// get a POST form field, or a GET field
$post_field = request\form('name');
$get_field = request\query('page');
// get request body as file, or directly
$content_path = request\body();
$content = request\body(false);
// some utilities
$path = request\path();
$method = request\method();
/**
* Response handling examples
*/
// create a stack of headers
$headers = [
response\cookies('name', 'noodlehaus'),
response\cookies('code', 'robin', '/'),
response\headers('x-author', 'Jesus A. Domingo')
];
// multiple ways of rendering a response
response\render("hello");
response\render(200, "hello");
response\render(200, $headers, "hello");
response\render($headers, "hello");
// stream a file
response\stream($path_to_file);
<?php
namespace badphp\context\request;
function cookies($name, $def = null)
{
return isset($_COOKIE[$name]) ? $_COOKIE[$name] : $def;
}
function headers($name, $def = null)
{
static $headers = null;
if (!$headers) {
if (function_exists('getallheaders')) {
$headers = \getallheaders();
} else {
$special = ['CONTENT_LENGTH', 'CONTENT_MD5', 'CONTENT_TYPE'];
foreach ($_SERVER as $key => $data) {
if (0 === strpos($key, 'HTTP_')) {
$headers[str_replace('_', '-', substr($key, 5))] = $data;
} else if (in_array($key, $special)) {
$headers[str_replace('_', '-', $key)] = $data;
}
}
}
$headers = array_change_key_case($headers);
}
$name = strtolower($name);
return isset($headers[$name]) ? $headers[$name] : $def;
}
function attachment($name)
{
static $cache = [];
// if file's already in cache, return it
if (isset($cache[$name])) {
return $cache[$name];
}
if (!isset($_FILES[$name])) {
return null;
}
// single-file attachment
if (!is_array($_FILES[$name]['name'])) {
return ($cache[$name] = $_FILES[$name]);
}
// attachment is an array
$result = [];
// consolidate file info
foreach ($_FILES[$name] as $k1 => $v1) {
foreach ($v1 as $k2 => $v2) {
$result[$k2][$k1] = $v2;
}
}
// cache and return array uploads
return ($cache[$name] = $result);
}
function form($name, $def = null)
{
return isset($_POST[$name]) ? $_POST[$name] : $def;
}
function query($name, $def = null)
{
return isset($_GET[$name]) ? $_GET[$name] : $def;
}
function body($load = false)
{
static $tmp = null;
// if it's already been done before, return it
if ($tmp !== null) {
return $tmp;
}
// default behaviour
if (!$load) {
$src = fopen('php://input', 'rb');
$tmp = fopen(tempnam(sys_get_temp_dir(), 'phpreq'), 'wb');
stream_copy_to_stream($src, $tmp);
fclose($tmp);
return $tmp;
}
// we got here, so we load directly
return file_get_contents('php://input');
}
function path()
{
return parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
}
function method()
{
return strtoupper(trim($_SERVER['REQUEST_METHOD']));
}
<?php
namespace badphp\context\response;
function cookies($name, $value)
{
$args = func_get_args();
array_unshift($args, 1);
return $args;
}
function headers($name, $value, $replace = true)
{
return [0, $name, $value, $replace];
}
function render($content)
{
$args = array_slice(func_get_args(), 0, 3);
$argn = count($args);
switch ($argn) {
case 3:
list($status, $headers, $content) = $args;
break;
case 2:
list($status, $content) = $args;
if (is_array($status)) {
$headers = $status;
$status = 200;
} else {
$headers = [];
}
break;
}
http_response_code($status);
foreach ($headers as $h) {
if ($h[0] === 0) {
header("{$h[1]}: {$h[2]}", $h[3]);
} else if ($h[0] === 1) {
call_user_func_array('setcookie', array_slice($h, 1));
}
}
if (is_string($content)) {
print $content;
return;
}
// copy stream to out, 8k at a time
if (is_resource($content) && in_array(get_resource_type($content), ['file', 'stream'])) {
$stream = fopen('php://output', 'wb');
while (!feof($content)) {
fwrite($stream, fread($content, 8192));
}
fclose($stream);
}
}
function stream($path, $headers = [])
{
if (!file_exists($path)) {
trigger_error(__FUNCTION__.": File not found [{$path}]", E_USER_ERROR);
}
if (!$headers) {
$headers = [
header('content-disposition: filename="'.basename($path).'"'),
header('content-type: application/octet-stream'),
header('content-length: '.filesize($path)),
header('content-transfer-encoding: binary')
];
}
render(200, $headers, $fp = fopen($path, 'rb'));
fclose($fp);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment