/** * Start a big file download on Laravel Framework 4.0 / 4.1 * Source (originally for Laravel 3.*) : http://stackoverflow.com/questions/15942497/why-dont-large-files-download-easily-in-laravel * @param string $path Path to the big file * @param string $name Name of the file (used in Content-disposition header) * @param array $headers Some extra headers */ public function sendFile($path, $name = null, array $headers = array()) { if (is_null($name)) { $name = basename($path); } $file = new \Symfony\Component\HttpFoundation\File\File($path); $mime = $file->getMimeType(); // Prepare the headers $headers = array_merge(array('Content-Description' => 'File Transfer', 'Content-Type' => $mime, 'Content-Transfer-Encoding' => 'binary', 'Expires' => 0, 'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0', 'Pragma' => 'public', 'Content-Length' => \File::size($path), 'Content-Disposition' => 'attachment; filename=' . $name), $headers); $response = new \Symfony\Component\HttpFoundation\Response('', 200, $headers); // If there's a session we should save it now if (\Config::get('session.driver') !== '') { \Session::save(); } session_write_close(); if (ob_get_length()) { ob_end_clean(); } $response->sendHeaders(); // Read the file if ($file = fopen($path, 'rb')) { while (!feof($file) and connection_status() == 0) { print fread($file, 1024 * 8); flush(); } fclose($file); } // Finish off, like Laravel would \Event::fire('laravel.done', array($response)); $response->send(); }
function handle_exception($e) { $template = App\Config::get('debug') ? 'debug' : '5xx'; $view = new App\Template($template, compact('e')); $response = new Symfony\Component\HttpFoundation\Response($view->fetch(), Symfony\Component\HttpFoundation\Response::HTTP_INTERNAL_SERVER_ERROR); $response->send(); }
private function downloadResponse($service) { $result = $service->execute(); $csvFile = $result['file']; $filename = $result['filename']; $response = new \Symfony\Component\HttpFoundation\Response(); $response->setStatusCode(200); $response->setContent(file_get_contents($csvFile)); $response->headers->set('Content-Type', 'application/stream'); $response->headers->set('Content-length', filesize($csvFile)); $response->headers->set('Content-Disposition', sprintf('attachment;filename="%s"', $filename)); $response->send(); return $response; }
/** * Intercepts, logs, and displays uncaught exceptions. * * To use a viewtype other than failsafe, create the views: * <viewtype>/messages/exceptions/admin_exception * <viewtype>/messages/exceptions/exception * See the json viewtype for an example. * * @warning This function should never be called directly. * * @see http://www.php.net/set-exception-handler * * @param Exception $exception The exception being handled * * @return void * @access private */ function _elgg_php_exception_handler($exception) { $timestamp = time(); error_log("Exception #{$timestamp}: {$exception}"); // Wipe any existing output buffer ob_end_clean(); // make sure the error isn't cached header("Cache-Control: no-cache, must-revalidate", true); header('Expires: Fri, 05 Feb 1982 00:00:00 -0500', true); // we don't want the 'pagesetup', 'system' event to fire global $CONFIG; $CONFIG->pagesetupdone = true; try { // allow custom scripts to trigger on exception // $CONFIG->exception_include can be set locally in settings.php // value should be a system path to a file to include if (!empty($CONFIG->exception_include) && is_file($CONFIG->exception_include)) { ob_start(); include $CONFIG->exception_include; $exception_output = ob_get_clean(); // if content is returned from the custom handler we will output // that instead of our default failsafe view if (!empty($exception_output)) { echo $exception_output; exit; } } if (elgg_is_xhr()) { elgg_set_viewtype('json'); $response = new \Symfony\Component\HttpFoundation\JsonResponse(null, 500); } else { elgg_set_viewtype('failsafe'); $response = new \Symfony\Component\HttpFoundation\Response('', 500); } if (elgg_is_admin_logged_in()) { $body = elgg_view("messages/exceptions/admin_exception", array('object' => $exception, 'ts' => $timestamp)); } else { $body = elgg_view("messages/exceptions/exception", array('object' => $exception, 'ts' => $timestamp)); } $response->setContent(elgg_view_page(elgg_echo('exception:title'), $body)); $response->send(); } catch (Exception $e) { $timestamp = time(); $message = $e->getMessage(); echo "Fatal error in exception handler. Check log for Exception #{$timestamp}"; error_log("Exception #{$timestamp} : fatal error in exception handler : {$message}"); } }
<?php require_once 'bootstrap.php'; $Request = \Symfony\Component\HttpFoundation\Request::createFromGlobals(); $App->setRequest($Request); $routes = (require_once DIR_PROJECT . '/config/route.php'); $Router = new TelegramBot\Utils\Router($routes, $App); $Response = new \Symfony\Component\HttpFoundation\Response(); try { $Route = $Router->findAction($Request); $Response->setContent($Router->resolve()); } catch (\TelegramBot\Exception\ExceptionNotFound $e) { $Response->setStatusCode(404); } catch (\Exception $e) { $Response->setStatusCode(500); } $Response->send();
function main() { $request = Request::createFromGlobals(); Http::Init(); //Get routes and match with incomming url $context = new Routing\RequestContext(); $context->fromRequest($request); $routes = Edu8\Route::getRoutes(__DIR__ . '/../routes/'); $matcher = new Routing\Matcher\UrlMatcher($routes, $context); try { $request->attributes->add($matcher->match($request->getPathInfo())); $file_root = $request->attributes->get('file_root'); $slug = $request->attributes->get('slug'); } catch (\Exception $e) { $file_root = rtrim($request->getPathInfo(), '/'); $slug = ''; //$request->attributes->get('slug'); } $twig_vars = Http::GetSession(); if (empty($twig_vars['request'])) { $twig_vars['request'] = $request->request->all(); } else { $twig_vars['request'] = array_merge($twig_vars['request'], $request->request->all()); } $twig_vars['request']['pathname'] = $request->getPathInfo(); if ($request->files->has('file')) { $twig_vars['request']['file'] = $request->files->get('file')->getPathname(); } Http::SetSession($twig_vars); if (isset($twig_vars['auth']) && $file_root === '/login') { Http::Redirect('/'); } if (!isset($twig_vars['auth']) && $file_root !== '/login') { Http::Redirect('/login'); } //Merge session and post variables try { if (isset($_SERVER['HTTP_REFERER'])) { //Get routes and match with refer url $routes2 = Edu8\Route::getRoutes(__DIR__ . '/../callbacks/'); $matcher2 = new Routing\Matcher\UrlMatcher($routes2, $context); $try = parse_url($_SERVER['HTTP_REFERER'], PHP_URL_PATH); $attribs = $matcher2->match($try); //Dispatch post() from appropriate file if (is_file($attribs['php_file'])) { include $attribs['php_file']; post($twig_vars); } } } catch (Routing\Exception\ResourceNotFoundException $e) { } //Dispatch build() from appropriate file if (is_file($request->attributes->get('php_file'))) { include $request->attributes->get('php_file'); build($twig_vars); } Http::SetSession($twig_vars); if (strpos($twig_vars['request']['pathname'], 'admin') && $twig_vars['student']['is_professor'] != 1) { Http::Redirect('/'); } //Render twig with varables assembled in build() $loader = new Twig_Loader_Filesystem(__DIR__ . '/../templates'); $twig = new Twig_Environment($loader); $response = new Symfony\Component\HttpFoundation\Response($twig->render($file_root . $slug . '.html.twig', $twig_vars)); $response->send(); unset($twig_vars['message_dlg']); }
private function sendResponse(Response $response) { $sendable_response = new \Symfony\Component\HttpFoundation\Response($this->serializer->serialize($response->getData()), $response->getStatusCode(), $response->getHeaders()); $sendable_response->send(); }
<?php require 'vendor/autoload.php'; $response = new \Symfony\Component\HttpFoundation\Response('Oops', 400); $response->send();
/** * setup i18n URI and detect the language in URI. */ public function i18nUri() { if ($this->Profiler != null) { $this->Profiler->Console->timeload('Initialize the language locale uri.', __FILE__, __LINE__); $this->Profiler->Console->memoryUsage('Initialize the language locale uri.', __FILE__, __LINE__ - 1); } $configdb = new \System\Core\Models\ConfigDb($this->Silexapp['Db']); if ($configdb->getConfigValue('site_lang_method', 'uri') == 'cookie') { // if detect language method is using cookie. $language_cookie_name = $_SERVER['HTTP_HOST'] . '_CMS_LANGUAGE_LOCALE_URI'; $request = new \Symfony\Component\HttpFoundation\Request($_GET, $_POST, [], $_COOKIE); if ($request->cookies->has($language_cookie_name)) { $this->language_locale_uri = $request->cookies->get($language_cookie_name); } else { $LangDb = new \System\Core\Models\LanguagesDb($this->Silexapp['Db']); $this->language_locale_uri = $LangDb->getDefaultLanguageUri(); $cookie = new \Symfony\Component\HttpFoundation\Cookie($language_cookie_name, $LangDb->getDefaultLanguageUri(), time() + 60 * 60 * 24 * 30, '/', null, isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? true : false); $response = new \Symfony\Component\HttpFoundation\Response(); $response->headers->setCookie($cookie); $response->send(); } unset($configdb, $cookie, $LangDb, $language_cookie_name, $request, $response); } else { // if detect language method is using URI. $uri = new \System\Libraries\Uri(); $uris_arr = $uri->getUriSegments(true); // get language locale uri from REQUEST_URI. this does not check the exists language yet. if (isset($uris_arr[1])) { $language_locale_uri = $uris_arr[1]; } else { $language_locale_uri = $uris_arr[count($uris_arr) - 1]; } // check that language locale uri is in language list or not. non-match or empty language locale uri will be use default language locale uri. $LangDb = new \System\Core\Models\LanguagesDb($this->Silexapp['Db']); $this->language_locale_uri = $LangDb->getLanguageUri($language_locale_uri); // check and detect language redirect. if ($this->language_locale_uri != $language_locale_uri) { // if checked language locale URI is not match the detected one. example: th != page, en-US != fr-FR where page, or fr-FR is not exists in language db. // set language locale uri to global variable $_SERVER. $_SERVER['CMS_LANGUAGE_LOCALE_URI'] = $this->language_locale_uri; if ($configdb->getConfigValue('site_lang_uri_default_visible', '1') == '1') { // if settings was set to force show language URI, redirect to new url with language prefixed. $uris_arr[0] = $this->language_locale_uri; $new_uri = implode('/', $uris_arr); unset($configdb, $LangDb, $language_locale_uri, $uris_arr); // redirect from EX. http://domain.tld/myapp/index.php to http://domain.tld/myapp/index.php/th, http://domain.tld/myapp/index.php/page/subpage -> http://domain.tld/index.php/th/page/subpage header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0'); header('Cache-Control: post-check=0, pre-check=0', false); header('Pragma: no-cache'); header('HTTP/1.1 301 Moved Permanently'); header('Location: ' . $uri->createUrl($new_uri, 'auto', false)); exit; } } else { // if checked language locale URI is match detected one. // set language locale uri to global variable $_SERVER. $_SERVER['CMS_LANGUAGE_LOCALE_URI'] = $language_locale_uri; if ($configdb->getConfigValue('site_lang_uri_default_visible', '1') == '0') { // if default language is set to not visible, redirect to the URL where it has no language locale URI. $default_language_locale_uri = $LangDb->getDefaultLanguageUri(); if ($language_locale_uri == $default_language_locale_uri) { // if detected language locale uri is default. example: default is 'th'; url is http://domain.tld/myapp/index.php/th/page/subpage; this language locale uri is default language! unset($_SERVER['CMS_LANGUAGE_LOCALE_URI']); $uris_arr = $uri->getUriSegments(true); if (isset($uris_arr[1]) && $uris_arr[1] != null) { unset($uris_arr[1]); } $new_uri = implode('/', $uris_arr); unset($configdb, $LangDb, $language_locale_uri, $uris_arr); // redirect from IE. http://domain.tld/myapp/index.php/th to http://domain.tld/myapp/index.php where th is default language. header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0'); header('Cache-Control: post-check=0, pre-check=0', false); header('Pragma: no-cache'); header('HTTP/1.1 301 Moved Permanently'); header('Location: ' . $uri->createUrl($new_uri, 'auto', false)); exit; } } } // endif check and detect language redirect. // re-setting request uri key. -------------------------------------------------------------- // in case that the url contain language locale uri. for example: uri is http://domain.tld/myapp/index.php/th/page/subpage; the original REQUEST_URI will be /myapp/index.php/th/page/subpage // with this re-setting request uri key, the modified REQUEST_URI will be /myapp/index.php/page/subpage. so the routes can works properly. $index_file = $uri->getIndexFile(); $uris_arr = $uri->getUriSegments(true); if (isset($uris_arr[1]) && $uris_arr[1] == $this->language_locale_uri) { unset($uris_arr[1]); } $uri_string = implode('/', $uris_arr); $_SERVER['REQUEST_URI'] = $uri->getBaseUri() . ($index_file != null ? '/' . $index_file : '') . $uri_string; unset($configdb, $default_language_locale_uri, $index_file, $language_locale_uri, $uri, $uris_arr, $uri_string); } // endif; site_lang_method // set share variable via Silex\Application. $this->Silexapp['language_locale_uri'] = $this->language_locale_uri; $this->Silexapp->register(new \Silex\Provider\TranslationServiceProvider(), ['locale' => $LangDb->getLanguageData($this->language_locale_uri), 'locale_fallbacks' => [$LangDb->getLanguageData('')]]); putenv('LC_ALL=' . $this->language_locale_uri); setlocale(LC_ALL, explode(',', str_replace(', ', ',', $LangDb->getLanguageData($this->language_locale_uri)))); // start to working with php-gettext. $this->Silexapp['Language'] = $this->Silexapp->share(function () { return new \System\Libraries\Language($this->language_locale_uri); }); unset($LangDb); if ($this->Profiler != null) { $this->Profiler->Console->timeload('Finished the language locale uri.', __FILE__, __LINE__); $this->Profiler->Console->memoryUsage('Finished the language locale uri.', __FILE__, __LINE__ - 1); } }
/** * export all local author to csv * @param Request $request [] * @author Nash Lesigon <*****@*****.**> * @return Response */ public function exportToCsvAction(Request $request) { $exportToCsvService = $this->get("buggl_mail.export_local_author_to_csv"); $result = $exportToCsvService->execute(); $csvFile = $result['file']; $filename = $result['filename']; $response = new \Symfony\Component\HttpFoundation\Response(); $response->setStatusCode(200); $response->setContent(file_get_contents($csvFile)); $response->headers->set('Content-Type', 'application/stream'); $response->headers->set('Content-length', filesize($csvFile)); $response->headers->set('Content-Disposition', sprintf('attachment;filename="%s"', $filename)); $response->send(); return $response; }
function download_nuxeo_document() { $request = \Symfony\Component\HttpFoundation\Request::createFromGlobals(); $validation = \Symfony\Component\Validator\Validation::createValidator(); $nxsession = $this->getClient(); if ($request->query->has('nx_doc_id')) { $doc_id = $request->query->get('nx_doc_id'); $violations = $validation->validate($doc_id, array(new \Symfony\Component\Validator\Constraints\Uuid())); if (0 === count($violations)) { $doc = $nxsession->newRequest("Document.Fetch")->set('params', 'value', $doc_id)->setSchema($schema = 'dublincore,file')->sendRequest()->getDocument(0); try { $file_content = $nxsession->newRequest("Blob.Get")->set('input', 'doc:' . $doc_id)->sendRequest(); $file_info = new AttributesBag($doc->getProperty('file:content')); $response = new \Symfony\Component\HttpFoundation\Response($file_content); $response->setLastModified(new DateTime($doc->getProperty('dc:modified'))); $response->headers->add(array('Content-Disposition' => $response->headers->makeDisposition(\Symfony\Component\HttpFoundation\ResponseHeaderBag::DISPOSITION_ATTACHMENT, $doc->getProperty('file:filename')), 'Content-Length' => $file_info->offsetGet('length'), 'Content-Type' => $file_info->offsetGet('mime-type', 'application/octet-stream'))); } catch (Exception $e) { $response = new \Symfony\Component\HttpFoundation\Response($e->getMessage()); } $response->send(); exit; } } }
/** * Dispatches the current request */ protected function dispatch() { try { $this->dispatcher->dispatch(); } catch (\Exception $ex) { if (env('WP_ENV') != 'production') { $res = new \Symfony\Component\HttpFoundation\Response($this->ui->render('stem-system.error', ['ex' => $ex, 'data' => \ILab\Stem\Core\Response::$lastData]), 500); $res->send(); die; } else { $this->dispatcher->dispatchError(500, $ex); } } }