Table of Contents
1、访问请求实例
2、获取输入
Home Backend Development PHP Tutorial [ Lumen 5.2 文档 ] 基础 -- HTTP 请求

[ Lumen 5.2 文档 ] 基础 -- HTTP 请求

Jun 23, 2016 pm 01:16 PM

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');                 //    }}
Copy after login

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

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

你仍然可以对 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)    {         //    }}
Copy after login

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();
Copy after login

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

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

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

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

获取请求方法

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

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

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
Copy after login

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

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

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

2、获取输入

获取输入值

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

$name = $request->input('name');
Copy after login

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

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

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

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

判断输入值是否出现

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

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

获取所有输入数据

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

$input = $request->all();
Copy after login

获取输入的部分数据

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

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

文件上传

获取上传的文件

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

$file = $request->file('photo');
Copy after login

验证文件是否存在

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

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

验证文件是否上传成功

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

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

保存上传的文件

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

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

其它文件方法

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

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles