search
HomeBackend DevelopmentPHP Tutorial[ Lumen 5.2 文档 ] 基础 -- HTTP 请求

1、访问请求实例

通过依赖注入获取当前HTTP请求实例,应该在控制器的构造函数或方法中对 Illuminate\Http\Request类进行类型提示,当前请求实例会被服务容器自动注入:

<?phpnamespace App\Http\Controllers;use Illuminate\Http\Request;use Illuminate\Routing\Controller;class UserController extends Controller{    /**     * 存储新用户     *     * @param  Request  $request     * @return Response     */    public function store(Request $request)    {        $name=$request->input('name');                 //    }}

如果你的控制器方法还期望获取路由参数输入,只需要将路由参数置于其它依赖之后即可,例如,如果你的路由定义如下:

$app->put('user/{id}','UserController@update');

你仍然可以对 Illuminate\Http\Request进行类型提示并通过如下方式定义控制器方法来访问路由参数:

<?php    namespace App\Http\Controllers;    use Illuminate\Http\Request;use Illuminate\Routing\Controller;classUser Controller extends Controller{    /**     * 更新指定用户     *     * @param  Request  $request     * @param  int  $id     * @return Response     */     public function update(Request $request,$id)    {         //    }}

1.1 基本请求信息

Illuminate\Http\Request实例提供了多个方法来检测应用的HTTP请求,Lumen的 Illuminate\Http\Request继承自 Symfony\Component\HttpFoundation\Request类,这里列出了一些该类中的有用方法:

获取请求URI

path方法将会返回请求的URI,因此,如果进入的请求路径是 http://domain.com/foo/bar,则 path方法将会返回 foo/bar:

$uri=$request->path();

is方法允许你验证进入的请求是否与给定模式匹配。使用该方法时可以使用 *通配符:

if($request->is('admin/*')){    //}

想要获取完整的URL,而不仅仅是路径信息,可以调用请求实例的 url或 fullUrl方法:

//不带请求参数$url=$request->url();//带请求参数$url = $request->fullUrl();

 获取请求方法

method方法将会返回请求的HTTP请求方式。你还可以使用 isMethod方法来验证HTTP请求方式是否匹配给定字符串:

$method=$request->method();if($request->isMethod('post')){     //}

1.2 PSR-7 请求

PSR-7标准指定了HTTP消息接口,包括请求和响应。如果你想要获取PSR-7请求实例,首先需要安装一些库,Lumen使用Symfony HTTP Message Bridge组件将典型的Lumen请求和响应转化为PSR-7兼容的实现:

composer require symfony/psr-http-message-bridgecomposer require zendframework/zend-diactoros

安装完这些库之后,你只需要在路由或控制器中通过对请求类型进行类型提示就可以获取PSR-7请求:

use Psr\Http\Message\ServerRequestInterface;$app->get('/', function (ServerRequestInterface $request) {    //});

如果从路由或控制器返回的是PSR-7响应实例,则其将会自动转化为Lumen响应实例并显示出来。

2、获取输入

获取输入值

使用一些简单的方法,就可以从 Illuminate\Http\Request实例中访问用户输入。你不需要担心请求所使用的HTTP请求方法,因为对所有请求方式的输入访问接口都是一致的:

$name = $request->input('name');

你还可以传递一个默认值作为第二个参数给 input方法,如果请求输入值在当前请求未出现时该值将会被返回:

$name = $request->input('name', 'Sally');

处理表单数组输入时,可以使用”.”来访问数组:

$input = $request->input('products.0.name');$names = $request->input('products.*.name');

判断输入值是否出现

判断值是否在请求中出现,可以使用 has方法,如果值出现过了且不为空, has方法返回 true:

if ($request->has('name')) {    //}

获取所有输入数据

你还可以通过 all方法获取所有输入数据:

$input = $request->all();

获取输入的部分数据

如果你需要取出输入数据的子集,可以使用 only或 except方法,这两个方法都接收一个数组或动态参数列表作为唯一参数:

$input = $request->only('username', 'password');$input = $request->only('username', 'password');$input = $request->except('credit_card');$input = $request->except('credit_card');

文件上传

获取上传的文件

可以使用 Illuminate\Http\Request实例的 file方法来访问上传文件,该方法返回的对象是 Symfony\Component\HttpFoundation\File\UploadedFile类的一个实例,该类继承自PHP标准库中提供与文件交互方法的 SplFileInfo类:

$file = $request->file('photo');

验证文件是否存在

使用 hasFile方法判断文件在请求中是否存在:

if ($request->hasFile('photo')) {    //}

验证文件是否上传成功

使用 isValid方法判断文件在上传过程中是否出错:

if ($request->file('photo')->isValid()){    //}

保存上传的文件

使用 move方法将上传文件保存到新的路径,该方法将上传文件从临时目录(在PHP配置文件中配置)移动到指定新目录:

$request->file('photo')->move($destinationPath);$request->file('photo')->move($destinationPath, $fileName);

其它文件方法

UploadedFile实例中很有很多其它方法,查看 该类的API了解更多相关方法。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software