This method can read the client host name from the "X-Forwarded-Host" header
when trusted proxies were set via "setTrustedProxies()".
The "X-Forwarded-Host" header must contain the client host name.
If your reverse proxy uses a different header name than "X-Forwarded-Host",
configure it via "setTrustedHeaderName()" with the "client-host" key.
/** * Returns true if the host of both specified requests match. * * @param Request $first First request to match. * @param Request $second Second request to match. * * @return boolean True if the host of both specified requests match. */ public static function matchHost(Request $first, Request $second) { if (null !== $first->getHost() && !preg_match('#' . str_replace('#', '\\#', $first->getHost()) . '#i', $second->getHost())) { return false; } return true; }
/** * Extract the subdomain from url * @return string subdomain parameter value */ private function extractSubdomainFromUrl() { if (\Request::getHost() != $this->tenantManager->getDomain()) { return str_ireplace($this->tenantManager->getDomain(), "", \Request::getHost()); } return false; }
function websocket_url($path = '', $port = false, $tail = '', $scheme = 'ws://') { $root = Request::getHost(); $start = starts_with($root, 'http://') ? 'http://' : 'https://'; $root = $scheme . $root; $root .= ':' . ($port ? $port : Request::getPort()); return trim($root . ($path ? '/' . trim($path . '/' . $tail, '/') : ''), '/'); }
/** * {@inheritdoc} */ public function matches(Request $request) { if (null !== $this->methods && !in_array(strtolower($request->getMethod()), $this->methods)) { return false; } if (null !== $this->path && !preg_match($this->path, $request->getPathInfo())) { return false; } if (null !== $this->host && !preg_match($this->host, $request->getHost())) { return false; } if (null !== $this->ip && !$this->checkIp($this->host, $request->getClientIp())) { return false; } return true; }
public function send(Request $request, Response $response = null, $useAuth = true) { if (is_null($response)) { $response = new Response(); } if (null === $request->getHost()) { $request->setHost($this->host); } if ($useAuth) { if (null === $this->accessToken) { throw new Exception("Access token not provided"); } $request->addHeader('Authorization: Bearer ' . $this->accessToken); } $client = $this->createClient(); $client->send($request, $response); if (!$response->isSuccessful()) { throw new ApiException('Operation failed, check `clientId` and `clientSecret`: ' . $response->getError(), $request, $response); } return $response; }
public static function run() { $dotenv = new \Dotenv\Dotenv(TXTROOT); $dotenv->load(); if (isset($_SERVER['HTTP_USER_AGENT']) && stripos($_SERVER['HTTP_USER_AGENT'], 'Slackbot-LinkExpanding') !== false) { Response::sendResponse(Response::HTTP_403, ['error' => "No slackbots allowed"]); exit; } if (!getenv('REDIS_URL')) { Response::sendResponse(Response::HTTP_500, ['error' => "REDIS_URL environment variable required"]); exit; } if (!Request::isGet() && !Request::isPost()) { Response::sendResponse(Response::HTTP_405, ['error' => "Please use a GET or POST"]); exit; } if (getenv('AUTH') && (!isset($_POST['auth']) || !static::compareStrings(getenv('AUTH'), $_POST['auth']))) { Response::sendResponse(Response::HTTP_401, ['error' => "'auth' parameter is missing or invalid"]); exit; } // header('Access-Control-Allow-Origin: ' . $_SERVER['ORIGIN']); // header('Access-Control-Allow-Credentials: true'); // Access-Control-Allow-Methods: GET, POST // x-frame-options $redis = Redis::getRedis(getenv('REDIS_URL')); $hash = ltrim(Request::getPath(), '/'); if ($hash) { if ($hash == 'robots.txt') { Response::setStatus(Response::HTTP_200); Response::setContentType(Response::TEXT); Response::setContent("User-agent: *\nDisallow: /"); Response::send(); exit; } if (Request::isPost()) { Response::sendResponse(Response::HTTP_405, ['error' => "Cannot post to a hash"]); exit; } if (strlen($hash) > Redis::MAX_KEY_LENGTH || !preg_match('/^[A-Za-z0-9]+$/', $hash)) { Response::sendResponse(Response::HTTP_404, ['error' => "Invalid hash"]); exit; } $data = $redis->hGetAll(Redis::PREFIX . $hash); if (!$data) { Response::sendResponse(Response::HTTP_404, ['error' => "Hash not found"]); exit; } $datum = Datum::createFromArray($data); if ($datum->once) { $redis->del(Redis::PREFIX . $hash); } // set proper cache header, esp for read-once // actually, PROBABLY NOT A GOOD IDEA, esp for things that are meant to expire. we should do the opposite - dont cache // Response::setCacheForeverHeaders(); Response::sendResponse('datum', ['datum' => $datum]); exit; } if (Request::isGet()) { Response::sendResponse('home', ['domain' => 'http' . (Request::isSSL() ? 's' : '') . '://' . Request::getHost()]); exit; } else { $data = isset($_POST['data']) ? $_POST['data'] : file_get_contents("php://input"); if (!$data) { Response::sendResponse(Response::HTTP_400, ['error' => 'No data submitted']); exit; } $datum = new Datum(trim($data), Datum::T_TEXT, Request::isFlagOn('once')); $key = substr(static::randId(), 0, Redis::MAX_KEY_LENGTH); $ttl = isset($_POST['ttl']) ? max(1, min((int) $_POST['ttl'], Redis::MAX_TTL)) : Redis::MAX_TTL; $redis->hMSet(Redis::PREFIX . $key, $datum->toArray()); $redis->expire(Redis::PREFIX . $key, $ttl); $url = 'http' . (Request::isSSL() ? 's' : '') . '://' . Request::getHost() . '/' . $key; Response::sendResponse(Response::HTTP_201, ['url' => $url, 'ttl' => $ttl, '_textKey' => 'url']); exit; } }
/** * 前台路由转发 ... */ protected static function _initRoute() { $host = Request::getHost(); $item = 'www'; $pattern = "/^([a-z]+)\\." . GAME_DOMAIN_ROOT . "/"; if (preg_match($pattern, strtolower($host), $matches)) { $item = $matches[1]; } $params = array('file' => 'index', 'action' => 'main', 'param' => '', 'item' => $item); if (preg_match("/\\/([^\\/]+)(\\/*)([^\\/]*)(\\/*)(.*)/", REQUEST_URI, $matches)) { $params['file'] = $matches[1] ? $matches[1] : 'index'; $params['action'] = $matches[3] ? $matches[3] : 'main'; $params['param'] = $matches[5] ? $matches[5] : ''; } //把GET部分删掉,最后在合并 $strpos = strpos($params['param'], '?'); if ($strpos !== false) { $params['param'] = substr($params['param'], 0, $strpos); } $param = array(); $params['param'] = explode('-', $params['param']); if (count($params['param']) % 2 != 0) { array_pop($params['param']); } foreach ($params['param'] as $k => $p) { if ($k % 2 == 0) { $param[$p] = $params['param'][$k + 1]; } } $param = array_merge($param, $_GET); $param = array_merge($param, $_POST); $params['param'] = $param; return $params; }
public function showWelcome() { return View::make('index')->with('host_warning', preg_match('/thokk/', Request::getHost())); }
public function testGetHost_Undefined() { $request = new Request(); $this->assertThat($request->getHost(), $this->equalTo('')); }
/** * Extract the subdomain from url * @return string subdomain parameter value */ private function extractSubdomainFromUrl() { $subdomain = str_ireplace("." . $this->tenantManager->getDomain(), "", \Request::getHost()); return $subdomain; }
/** * {@inheritdoc} */ public function matches(Request $request) { if (null !== $this->methods && !in_array(strtolower($request->getMethod()), $this->methods)) { return false; } foreach ($this->attributes as $key => $pattern) { if (!preg_match('#^' . $pattern . '$#', $request->attributes->get($key))) { return false; } } if (null !== $this->path && !preg_match('#^' . $this->path . '$#', $request->getPathInfo())) { return false; } if (null !== $this->host && !preg_match('#^' . $this->host . '$#', $request->getHost())) { return false; } if (null !== $this->ip && !$this->checkIp($this->host, $request->getClientIp())) { return false; } return true; }
public function testFromUrlLeaveHostEmptyIfNoneIsProvided() { $request = new Request(); $request->fromUrl('/foo'); $this->assertNull($request->getHost()); }
public function matches(Request $request) { if ($this->schemes && !in_array($request->getScheme(), $this->schemes)) { return false; } if ($this->methods && !in_array($request->getMethod(), $this->methods)) { return false; } foreach ($this->attributes as $key => $pattern) { if (!preg_match('{' . $pattern . '}', $request->attributes->get($key))) { return false; } } if (null !== $this->path && !preg_match('{' . $this->path . '}', rawurldecode($request->getPathInfo()))) { return false; } if (null !== $this->host && !preg_match('{' . $this->host . '}i', $request->getHost())) { return false; } if (IpUtils::checkIp($request->getClientIp(), $this->ips)) { return true; } return count($this->ips) === 0; }
$locales = Config::get('app.locales'); if (@(!$locales[Request::segment(1)])) { if (Request::path() != '/') { ## Если не главная страница - подставим дефолтную локаль и сделаем редирект #Helper::dd(Config::get('app.locale') . '/' . Request::path()); Redirect(URL::to(Config::get('app.locale') . '/' . Request::path())); } } }); function Redirect($url = '', $code = '301 Moved Permanently') { header("HTTP/1.1 {$code}"); header("Location: {$url}"); die; } ############################################################################### ## MOBILE VERSION ## Template changing by mobile subdomain ############################################################################### $host = explode('.', Request::getHost()); if (count($host) > 2 && Config::get('site.mobile.enabled') && NULL !== ($mobile_domain = Config::get('site.mobile.domain')) && NULL !== ($mobile_template = Config::get('site.mobile.template')) && $host[0] == $mobile_domain && is_dir(app_path('views/templates/' . $mobile_template))) { Config::set('site.mobile.active', TRUE); Config::set('app.template', $mobile_template); if (NULL !== ($mobile_theme_path = Config::get('site.mobile.theme_path'))) { Config::set('site.theme_path', $mobile_theme_path); } elseif (NULL !== ($mobile_theme_path = Config::get('site.mobile_theme_path'))) { Config::set('site.theme_path', $mobile_theme_path); } } ## Выводит на экран все SQL-запросы #Event::listen('illuminate.query',function($query){ echo "<pre>" . print_r($query, 1) . "</pre>\n"; });
/** * {xhub:getcfg variable} * * @param string $options Variable name * @return string */ private function _getCfg($options) { $options = trim($options, " \n\t\r}"); $sitename = Config::get('sitename'); $live_site = rtrim(Request::base(), '/'); if ($options == 'hubShortName') { return $sitename; } else { if ($options == 'hubShortURL') { return $live_site; } else { if ($options == 'hubHostname') { return Request::getHost(); } } } return ''; }
/** * {@inheritdoc} */ public function matches(Request $request) { if (null !== $this->methods && !in_array(strtolower($request->getMethod()), $this->methods)) { return false; } foreach ($this->attributes as $key => $pattern) { if (!preg_match('#' . str_replace('#', '\\#', $pattern) . '#', $request->attributes->get($key))) { return false; } } if (null !== $this->path) { if (null !== ($session = $request->getSession())) { $path = strtr($this->path, array('{_locale}' => $session->getLocale(), '#' => '\\#')); } else { $path = str_replace('#', '\\#', $this->path); } if (!preg_match('#' . $path . '#', $request->getPathInfo())) { return false; } } if (null !== $this->host && !preg_match('#' . str_replace('#', '\\#', $this->host) . '#', $request->getHost())) { return false; } if (null !== $this->ip && !$this->checkIp($request->getClientIp())) { return false; } return true; }
/** * Ensures that setHost can be used to set a host * * @return void * * @test */ public function hostCanBeSetWithSetHost() { $host = uniqid() . '.com'; $request = new \Request($this->config, []); $request->setHost($host); $this->assertEquals($host, $request->getHost()); }
/** * Create a new job based on the PUT parameters given and content-type. */ public static function createJob($uri) { list($collection_uri, $name) = self::getParts($uri); // Retrieve the parameters of the PUT requests (either a JSON document or a key=value string) $params = \Request::getContent(); // Is the body passed as JSON, if not try getting the request parameters from the uri if (!empty($params)) { $params = json_decode($params, true); } else { $params = \Input::all(); } // If we get empty params, then something went wrong if (empty($params)) { \App::abort(400, "The parameters could not be parsed from the body or request URI, make sure parameters are provided and if they are correct (e.g. correct JSON)."); } // Validate the job properties $job_params = self::validateParameters('Job', 'job', $params); // Retrieve the collection uri and resource name $matches = array(); // Check which parts are set for validation purposes $extract = @$params['extract']; $map = @$params['map']; $load = @$params['load']; $publisher = @$params['publish']; // Check for every emlp part if the type is supported $extractor = self::validateType(@$extract, 'extract'); $mapper = self::validateType(@$map, 'map'); $loader = self::validateType(@$load, 'load'); $publisher = self::validateType(@$publisher, 'publish'); // Save the emlp models $extractor->save(); $loader->save(); if (!empty($mapper)) { $mapper->save(); } if (!empty($publisher)) { $publisher->save(); } // Create the job associated with emlp relations $job = new \Job(); $job->collection_uri = $collection_uri; $job->name = $name; // Add the validated job params foreach ($job_params as $key => $value) { $job->{$key} = $value; } $job->extractor_id = $extractor->id; $job->extractor_type = self::getClass($extractor); $job->mapper_id = @$mapper->id; $job->mapper_type = self::getClass($mapper); $job->loader_id = $loader->id; $job->loader_type = self::getClass($loader); $job->publisher_id = @$publisher->id; $job->publisher_type = self::getClass($publisher); $job->save(); $response = \Response::make(null, 200); $response->header('Location', \Request::getHost() . '/' . $uri); return $response; }
/** * {@inheritdoc} */ public function matches(Request $request) { if ($this->methods && !in_array($request->getMethod(), $this->methods)) { return false; } foreach ($this->attributes as $key => $pattern) { if (!preg_match('{' . $pattern . '}', $request->attributes->get($key))) { return false; } } if (null !== $this->path && !preg_match('{' . $this->path . '}', rawurldecode($request->getPathInfo()))) { return false; } if (null !== $this->host && !preg_match('{' . $this->host . '}i', $request->getHost())) { return false; } if (IpUtils::checkIp($request->getClientIp(), $this->ips)) { return true; } // Note to future implementors: add additional checks above the // foreach above or else your check might not be run! return count($this->ips) === 0; }
<?php /* |-------------------------------------------------------------------------- | Application & Route Filters |-------------------------------------------------------------------------- | | Below you will find the "before" and "after" events for the application | which may be used to do any work before or after a request into your | application. Here you may also register your custom route filters. | */ App::before(function ($request) { preg_match("/^(..)(.*)\$/", Request::getHost(), $parts); $is_real = in_array($parts[1], Config::get('site.available_languages')); Config::set('language', $is_real ? $parts[1] : Config::get('site.default_language')); // English isn't "real", which helps us out here Config::set('language_base_url', ($is_real ? substr($parts[2], 1) : $parts[0]) . $_SERVER['REQUEST_URI']); }); App::after(function ($request, $response) { // }); /* |-------------------------------------------------------------------------- | Authentication Filters |-------------------------------------------------------------------------- | | The following filters are used to verify that the user of the current | session is logged into this application. The "basic" filter easily | integrates HTTP Basic authentication for quick, simple checking. |
/** * {@inheritdoc} * * @api */ public function matches(Request $request) { if ($this->methods && !in_array($request->getMethod(), $this->methods)) { return false; } foreach ($this->attributes as $key => $pattern) { if (!preg_match('#' . str_replace('#', '\\#', $pattern) . '#', $request->attributes->get($key))) { return false; } } if (null !== $this->path) { $path = str_replace('#', '\\#', $this->path); if (!preg_match('#' . $path . '#', rawurldecode($request->getPathInfo()))) { return false; } } if (null !== $this->host && !preg_match('#' . str_replace('#', '\\#', $this->host) . '#i', $request->getHost())) { return false; } if (null !== $this->ip && !IpUtils::checkIp($request->getClientIp(), $this->ip)) { return false; } return true; }
/** * Returns true if the host of both specified requests match. * * @param Request $first First request to match. * @param Request $second Second request to match. * * @return boolean True if the host of both specified requests match. */ public static function matchHost(Request $first, Request $second) { return $first->getHost() === $second->getHost(); }