function routeRequest(Response $response, Request $request) { $routesDefinitionsCallback = function (RouteCollector $r) { foreach (require __DIR__ . "/routes.php" as $route) { $r->addRoute($route[0], $route[1], $route[2]); } }; $dispatcher = \FastRoute\simpleDispatcher($routesDefinitionsCallback); $routeInfo = $dispatcher->dispatch($request->getMethod(), $request->getPath()); switch ($routeInfo[0]) { case Dispatcher::NOT_FOUND: $response->setStatusCode(404); $response->setContent('404 - not found'); break; case Dispatcher::METHOD_NOT_ALLOWED: $response->setStatusCode(403); $response->setContent('403 - not allowed'); break; case Dispatcher::FOUND: $response->setStatusCode(200); $className = $routeInfo[1][0]; $method = $routeInfo[1][1]; $vars = $routeInfo[2]; return new Step("{$className}::{$method}", InjectionParams::fromRouteParams($vars)); } return new step(function () { echo "something went wrong"; }); }
/** * Validate a given rule against a route and request. * * @param \Routing\Route $route * @param \Http\Request $request * @return bool */ public function matches(Route $route, Request $request) { $regex = $route->getCompiled()->getHostRegex(); if (is_null($regex)) { return true; } return preg_match($regex, $request->getHost()); }
public function testRequestGetUrl() { $url = "http://www.example.com?pippo=d&o=pil"; $u = "http://www.example.com"; $q = array('pippo' => 'd', 'o' => 'pil'); $request = new Request($url); $this->assertEquals($request->getUrl(), $url); $this->assertEquals($request->getQueries(), $q); }
/** * Validate a given rule against a route and request. * * @param \Routing\Route $route * @param \Http\Request $request * @return bool */ public function matches(Route $route, Request $request) { if ($route->httpOnly()) { return !$request->secure(); } else { if ($route->secure()) { return $request->secure(); } } return true; }
/** * 检查数据 * * @param array|null $data 要验证的数据,默认为null验证表单数据 * * @return array|bool|null */ public final function check($data = null) { $this->data = $data ? $data : $this->request->getPostData(); $rules = $this->rules; $token = Session::get('token'); $post_token = $this->data['token']; if (false === array_search($post_token, $token)) { $this->error = 'token失效'; return false; } $validator = new ValidateRule($this->data); foreach ($rules as $field => $rule) { if (array_key_exists('required', $rule) && !array_key_exists($field, $this->data)) { //必填项 $validator->checkRequired($field, '', $rule['required']); return false; } $value = $this->data[$field]; $xss = true; foreach ($rule as $k => $v) { if ($k == 'xss') { $xss = $v; continue; } $method = 'check' . ucfirst($k); if (!method_exists($validator, $method)) { if (is_callable($v[0])) { //如果第一个参数是函数则使用回调函数 $method = 'checkCallback'; } } if (is_array($v)) { array_unshift($v, $field, $value); $re = call_user_func_array(array($validator, $method), $v); } else { $re = call_user_func_array(array($validator, $method), array($field, $value, $v)); } if ($re !== true) { $this->error = $re; return false; } } if ($xss) { $this->cleanXss($this->data[$field]); } } return $this->data; }
/** * Filter the incoming requests. */ public function filterRequests(Route $route, Request $request) { // Store the Request instance for further processing. $this->request = $request; // Check the User Authorization. if (Auth::user()->hasRole('administrator')) { // The User is authorized; continue the Execution Flow. return null; } if ($request->ajax()) { // On an AJAX Request; just return Error 403 (Access denied) return Response::make('', 403); } // Redirect the User to his/hers Dashboard with a warning message. $status = __d('files', 'You are not authorized to access this resource.'); return Redirect::to('admin/dashboard')->withStatus($status, 'warning'); }
/** * Get the base URL for the request. * * @param string $scheme * @param string $root * @return string */ protected function getRootUrl($scheme, $root = null) { if (is_null($root)) { $root = $this->forcedRoot ?: $this->request->root(); } $start = Str::startsWith($root, 'http://') ? 'http://' : 'https://'; return preg_replace('~' . $start . '~', $scheme, $root, 1); }
public function __construct($edge, $method, $fields) { $url = self::API_URL . ($edge[0] !== '/' ? '/' : '') . $edge; $options = []; if (!empty($fields)) { if ($method === 'get') { $url .= '?' . http_build_query($fields); } else { $options[CURLOPT_POSTFIELDS] = json_encode($fields, JSON_UNESCAPED_UNICODE); } } $options[CURLOPT_CUSTOMREQUEST] = strtoupper($method); parent::__construct($url, $options); }
public function run(Request $request = null) { if (null === $request) { $request = Request::createFromGlobals(); } $method = $request->getMethod(); $uri = $request->getUri(); foreach ($this->routes as $route) { if ($route->match($method, $uri)) { return $this->process($route, $request); } } throw new HttpException(404, 'Page Not Found'); }
public function start($name = 'NDK', $limit = 0, $path = '/', $domain = null, $secure = null) { session_name($name . '_SESSION'); $domain = isset($domain) ? $domain : Request::getServerName(); $https = isset($secure) ? $secure : isset($_SERVER['HTTPS']); session_set_cookie_params($limit, $path, $domain, $https, true); session_start(); if (empty($_SESSION['_NDK_SESSION_TOKEN_'])) { $_SESSION['_NDK_SESSION_TOKEN_'] = base64_encode(Request::getRemoteAddr() . Request::getHttpUserAgent()); } elseif ($_SESSION['_NDK_SESSION_TOKEN_'] != base64_encode(Request::getRemoteAddr() . Request::getHttpUserAgent())) { self::destroy(); session_start(); session_regenerate_id(true); __error__('Your session has been terminated !'); } }
private function responseCode() { if (version_compare(PHP_VERSION, '5.4.0') >= 0) { http_response_code($this->status_code); } else { $status_msg = self::getStatusMessage($this->status_code); if ($status_msg === false) { die; } if (filter_input(INPUT_SERVER, 'FCGI_SERVER_VERSION') != null) { header('Status: ' . $this->status_code . ' ' . $status_msg); } else { $protocol = Request::getServerProtocol(); header($protocol . ' ' . $this->status_code . ' ' . $status_msg); } } }
public function run(Request $request = null) { //Remplacer par $method = $request->getMethode(); //$method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : self::GET; //$uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/'; if (null === $request) { $request = Request::createFromGlobals(); } $uri = $request->getURI(); $method = $request->getMethod(); foreach ($this->routes as $route) { if ($route->match($method, $uri)) { return $this->process($route, $request); } } throw new HttpException(404, 'Page Not Found'); }
/** * Delete a single person based on the ID * * URI: /delete * */ public function delete() { if ($this->request->getParameter('csrf') === $this->csrf->getCurrentToken()) { try { $this->people->deleteById((int) $this->request->getParameter('id')); $message = 'success'; $response = 200; } catch (\Exception $e) { $message = 'failure'; $response = 500; } } else { $message = 'failure'; $response = 500; } $template_vars = array('json' => json_encode(array('message' => $message))); $html = $this->renderer->render('page/data.php', $template_vars); $this->response->setStatusCode($response); $this->response->setContent($html); }
/** * Prepare the request by injecting any services. * * @param \Http\Request $request * @return \Http\Request */ public function prepareRequest(Request $request) { if (!is_null($this['config']['session.driver']) && !$request->hasSession()) { $request->setSession($this['session']->driver()); } return $request; }
/** * Flash an array of input to the session. * * @param mixed string * @return \Nova\Http\RedirectResponse */ public function exceptInput() { return $this->withInput($this->request->except(func_get_args())); }
/** * Validate a given rule against a route and request. * * @param \Routing\Route $route * @param \Http\Request $request * @return bool */ public function matches(Route $route, Request $request) { $regex = $route->getCompiled()->getRegex(); $path = $request->path() == '/' ? '/' : '/' . $request->path(); return preg_match($regex, rawurldecode($path)); }
$response = new Response($content, 200); $response->send(); }); $app->get('/statuses/(\\d+)', function (Request $request, $id) use($app, $statusFinder) { if (!Verification::checkInteger($id)) { $response = new Response("Error with the object ID", 400); $response->send(); return; } $status = $statusFinder->findOneById($id); if (!isset($status)) { $response = new Response("Object doesn't exist", 416); $response->send(); return; } if (Request::guessBestFormat() == 'json') { $response = new Response(json_encode($status), 200); $response->send(); return; } $content = $app->render("unStatus.php", array('status' => $status)); $response = new Response($content, 200); $response->send(); }); $app->get('/statusesForm', function (Request $request) use($app) { return $app->render("statusesForm.php", array('user' => $_SESSION['login'], 'erreur' => '', 'message' => '')); }); $app->post('/statuses', function (Request $request) use($app, $statusMapper) { $message = htmlspecialchars($request->getParameter('message')); $user = htmlspecialchars($request->getParameter('username')); if (!isset($user) || !isset($message)) {
/** * Determine if the filter fails the "on" constraint. * * @param array $filter * @param \Http\Request $request * @param string $method * @return bool */ protected function filterFailsOn($filter, $request, $method) { $on = array_get($filter, 'options.on'); if (is_null($on)) { return false; } if (is_string($on)) { $on = explode('|', $on); } return !in_array(strtolower($request->getMethod()), $on); }
use HTTP\Request; use HTTP\Session; use Routing\Router; require __DIR__ . '/../vendor/autoload.php'; $application = new Application(); $application->share('HTTP\\Session', function () { return new Session(); }); $application->share('i want to save to the session', function (Session $session) { $session->name = 'Reno Jackson'; $session->quotes = 'We\'re gonna be rich'; }); $application->share('i want to read the session', function (Session $session) { dump($session); }); $application->share('i want to flash to the session', function (Session $session) { // $session->flash->city = 'Nijmegen'; }); $application->share('i want to read the session flash', function (Session $session) { dump($session->flash); }); $router = new Router(); $router->add('/', 'i want to save to the session'); $router->add('/read', 'i want to read the session'); $router->add('/add/flash', 'i want to flash to the session'); $router->add('/read/flash', 'i want to read the session flash'); $kernel = new Kernel($router, $application); $response = $kernel->handle(Request::create('/read/flash')); $response->send(); $application->make('HTTP\\Session')->replenish(); dump($_SESSION);
<?php use HTTP\Request; require __DIR__ . '/../vendor/autoload.php'; dd(Request::capture());
//-------------------------------------------------------------------------- $app->instance('config', $config = new ConfigRepository($app->getConfigLoader())); //-------------------------------------------------------------------------- // Set The Default Timezone From Configuration //-------------------------------------------------------------------------- $config = $app['config']['app']; date_default_timezone_set($config['timezone']); //-------------------------------------------------------------------------- // Register The Alias Loader //-------------------------------------------------------------------------- $aliases = $config['aliases']; AliasLoader::getInstance($aliases)->register(); //-------------------------------------------------------------------------- // Enable HTTP Method Override //-------------------------------------------------------------------------- Request::enableHttpMethodParameterOverride(); //-------------------------------------------------------------------------- // Enable Trusting Of X-Sendfile Type Header //-------------------------------------------------------------------------- BinaryFileResponse::trustXSendfileTypeHeader(); //-------------------------------------------------------------------------- // Register The Core Service Providers //-------------------------------------------------------------------------- $providers = $config['providers']; $app->getProviderRepository()->load($app, $providers); //-------------------------------------------------------------------------- // Additional Middleware On Application //-------------------------------------------------------------------------- App::middleware('Shared\\Http\\ContentGuard', array($app['config']['app.debug'])); //-------------------------------------------------------------------------- // Register Booted Start Files
/** * Extract the parameter list from the host part of the request. * * @param \Http\Request $request * @param array $parameters * @return array */ protected function bindHostParameters(Request $request, $parameters) { preg_match($this->compiled->getHostRegex(), $request->getHost(), $matches); return array_merge($this->matchToKeys(array_slice($matches, 1)), $parameters); }
private function loadMethod() { $method = array_shift($this->_segments); if (!$method) { $method = Config::get('default_method'); } $m_tmp = $method . '_' . strtolower(Request::getRequestMethod()); if (method_exists($this->_controller, $m_tmp)) { $method = $m_tmp; } if (method_exists($this->_controller, $method)) { call_user_func_array(array($this->_controller, $method), $this->_segments); } else { throw_error('Method `' . $method . '` is not found !'); } }
/** * Get a route (if necessary) that responds when other available methods are present. * * @param \Http\Request $request * @param array $others * @return \Routing\Route * * @throws \Symfony\Component\Routing\Exception\MethodNotAllowedHttpException */ protected function getOtherMethodsRoute($request, array $others) { if ($request->method() == 'OPTIONS') { return new Route('OPTIONS', $request->path(), function () use($others) { return new Response('', 200, array('Allow' => implode(',', $others))); }); } $this->methodNotAllowed($others); }
<?php // Request HTTP Class require_once 'Http/Request.php'; require_once 'Http/Validator.php'; use Http\Request; use Http\Validator; $request = Request::getInstance(); $validator = new Validator($request); $rules = array('username' => 'required|min:4|max:8', 'email' => 'required|email'); $validator->validate($rules); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Example</title> <style> input[type="text"], textarea { display: block; } textarea, input { width: 50%; border-radius: 5px; font-size: 16px; margin: 3px 0;
<?php use Foundation\Application; use HTTP\Kernel; use HTTP\Request; use Routing\Router; require __DIR__ . '/../vendor/autoload.php'; $application = new Application(); $application->share('i want to see the dashboard', function () { echo '<h1>Dashboard</h1>'; }); $router = new Router(); $router->add('/', 'i want to see the dashboard'); $kernel = new Kernel($router, $application); $request = Request::create('/', 'GET'); $response = $kernel->handle($request); $response->send();
/** * @test */ public function symfony_underscoreAddingToInputWithSpaces_convertedBackToSpaces() { $request = Request::create('/', 'GET', array('sports_exercise' => 'benchpress')); assertThat($request->attributes, is(identicalTo(array('sports exercise' => 'benchpress')))); }
/** * Get the response for a given request. * * @param \Symfony\Component\HttpFoundation\Request $request * @param int $type * @param bool $catch * @return \Http\Response */ public function handle(SymfonyRequest $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true) { return $this->dispatch(Request::createFromBase($request)); }
/** * Validate a given rule against a route and request. * * @param \Routing\Route $route * @param \Http\Request $request * @return bool */ public function matches(Route $route, Request $request) { return in_array($request->getMethod(), $route->methods()); }