function returnJson($returnArray, $success = true, $statusCode = 200) { $app = \Slim\Slim::getInstance(); $app->response()->status($statusCode); $callback = empty($returnArray['callback']) ? null : $returnArray['callback']; if ($callback) { unset($returnArray['callback']); echo $callback . '(' . json_encode($returnArray) . ');'; exit; } else { if (!$success) { $app->log->debug(print_r(headers_list(), true)); $app->status($statusCode); $app->response()->header('Content-Type', 'application/json'); $app->response->write(json_encode($returnArray)); header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']); header('Access-Control-Allow-Headers: X-Requested-With'); header('Access-Control-Allow-Credentials: true'); header('Access-Control-Allow-Methods: GET, POST, OPTIONS'); $app->stop(); } else { $app->response()->header('Content-Type', 'application/json'); $app->response->write(json_encode($returnArray)); } } }
/** * Set registration cookie * * @access public * @return void */ function set_cookie() { global $debug; global $mycookie_name, $mycookie_expiry; global $loggedin, $admin; if (!headers_sent()) { ob_start(); setcookie($mycookie_name . '[id]', $_POST['id'], time() + $mycookie_expiry); // '/', '.localhost', 0, 0) setcookie($mycookie_name . '[name]', $_POST['forename'], time() + $mycookie_expiry); // '/', '.localhost', 0, 0) setcookie($mycookie_name . '[admin]', $_POST['admin'], time() + $mycookie_expiry); // '/', '.localhost', 0, 0) ob_end_flush(); $loggedin = TRUE; if ($_POST['admin'] == '1') { $admin = TRUE; } else { $admin = FALSE; } } else { if ($debug) { var_dump(headers_list()); exit('header already sent!!'); } } }
/** * 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); }
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; }; }
/** * Handler that compresses data with gzip if allowed by the Accept header. * Unlike ob_gzhandler, it works for HEAD requests too. */ function wfGzipHandler($s) { if (!function_exists('gzencode') || headers_sent()) { return $s; } $ext = wfRequestExtension(); if ($ext == '.gz' || $ext == '.tgz') { // Don't do gzip compression if the URL path ends in .gz or .tgz // This confuses Safari and triggers a download of the page, // even though it's pretty clearly labeled as viewable HTML. // Bad Safari! Bad! return $s; } if (wfClientAcceptsGzip()) { header('Content-Encoding: gzip'); $s = gzencode($s, 6); } // Set vary header if it hasn't been set already $headers = headers_list(); $foundVary = false; foreach ($headers as $header) { if (substr($header, 0, 5) == 'Vary:') { $foundVary = true; break; } } if (!$foundVary) { header('Vary: Accept-Encoding'); global $wgUseXVO; if ($wgUseXVO) { header('X-Vary-Options: Accept-Encoding;list-contains=gzip'); } } return $s; }
/** * response/output event filter * Appends tokens to POST forms if user is logged in. * * @param string $templateResult ByRef */ public static function output($templateResult) { if (!self::shouldProtectUser()) { eZDebugSetting::writeDebug('ezformtoken', 'Output not protected (not logged in user)', __METHOD__); return $templateResult; } // We only rewrite pages served with an html/xhtml content type $sentHeaders = headers_list(); foreach ($sentHeaders as $header) { // Search for a content-type header that is NOT HTML // Note the Content-Type header will not be included in // headers_list() unless it has been explicitly set from PHP. if (stripos($header, 'Content-Type:') === 0 && strpos($header, 'text/html') === false && strpos($header, 'application/xhtml+xml') === false) { eZDebugSetting::writeDebug('ezformtoken', 'Output not protected (Content-Type is not html/xhtml)', __METHOD__); return $templateResult; } } $token = self::getToken(); $field = self::FORM_FIELD; $replaceKey = self::REPLACE_KEY; eZDebugSetting::writeDebug('ezformtoken', 'Output protected (all forms will be modified)', __METHOD__); // If document has head tag, insert in a html5 valid and semi standard way if (strpos($templateResult, '<head>') !== false) { $templateResult = str_replace('<head>', "<head>\n<meta name=\"csrf-param\" content=\"{$field}\" />\n" . "\n<meta name=\"csrf-token\" id=\"{$field}_js\" title=\"{$token}\" content=\"{$token}\" />\n", $templateResult); } else { $templateResult = preg_replace('/(<body[^>]*>)/i', '\\1' . "\n<span style='display:none;' id=\"{$field}_js\" title=\"{$token}\"></span>\n", $templateResult); } $templateResult = preg_replace('/(<form\\W[^>]*\\bmethod=(\'|"|)POST(\'|"|)\\b[^>]*>)/i', '\\1' . "\n<input type=\"hidden\" name=\"{$field}\" value=\"{$token}\" />\n", $templateResult); return str_replace($replaceKey, $token, $templateResult); }
/** * Convert records to javascript console commands and send it to the browser. * This method is automatically called on PHP shutdown if output is HTML or Javascript. */ public static function send() { $htmlTags = true; // Check content type foreach (headers_list() as $header) { if (stripos($header, 'content-type:') === 0) { // This handler only works with HTML and javascript outputs // text/javascript is obsolete in favour of application/javascript, but still used if (stripos($header, 'application/javascript') !== false || stripos($header, 'text/javascript') !== false) { $htmlTags = false; } elseif (stripos($header, 'text/html') === false) { return; } break; } } if (count(self::$records)) { if ($htmlTags) { echo '<script>', self::generateScript(), '</script>'; } else { echo self::generateScript(); } self::reset(); } }
/** * @return void */ public function output() { if ($this->isOutput()) { return; } // It not application/{type} header. To output bar information. $isApplication = (function () { $list = headers_list(); foreach ($list as $value) { list($name, $value) = explode(':', $value); if (strtolower($name) == 'content-type' && false !== strpos(trim($value), 'application')) { return true; } } return false; })(); if (!headers_sent() && 'cli' !== PHP_SAPI && !$isApplication) { $this->outputEmpty(); } if (!$isApplication) { $render = $this->getJavascriptRenderer(); echo $this->wrapOutput($render); } $this->output = true; }
/** * Instantiate Whoops with the correct handlers. */ public function __construct() { require 'YiiWhoopsRunner.php'; $this->whoops = new YiiWhoopsRunner(); if (Yii::app()->request->isAjaxRequest) { $this->whoops->pushHandler(new JsonResponseHandler()); } else { $contentType = ''; foreach (headers_list() as $header) { list($key, $value) = explode(':', $header); $value = ltrim($value, ' '); if (strtolower($key) === 'content-type') { // Split encoding if exists $contentType = explode(";", strtolower($value)); $contentType = current($contentType); break; } } if ($contentType && strpos($contentType, 'json')) { $this->whoops->pushHandler(new JsonResponseHandler()); } else { $page_handler = new PrettyPageHandler(); if ($this->pageTitle) { $page_handler->setPageTitle($this->pageTitle); } $reordered_tables = array('Request information' => static::createRequestTable(), "GET Data" => $_GET, "POST Data" => $_POST, "Files" => $_FILES, "Cookies" => $_COOKIE, "Session" => isset($_SESSION) ? $_SESSION : array(), "Environment Variables" => $_ENV, "Server/Request Data" => $_SERVER); foreach ($reordered_tables as $label => $data) { $page_handler->addDataTable($label, $data); } $this->whoops->pushHandler($page_handler); } } }
/** * Handler that compresses data with gzip if allowed by the Accept header. * Unlike ob_gzhandler, it works for HEAD requests too. */ function wfGzipHandler($s) { if (!function_exists('gzencode') || headers_sent()) { return $s; } $ext = wfRequestExtension(); if ($ext == '.gz' || $ext == '.tgz') { // Don't do gzip compression if the URL path ends in .gz or .tgz // This confuses Safari and triggers a download of the page, // even though it's pretty clearly labeled as viewable HTML. // Bad Safari! Bad! return $s; } if (isset($_SERVER['HTTP_ACCEPT_ENCODING'])) { $tokens = preg_split('/[,; ]/', $_SERVER['HTTP_ACCEPT_ENCODING']); if (in_array('gzip', $tokens)) { header('Content-Encoding: gzip'); $s = gzencode($s, 3); } } // Set vary header if it hasn't been set already $headers = headers_list(); $foundVary = false; foreach ($headers as $header) { if (substr($header, 0, 5) == 'Vary:') { $foundVary = true; break; } } if (!$foundVary) { header('Vary: Accept-Encoding'); header('X-Vary-Options: Accept-Encoding;list-contains=gzip'); } return $s; }
public function run(&$content) { if (C('TMPL_STRIP_SPACE')) { preg_match_all("/<script[\\s\\S]*?>([\\s\\S]*?)<\\/script>/i", $content, $scripta); preg_match_all("/<style[\\s\\S]*?>([\\s\\S]*?)<\\/style>/i", $content, $stylea); $comhtml = $this->delHtml($content); preg_match_all("/<script[\\s\\S]*?>([\\s\\S]*?)<\\/script>/i", $comhtml, $scriptb); preg_match_all("/<style[\\s\\S]*?>([\\s\\S]*?)<\\/style>/i", $comhtml, $styleb); foreach ($stylea[0] as $k => $v) { $cssmin[$k] = Cssmin::minify($v); } foreach ($scripta[0] as $key => $value) { if (empty(Jsmin::minify($scripta[1][$key]))) { $jsmin[$key] = $scriptb[0][$key]; } else { $jsmin[$key] = Jsmin::minify($value); } } $content = str_replace($scriptb[0], $jsmin, $comhtml); $content = str_replace($styleb[0], $cssmin, $content); if (C('HTML_CACHE_ON') && defined('HTML_FILE_NAME') && !preg_match('/Status.*[345]{1}\\d{2}/i', implode(' ', headers_list())) && !preg_match('/(-[a-z0-9]{2}){3,}/i', HTML_FILE_NAME)) { //静态文件写入 Storage::put(HTML_FILE_NAME, $content, 'html'); } } }
/** * Renders debug bar. * @return void */ public function render() { $obLevel = ob_get_level(); $panels = array(); foreach ($this->panels as $id => $panel) { try { $panels[] = array('id' => preg_replace('#[^a-z0-9]+#i', '-', $id), 'tab' => $tab = (string) $panel->getTab(), 'panel' => $tab ? (string) $panel->getPanel() : NULL); } catch (\Exception $e) { $panels[] = array('id' => "error-" . preg_replace('#[^a-z0-9]+#i', '-', $id), 'tab' => "Error in {$id}", 'panel' => '<h1>Error: ' . $id . '</h1><div class="nette-inner">' . nl2br(htmlSpecialChars($e, ENT_IGNORE)) . '</div>'); while (ob_get_level() > $obLevel) { // restore ob-level if broken ob_end_clean(); } } } @session_start(); $session =& $_SESSION['__NF']['debuggerbar']; if (preg_match('#^Location:#im', implode("\n", headers_list()))) { $session[] = $panels; return; } foreach (array_reverse((array) $session) as $reqId => $oldpanels) { $panels[] = array('tab' => '<span title="Previous request before redirect">previous</span>', 'panel' => NULL, 'previous' => TRUE); foreach ($oldpanels as $panel) { $panel['id'] .= '-' . $reqId; $panels[] = $panel; } } $session = NULL; require __DIR__ . '/templates/bar.phtml'; }
/** * 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 static function log_runtime($req) { $end_time = microtime(true); $framework_time = (double) ($req->start_times["request"] - $req->start_times["init"]); if (isset($req->start_times["app"])) { $app_time = (double) ($end_time - $req->start_times["app"]); } $total_time = (double) ($end_time - $req->start_times["init"]); if (class_exists('\\ActiveRecord\\ConnectionManager') && \ActiveRecord\ConnectionManager::connection_count()) { $db_time = (double) \ActiveRecord\ConnectionManager::get_connection()->reset_database_time(); if (isset($app_time)) { $app_time -= $db_time; } } $status = "200"; foreach (headers_list() as $header) { if (preg_match("/^Status: (\\d+)/", $header, $m)) { $status = $m[1]; } } $log = "Completed in " . sprintf("%0.5f", $total_time); if (isset($db_time)) { $log .= " | DB: " . sprintf("%0.5f", $db_time) . " (" . intval($db_time / $total_time * 100) . "%)"; } if (isset($app_time)) { $log .= " | App: " . sprintf("%0.5f", $app_time) . " (" . intval($app_time / $total_time * 100) . "%)"; } $log .= " | Framework: " . sprintf("%0.5f", $framework_time) . " (" . intval($framework_time / $total_time * 100) . "%)"; $log .= " | " . $status . " [" . $req->url . "]"; if (isset($req->redirected_to)) { $log .= " -> [" . $req->redirected_to . "]"; } Log::info($log); }
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; }
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; }
public function run($request, $verb = 'GET') { if (!in_array($verb, $this->cachedVerbs)) { return parent::run($request, $verb); } $key = call_user_func($this->keyGenerator, $request, $verb); try { $cached = $this->cache->get($key, $this->cacheNamespace); http_response_code($cached['code']); foreach ($cached['head'] as $head) { header($head); } echo $cached['body']; return $cached['rtrn']; } catch (\Exception $e) { ob_start(); $rtrn = parent::run($request, $verb); $body = ob_get_contents(); $head = headers_list(); $code = http_response_code(); ob_end_clean(); if (!$code || $code === 200) { $this->cache->set($key, ['rtrn' => $rtrn, 'head' => $head, 'body' => $body, 'code' => $code], $this->cacheNamespace, $this->cacheTimeout); } echo $body; return $rtrn; } }
/** * @return string */ public function testHeaderSentCookies() { $_COOKIE['test0'] = 'test0'; // Create cookies : setcookie('test1', 'test1'); setcookie('test2', 'test2'); setrawcookie('test3', 'test3'); setrawcookie('test4', 'test4'); // Delete, created cookies (with false) : setcookie('test1', false); setrawcookie('test2', false); // Delete, created cookies (with null) : setcookie('test3', null); setrawcookie('test4', null); // Delete others cookies : setcookie('testDeleteOther0', null); setrawcookie('testDeleteOther1', null); // Not send REQUEST_TIME + 0 : setrawcookie('testKeyNotSend', 'testValueNotSend', REQUEST_TIME + 0); $listOfHeaders = headers_list(); ob_start(); print_r($listOfHeaders); $result = ob_get_clean(); $lines = $this->outputTestLineLayout($this->highlightPhp("\$_COOKIE['test0'] = 'test0';\n\n// Create cookies :\nsetcookie('test1', 'test1');\nsetcookie('test2', 'test2');\nsetrawcookie('test3', 'test3');\nsetrawcookie('test4', 'test4');\n\n// Delete, created cookies (with false) :\nsetcookie('test1', false);\nsetrawcookie('test2', false);\n\n// Delete, created cookies (with null) :\nsetcookie('test3', null);\nsetrawcookie('test4', null);\n\n// Delete others cookies :\nsetcookie('testDeleteOther0', null);\nsetrawcookie('testDeleteOther1', null);\n\n// Not send REQUEST_TIME + 0 :\nsetrawcookie('testKeyNotSend', 'testValueNotSend', REQUEST_TIME + 0);"), $this->getDefaultTestLineTitle()); $lines .= $this->outputTestLineLayout($this->highlightPhp($result, false), self::getDefaultTestResultTitle()); return $this->outputTestLayout($lines, 'Headers - Create cookies, sent cookies and print headers sent'); }
function pa_end_of_page_ob_filter($html) { // if headers not sent yet, and we don't have a content type specified, send text/html; charset=UTF-8 if (!headers_sent()) { $ct_sent = FALSE; foreach (headers_list() as $hdr) { if (preg_match("/^Content-Type:/", $hdr)) { $ct_sent = TRUE; } } if (!$ct_sent) { header("Content-Type: text/html; charset=UTF-8"); } } // work out timing global $pa_page_render_start; $duration = microtime(TRUE) - $pa_page_render_start; $eop_text = sprintf("[%.2f s]", $duration); global $debug_show_svn_version; if ($debug_show_svn_version) { $svn_text = get_svn_version(); $eop_text .= " [{$svn_text}]"; } $eop_text .= " " . PA::$remote_ip; // now drop timing and anything else we want to show at the bottom of the page return str_replace("<!--**timing**-->", $eop_text, $html); }
public function display() { $value = $this->getValue(); if (!empty($value)) { //Generate an unike ID for the resource: $resource_hash = $this->getFileMD5(); //Now will check if the browser sent an ID for requested resource. //If he sent it, will check if they match with current resource: $headers = headers_list(); if (key_exists('If-None-Match', $headers) && ereg($resource_hash, $headers['If-None-Match'])) { header('HTTP/1.1 304 Not Modified'); } else { header("ETag: \"{$resource_hash}\""); header("Cache-Control: max-age=3600, must-revalidate"); header("Pragma: Public"); header("Accept-Ranges: bytes"); header("Content-Length: " . strlen($value)); if ($this->getMimeType() != null) { header("Content-Type: {$this->getMimeType()}"); } if ($this->getFileName() != null) { header("Content-Disposition: inline; filename=\"{$this->getFileName()}\";"); } echo $value; } } else { /** * @todo Add a default image resource for non found resources! */ } }
function CharsetMeta() { $content = ''; $charset = ''; foreach (headers_list() as $hdr) { if (strtolower(substr($hdr, 0, 13)) == 'content-type:') { $hdr = trim(substr($hdr, 13)); if (($p = strpos($hdr, ';')) === null) { $content = $hdr; } else { $content = trim(substr($hdr, 0, $p)); $s = trim(substr($hdr, $p + 1)); $charset = trim(substr($s, 8)); } break; } } if ($content != '' && $charset != '') { return "<meta http-equiv=\"Content-Type\" content=\"{$content}; charset={$charset}\">"; } else { if ($content != '') { return "<meta http-equiv=\"Content-Type\" content=\"{$content}\">"; } else { return null; } } }
public function dispatchLoopShutdown() { $headers = headers_list(); $hasContentType = false; foreach ($headers as $head) { if (false !== strpos($head, 'Content-Type')) { $hasContentType = true; break; } } //if we are using Response Headers, they will still not be set if ($hasContentType === false) { $headers = $this->getResponse()->getHeaders(); foreach ($headers as $header) { if (isset($header['name']) && $header['name'] == 'Content-Type') { $hasContentType = true; break; } } } if ($hasContentType === false) { $response = $this->getResponse(); $response->setHeader('Content-Type', 'text/html; charset=utf-8'); } }
public static final function hasHeader($a_name) { foreach (headers_list() as $header) { if (stripos((string) $a_name . ':', $header) !== false) { return $header; } } }
public function getHeaders() { $headers = headers_list(); if ($this->response_code) { array_unshift($headers, 'HTTP/1.0 ' . $this->response_code); } return $headers; }
public static function getScriptResponse($checkIfSent = false) { if (!is_bool($checkIfSent)) { throw new \Exception('CheckIfSent parameter must be an boolean'); } $response = $checkIfSent ? headers_sent() ? headers_list() : null : headers_list(); return $response; }
public static function headers_list() { if (defined('UNIT_TESTING')) { return self::$headers; } else { return headers_list(); } }
/** * setup test */ public function setUp($action, $context) { // remove all headers $headers = headers_list(); foreach ($headers as $h) { header_remove($h); } }
public function send() { $list = $this->getList(); foreach ($list as $item) { header($item, true); } return headers_list(); }
/** * Removes previously set headers. */ public static function clear() { if (headers_sent() && !error_get_last()) { foreach ((array) headers_list() as $header) { header_remove($header); } } }
/** * Check headers already created to not step on download or Img_lib's feet * * @return boolean */ public static function check_headers() { foreach (headers_list() as $header) { if (stripos($header, 'Last-Modified:') === 0 or stripos($header, 'Expires:') === 0) { return FALSE; } } return TRUE; }