protected function sendHeaders() { // setup the status code http_response_code($this->response_status_code); // collect current headers into array $headers = headers_list(); foreach ($headers as $h) { $h_parts = explode(":", $h); if (array_key_exists($h_parts[0], $this->response_headers)) { continue; } $this->response_headers[$h_parts[0]] = $h_parts[1]; } // response type $this->response_headers["Content-Type"] = $this->response_content_type; if (!is_null($this->response_content_charset)) { $this->response_headers["Content-Type"] .= "; charset=" . $this->response_content_charset; } // put own headers header_remove(); foreach ($this->response_headers as $key => $value) { header($key . ":" . $value); } return; }
/** * Example of function that defines a setup process common to all the * application. May be take as a template, or used as-is. Suggestions on new * things to include or ways to improve it are welcome :) */ function bootstrap(int $env = Env::PROD) { // Set the encoding of the mb_* functions mb_internal_encoding('UTF-8'); // Set the same timezone as the one used by the database date_default_timezone_set('UTC'); // Get rid of PHP's default custom header header_remove('X-Powered-By'); // Determine the current environment Env::set($env); // Control which errors are fired depending on the environment if (Env::isProd()) { error_reporting(0); ini_set('display_errors', '0'); } else { error_reporting(E_ALL & ~E_NOTICE); ini_set('display_errors', '1'); } // Handling errors from exceptions set_exception_handler(function (\Throwable $e) { $data = ['title' => 'Unexpected exception', 'detail' => $e->getMessage() ?: '']; if (Env::isDev()) { $data['debug'] = ['exception' => get_class($e) . ' (' . $e->getCode() . ')', 'file' => $e->getFile() . ':' . $e->getLine(), 'trace' => $e->getTrace()]; } (new Response(HttpStatus::InternalServerError, [], $data))->send(); }); // Handling errors from trigger_error and the alike set_error_handler(function (int $errno, string $errstr, string $errfile, int $errline, array $errcontext) { $data = ['title' => 'Unexpected error', 'detail' => $errstr ?: '']; if (Env::isDev()) { $data['debug'] = ['error' => $errno, 'file' => $errfile . ':' . $errline, 'context' => $errcontext]; } (new Response(HttpStatus::InternalServerError, [], $data))->send(); }); }
public static function init($timezone) { mb_internal_encoding('utf-8'); if (!empty($timezone)) { @date_default_timezone_set($timezone); } header('Content-type: text/html; charset=utf-8'); // prevent caching/storage of sensitive data header('Expires: Mon, 24 Mar 2008 00:00:00 GMT'); header('Cache-Control: no-cache, no-store'); // prevent clickjacking header('X-Frame-Options: sameorigin'); // prevent content sniffing (MIME sniffing) header('X-Content-Type-Options: nosniff'); if (self::FORCE_HTTPS) { // use HTTP Strict Transport Security (HSTS) with a period of three months header('Strict-Transport-Security: max-age=7884000'); } // remove unnecessary HTTP headers header_remove('X-Powered-By'); // present a link to the project's bug bounty to people who check the HTTP headers header('X-Bug-Bounty: http://security.localize.im/'); if (self::ERROR_REPORTING_ON) { error_reporting(E_ALL); ini_set('display_errors', 'stdout'); } else { error_reporting(0); ini_set('display_errors', 'stderr'); } self::$page = isset($_GET['p']) && is_string($_GET['p']) ? trim($_GET['p']) : ''; self::$actionPOST = isset($_POST) ? $_POST : array(); self::$actionGET = isset($_GET) ? $_GET : array(); self::$breadcrumbPath = array(); self::$breadcrumbDisabled = false; }
public function __construct() { $this->stack[] = function (RequestInterface $req) : ResponseInterface { try { ob_start(); $res = $this->run($req->getUrl()->getPath(), $req->getMethod()); if (!$res instanceof ResponseInterface) { $body = ob_get_contents(); $headers = headers_list(); $code = http_response_code(); @header_remove(); $res = (new Response($code ? $code : 200))->setBody(strlen($body) ? $body : (string) $res); foreach ($headers as $header) { $header = array_map('trim', explode(':', $header, 2)); $res->setHeader($header[0], $header[1]); } } ob_end_clean(); } catch (\Exception $e) { ob_end_clean(); throw $e; } return $res; }; }
public function buildOutput() { // Must have controller if (is_null($this->controller)) { return ''; } $controller = $this->controller; $responseCode = $controller->getResponseCode(); $contentType = $controller->getContentType(); $controllerHeaderList = $controller->getHeaderList(); $headersList = headers_list(); // Always remove the Content-Type header, let Jolt handle it header_remove('Content-Type'); header("Content-Type: {$contentType}", true, $responseCode); // Go through the list of headers to send, if they exist in the // $controllerHeaderList, unset them foreach ($headersList as $fullHeader) { foreach ($controllerHeaderList as $header => $value) { if (false !== stripos($fullHeader, $header)) { header_remove($header); } header("{$header}: {$value}", true, $responseCode); } } $renderedController = $this->controller->getRenderedController(); return $renderedController; }
function make_export() { if ($this->request->isset_GET('download') && ($this->request->isset_GET('page') && $this->request->GET('page') == 'tf_export')) { remove_filter('the_title_rss', 'strip_tags'); remove_filter('the_title_rss', 'ent2ncr', 8); remove_filter('the_title_rss', 'esc_html'); add_filter('the_title_rss', array($this, 'tfuse_post_title_export'), 99, 1); ob_start(); require_once './includes/export.php'; export_wp(array('content' => 'all')); if (version_compare(PHP_VERSION, '5.3.0', '>=')) { header_remove('Content-Description'); header_remove('Content-Disposition'); } else { header("Content-Description: "); header("Content-Disposition: "); } $buffer = ob_get_contents(); ob_end_clean(); $buffer = explode('</rss>', $buffer); $tmp = explode('/', site_url()); $multi = is_multisite() ? '-' . end($tmp) : ''; $this->export_wp_filename = 'wordpress-' . TF_THEME_PREFIX . $multi . '.xml_.txt'; $this->content = $buffer[0] . $this->tfuse_options_export() . '</rss>'; // $this->download_export($this->content); // die(); } }
/** * Unset the X-Pingback HTTP header. * * @hook * * @priority 20 */ public function template_redirect() { $headers = headers_list(); if (preg_grep('/X-Pingback:/', $headers)) { header_remove('X-Pingback'); } }
public function start($filename) { $ext = strtolower(strrchr($filename, '.')); $type = $this->mime_types[$ext]; if ($ext == '.csv') { $this->seperator = ','; } set_time_limit(0); header('Content-Type: application/octet-stream'); header('Content-Description: File Transfer'); header('Content-Type: ' . $type); header('Content-Disposition: attachment;filename="' . $filename . '"'); $seconds = 30; header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $seconds) . ' GMT'); header('Cache-Control: max-age=' . $seconds . ', s-maxage=' . $seconds . ', must-revalidate, proxy-revalidate'); session_cache_limiter(false); // Disable session_start() caching headers if (session_id()) { // Remove Pragma: no-cache generated by session_start() if (function_exists('header_remove')) { header_remove('Pragma'); } else { header('Pragma:'); } } }
public function renderRaw() { $attachment = $this->_params['attachment']; if (!headers_sent() && function_exists('header_remove')) { header_remove('Expires'); header('Cache-control: private'); } $extension = XenForo_Helper_File::getFileExtension($attachment['filename']); $imageTypes = array('svg' => 'image/svg+xml', 'gif' => 'image/gif', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpe' => 'image/jpeg', 'png' => 'image/png'); if (isset($imageTypes[$extension]) && ($attachment['width'] && $attachment['height'])) { $this->_response->setHeader('Content-type', $imageTypes[$extension], true); $this->setDownloadFileName($attachment['filename'], true); } else { $this->_response->setHeader('Content-type', 'application/octet-stream', true); $this->setDownloadFileName($attachment['filename']); } $this->_response->setHeader('ETag', '"' . $attachment['attach_date'] . '"', true); $this->_response->setHeader('Content-Length', $attachment['file_size'], true); $this->_response->setHeader('X-Content-Type-Options', 'nosniff'); $attachmentFile = $this->_params['attachmentFile']; $options = XenForo_Application::getOptions(); if ($options->SV_AttachImpro_XAR) { if (SV_AttachmentImprovements_AttachmentHelper::ConvertFilename($attachmentFile)) { if (XenForo_Application::debugMode() && $options->SV_AttachImpro_log) { XenForo_Error::debug('X-Accel-Redirect:' . $attachmentFile); } $this->_response->setHeader('X-Accel-Redirect', $attachmentFile); return ''; } if (XenForo_Application::debugMode() && $options->SV_AttachImpro_log) { XenForo_Error::debug('X-Accel-Redirect skipped'); } } return new XenForo_FileOutput($attachmentFile); }
function downloadFile() { global $wp_query; if ($wp_query->get('private_file_post_type') && $wp_query->get('private_file_meta_name') && $wp_query->get('private_file_post_id')) { $post_type = $wp_query->get('private_file_post_type'); $post_id = $wp_query->get('private_file_post_id'); $meta_name = $wp_query->get('private_file_meta_name'); if ($post_type == $this->_config['post_type'] && $meta_name == $this->_config['meta_name']) { $access_function = $this->_config['access_control']; if (!$access_function()) { header_remove(); http_response_code(403); die('403'); } $filename = $this->getFilePath($post_id); if (!$filename || !file_exists($filename)) { header_remove(); http_response_code(404); die('404'); } $finfo = finfo_open(FILEINFO_MIME_TYPE); $mime_type = finfo_file($finfo, $filename); header('Content-type: ' . $mime_type); header('Content-Disposition: attachment; filename="' . basename($filename) . '"'); readfile($filename); do_action('download_private_file', array('post_type' => $post_type, 'meta_name' => $meta_name, 'post_id' => $post_id)); add_post_meta($post_id, $this->_config['meta_name'] . ':download', get_current_user_id()); die; } } }
protected function EventSkin() { $aParams = $this->GetParams(); $sSkinName = array_shift($aParams); $sRelPath = implode('/', $aParams); $sOriginalFile = Config::Get('path.skins.dir') . $sSkinName . '/' . $sRelPath; if (F::File_Exists($sOriginalFile)) { $sAssetFile = F::File_GetAssetDir() . 'skin/' . $sSkinName . '/' . $sRelPath; if (F::File_Copy($sOriginalFile, $sAssetFile)) { if (headers_sent($sFile, $nLine)) { $sUrl = F::File_GetAssetUrl() . 'skin/' . $sSkinName . '/' . $sRelPath; if (strpos($sUrl, '?')) { $sUrl .= '&' . uniqid(); } else { $sUrl .= '?' . uniqid(); } R::Location($sUrl); } else { header_remove(); if ($sMimeType = F::File_MimeType($sAssetFile)) { header('Content-Type: ' . $sMimeType); } echo file_get_contents($sAssetFile); exit; } } } F::HttpHeader('404 Not Found'); exit; }
private function GetFile($contentType, $cacheLife, $directory, $plugin, $filename) { $cacheDir = \Application::$pluginDirectory; $file = $cacheDir . "{$plugin}/{$directory}/{$filename}"; if (is_file($file)) { $last_modified_time = filemtime($file); $etag = md5_file($file); header('Last-modified: ' . gmdate('D, d M Y H:i:s', $_SERVER['REQUEST_TIME']) . ' GMT'); header("Etag: {$etag}"); if ((isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && @strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])) == $last_modified_time || isset($_SERVER['HTTP_IF_NONE_MATCH']) && @trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) { header("HTTP/1.1 304 Not Modified"); exit; } else { header("Content-Type: {$contentType}"); header('Cache-Control: public, max-age=' . $cacheLife * 60); header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $cacheLife * 60) . ' GMT'); header_remove('Pragma'); } return file_get_contents($file); } elseif (method_exists($this->application->GetPlugin($plugin), 'HookJSON')) { $file = $this->application->GetPlugin($plugin)->HookJSON($filename); if ($file != null && $file != false) { header("Content-Type: {$contentType}"); header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); return $file; } } return false; }
public static function cache($contentType = 'text/plain') { header_remove('Expires'); header_remove('Pragma'); header('Cache-Control: private, max-age=31415926'); header('Content-Type: ' . $contentType); }
/** * indexAction * * @param string $url * * @return \Symfony\Component\HttpFoundation\Response */ public function indexAction($url) { // pass Dependency Injection Container Zend_Registry::set('dic', $this->container); $rootDir = $this->get('kernel')->getRootDir(); $bootstrap = $this->container->getParameter('zf1wrapper_bootstrap_path'); // capture content from legacy application ob_start(); include $rootDir . '/' . $bootstrap; $content = ob_get_clean(); // capture http response code (requires PHP >= 5.4.0) if (function_exists('http_response_code') && http_response_code() > 0) { $code = http_response_code(); } else { $code = 200; } // capture headers $headersSent = headers_list(); $headers = array(); array_walk($headersSent, function ($value, $key) use(&$headers) { $parts = explode(': ', $value); $headers[$parts[0]][] = $parts[1]; }); header_remove(); return new Response($content, $code, $headers); }
/** * Logs PHP errors properly * * @access public * @param string $title Error title * @param string $message Short descriptive message * @param string $details Advanced technical details * @param bool $critical Stop script here * @return void */ public function logError($title, $message, $details, $critical = false) { // Save log (error or critical error) $this->_saveLog($title, $message, $details, $critical ? 3 : 2); // Stop script if critical if ($critical) { // Remove any previous header header_remove(); // Create header header('HTTP/1.0 500 Internal Server Error'); // In development mode show errors on browser if ($this->_mode == 'development') { print "<!doctype html><html><head>"; print "<style>body{font-family:Arial;}</style>"; print "</head><body>"; // Show the error in a nice box print "<div style='text-align: center;'>"; print "<h1 style='color: #ff4800;'>" . $title . "</h1>"; print "<p>" . $message . '</p><hr>'; print "<p>" . $details . '</p>'; print "</div>"; // Close BODY and HTML tags print "</body></html>"; } else { // If template defined and found, show if (ERROR_TEMPLATE && @file_exists(ERROR_TEMPLATE)) { include_once ERROR_TEMPLATE; } } // Be done with it die; } }
/** * Removes previously set headers. */ public static function clear() { if (headers_sent() && !error_get_last()) { foreach ((array) headers_list() as $header) { header_remove($header); } } }
/** * setup test */ public function setUp($action, $context) { // remove all headers $headers = headers_list(); foreach ($headers as $h) { header_remove($h); } }
/** * Destroy session * @return TRUE * @param $id string **/ function destroy($id) { Cache::instance()->clear($id . '.@'); setcookie(session_name(), '', strtotime('-1 year')); unset($_COOKIE[session_name()]); header_remove('Set-Cookie'); return TRUE; }
public function removeHeaders() { if ($this->headersToRemove) { foreach ($this->headersToRemove as $removeThisHeader) { header_remove($removeThisHeader); } } }
protected function send_header() { if (IS_DEBUG) { header_remove(); } Core::close_buffers(false); HttpIO::set_cache_header(86400); }
/** * Destroy session * @return TRUE * @param $id string **/ function destroy($id) { $this->erase(array('session_id=?', $id)); setcookie(session_name(), '', strtotime('-1 year')); unset($_COOKIE[session_name()]); header_remove('Set-Cookie'); return TRUE; }
/** * Serve file using X-Sendfile header, this needs special server module * or configuration. Please make sure that all headers are already sent * and the all access control checks passed. * * @param string $filepath * @return bool success */ function xsendfile($filepath) { global $CFG; if (empty($CFG->xsendfile)) { return false; } if (!file_exists($filepath)) { return false; } if (headers_sent()) { return false; } $filepath = realpath($filepath); $aliased = false; if (!empty($CFG->xsendfilealiases) and is_array($CFG->xsendfilealiases)) { foreach ($CFG->xsendfilealiases as $alias=>$dir) { $dir = realpath($dir); if ($dir === false) { continue; } if (substr($dir, -1) !== DIRECTORY_SEPARATOR) { // add trailing dir separator $dir .= DIRECTORY_SEPARATOR; } if (strpos($filepath, $dir) === 0) { $filepath = $alias.substr($filepath, strlen($dir)); $aliased = true; break; } } } // Remove Etag because is is not strictly defined for byteserving, // is it tag of this range or whole file? if (!empty($_SERVER['HTTP_RANGE'])) { header_remove('Etag'); } if ($CFG->xsendfile === 'X-LIGHTTPD-send-file') { // http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file says 1.4 it does not support byteserving header('Accept-Ranges: none'); } else if ($CFG->xsendfile === 'X-Accel-Redirect') { // http://wiki.nginx.org/XSendfile // Nginx requires paths relative to aliases, you need to specify them in config.php if (!$aliased) { return false; } } header("$CFG->xsendfile: $filepath"); return true; }
static function action($argv = null, $cache = null, $controllers = "", $views = "") { if (!$argv) { $argv = self::argv(); } if (is_string($argv)) { $argv = explode('/', $argv); } if ($controllers) { self::$controllers = $controllers; } if ($views) { self::$views = $views; } if ($cache) { self::$cache = $cache; } $gzip = strpos(@$_SERVER['HTTP_ACCEPT_ENCODING'], "gzip") !== false && extension_loaded('zlib') ? ".gz" : ""; $cachename = self::$cache && @$_SERVER['REQUEST_METHOD'] == "GET" ? "output" . str_replace("/", "-", self::path_info()) . ".html{$gzip}" : false; if ($cachename) { if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) { if (self::$cache->ready($cachename, strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']))) { if (function_exists("header_remove")) { header_remove(); } header('HTTP/1.0 304 Not Modified'); exit; } } header("Last-Modified: " . date("r")); header("Vary: Accept-Encoding"); if (self::$cache->ready($cachename)) { if ($gzip) { ini_set('zlib.output_compression', 'Off'); header('Content-Encoding: gzip'); } self::$cache->dump($cachename); exit; } } $method = strtolower($_SERVER['REQUEST_METHOD']); if (($classname = ucfirst($argv[1])) && is_file(self::$controllers . "{$classname}.php") && (include_once self::$controllers . "{$classname}.php") && class_exists($classname, false) && ($instance = new $classname($argv)) && (method_exists($instance, $action = $method . ucfirst($argv[2])) || method_exists($instance, $action = $argv[2]) || count($argv) > 3 && method_exists($instance, $method . ucfirst($argv[3])) && (list($action, $argv[3]) = array($method . ucfirst($argv[3]), $argv[2])) || count($argv) > 3 && method_exists($instance, $argv[3]) && (list($action, $argv[3]) = array($argv[3], $argv[2])) || count($argv) >= 3 && method_exists($instance, $method . 'Single') && !array_splice($argv, 2, 0, $action = $method . 'Single') || count($argv) >= 3 && method_exists($instance, 'single') && !array_splice($argv, 2, 0, $action = 'single') || method_exists($instance, "__call"))) { if ($cachename) { ob_start(); } try { call_user_func_array(array($instance, $action), array_slice($argv, 3)); } catch (Exception $e) { header('HTTP/1.1 500 Server Error'); trigger_error(htmlspecialchars($e), E_USER_ERROR); } if ($cachename) { self::$cache->put($cachename, $gzip ? gzencode(ob_get_contents()) : ob_get_contents()); } exit; } }
protected function rendering() { header_remove(); header("Cache-Control: no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); header("Location: {$this->uri->toUri()}", true, 301); exit; }
public function removeCookie() { if (!$this->_allow_cooki) { $na = session_name(); if (!headers_sent()) { @header_remove('set-cookie'); } } }
/** * @runInSeparateProcess */ public function testSendsRedirectLocationHeader() { if (!function_exists('xdebug_get_headers')) { $this->markTestSkipped('Requires ext/xdebug to be installed.'); } $this->redirector->redirect('http://www.example.com'); $this->assertContains('Location: http://www.example.com/', xdebug_get_headers()); header_remove(); }
public function handle($http_data) { /* * Unset global aur.inc.php Pragma header. We want to allow * caching of data in proxies, but require validation of data * (if-none-match) if possible. */ header_remove('Pragma'); /* * Overwrite cache-control header set in aur.inc.php to allow * caching, but require validation. */ header('Cache-Control: public, must-revalidate, max-age=0'); header('Content-Type: application/json, charset=utf-8'); if (isset($http_data['v'])) { $this->version = intval($http_data['v']); } if ($this->version < 1 || $this->version > 4) { return $this->json_error('Invalid version specified.'); } if (!isset($http_data['type']) || !isset($http_data['arg'])) { return $this->json_error('No request type/data specified.'); } if (!in_array($http_data['type'], self::$exposed_methods)) { return $this->json_error('Incorrect request type specified.'); } if (isset($http_data['search_by']) && !in_array($http_data['search_by'], self::$exposed_fields)) { return $this->json_error('Incorrect search_by field specified.'); } $this->dbh = DB::connect(); $type = str_replace('-', '_', $http_data['type']); $json = call_user_func(array(&$this, $type), $http_data); $etag = md5($json); header("Etag: \"{$etag}\""); /* * Make sure to strip a few things off the * if-none-match header. Stripping whitespace may not * be required, but removing the quote on the incoming * header is required to make the equality test. */ $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? trim($_SERVER['HTTP_IF_NONE_MATCH'], "\t\n\r\" ") : false; if ($if_none_match && $if_none_match == $etag) { header('HTTP/1.1 304 Not Modified'); return; } if (isset($http_data['callback'])) { $callback = $http_data['callback']; if (!preg_match('/^[a-zA-Z0-9().]{1,128}$/D', $callback)) { return $this->json_error('Invalid callback name.'); } header('content-type: text/javascript'); return '/**/' . $callback . '(' . $json . ')'; } else { header('content-type: application/json'); return $json; } }
/** * @param Body $body */ public static function sendRawBodyResponse(Body $body) { if (headers_sent() === false) { header_remove(); $message = sprintf("HTTP/1.0 %d %s", $body->getStatusCode(), $body->getReasonPhrase()); header($message, true, $body->getStatusCode()); } $body->sendData(); flush(); }
public function Traffic() { $content = $this->loadFromDisk() ?? $this->getFromAPI('http://api.sr.se/api/v2/traffic/messages?format=json&pagination=false&sort=createddate&indent=true'); header('Content-Type: application/json'); header('Cache-Control: public, max-age=' . self::$cache_life * 60 . ',must-revalidate'); header('Expires: ' . gmdate('D, d M Y H:i:s', time() + self::$cache_life * 60) . ' GMT'); header('Last-modified: ' . gmdate('D, d M Y H:i:s', $_SERVER['REQUEST_TIME']) . ' GMT'); header_remove('Pragma'); return $content; }
/** * @runInSeparateProcess */ public function testHeaderIsSent() { if (!function_exists('xdebug_get_headers')) { $this->markTestSkipped('Requires ext/xdebug to be installed.'); } $header = new CsrfToken(array('token' => 'foo')); $header->send(); $this->assertContains('X-CSRFToken: foo', xdebug_get_headers()); header_remove(); }