Description

Obtaining Request Object

Webman automatically injects the request object into the first parameter of the action method, for example:

Example

<?php
namespace app\controller;

use support\Request;

class UserController
{
    public function hello(Request $request)
    {
        $default_name = 'webman';
        // Get the name parameter from the GET request; if not provided, return $default_name
        $name = $request->get('name', $default_name);
        // Return a string to the browser
        return response('hello ' . $name);
    }
}

Using the $request object allows us to retrieve any data related to the request.

Sometimes we want to retrieve the current request's $request object in other classes; in this case, we can simply use the helper function request();

Obtaining GET Request Parameters

Get the entire GET array

$request->get();

If there are no GET parameters, it returns an empty array.

Get a specific value from the GET array

$request->get('name');

If this value is not contained in the GET array, it returns null.

You can also pass a default value as the second parameter to the get method, which will be returned if the corresponding value is not found in the GET array. For example:

$request->get('name', 'tom');

Obtaining POST Request Parameters

Get the entire POST array

$request->post();

If there are no POST parameters, it returns an empty array.

Get a specific value from the POST array

$request->post('name');

If this value is not contained in the POST array, it returns null.

Similar to the get method, you can also pass a default value as the second parameter to the post method, which will be returned if the corresponding value is not found in the POST array. For example:

$request->post('name', 'tom');

Helper Function input()

Similar to the $request->input() function, it can get all parameters. The input() helper function has two parameters:

  1. name: The name of the parameter to fetch (if empty, it fetches an array of all parameters)
  2. default: Default value (this value will be used if the first parameter fetch fails)

For example

// Get parameter name
$name = input('name');
// Get parameter name; if it does not exist, use the default value
$name = input('name', '张三');
// Get all parameters
$all_params = input();

Obtaining Raw Request POST Body

$post = $request->rawBody();

This feature is similar to the file_get_contents("php://input"); operation in php-fpm. It is used to obtain the raw HTTP request body. This is particularly useful for obtaining POST request data that is not in application/x-www-form-urlencoded format.

Getting Headers

Get the entire header array

$request->header();

If there are no headers, it returns an empty array. Note that all keys are lowercase.

Get a specific value from the header array

$request->header('host');

If this value is not contained in the header array, it returns null. Note that all keys are lowercase.

Similar to the get method, you can also pass a default value as the second parameter to the header method. If the corresponding value is not found in the header array, it will return the default value. For example:

$request->header('host', 'localhost');

Obtaining Cookies

Get the entire cookie array

$request->cookie();

If there are no cookies, it returns an empty array.

Get a specific value from the cookie array

$request->cookie('name');

If this value is not contained in the cookie array, it returns null.

Similar to the get method, you can also pass a default value as the second parameter to the cookie method. If the corresponding value is not found in the cookie array, it will return the default value. For example:

$request->cookie('name', 'tom');

Obtaining All Input

This contains a collection of post and get.

$request->all();

Obtaining Specific Input Value

Retrieve a certain value from the post and get collection.

$request->input('name', $default_value);

Obtaining Partial Input Data

Retrieve partial data from the post and get collection.

// Get an array consisting of username and password, ignoring any missing keys
$only = $request->only(['username', 'password']);
// Get all input except for avatar and age
$except = $request->except(['avatar', 'age']);

Obtaining Input via Controller Parameters

<?php
namespace app\controller;
use support\Response;

class UserController
{
    public function create(string $name, int $age = 18): Response
    {
        return json(['name' => $name, 'age' => $age]);
    }
}

The code logic is similar to:

<?php
namespace app\controller;
use support\Request;
use support\Response;

class UserController
{
    public function create(Request $request): Response
    {
        $name = $request->input('name');
        $age = (int)$request->input('age', 18);
        return json(['name' => $name, 'age' => $age]);
    }
}

For more information, please refer to Controller Parameter Binding

Obtaining Uploaded Files

Note
Uploading files requires the use of forms in multipart/form-data format.

Get the entire uploaded files array

$request->file();

The form is similar to:

<form method="post" action="http://127.0.0.1:8787/upload/files" enctype="multipart/form-data" />
<input name="file1" multiple="multiple" type="file">
<input name="file2" multiple="multiple" type="file">
<input type="submit">
</form>

The format returned by $request->file() is similar to:

array (
    'file1' => object(webman\Http\UploadFile),
    'file2' => object(webman\Http\UploadFile)
)

This is an array of webman\Http\UploadFile instances. The webman\Http\UploadFile class extends the PHP built-in SplFileInfo class and provides some utility methods.

<?php
namespace app\controller;

use support\Request;

class UploadController
{
    public function files(Request $request)
    {
        foreach ($request->file() as $key => $spl_file) {
            var_export($spl_file->isValid()); // Whether the file is valid, e.g., true|false
            var_export($spl_file->getUploadExtension()); // Upload file extension, e.g., 'jpg'
            var_export($spl_file->getUploadMimeType()); // Upload file MIME type, e.g., 'image/jpeg'
            var_export($spl_file->getUploadErrorCode()); // Get upload error code, e.g., UPLOAD_ERR_NO_TMP_DIR UPLOAD_ERR_NO_FILE UPLOAD_ERR_CANT_WRITE
            var_export($spl_file->getUploadName()); // Uploaded file name, e.g., 'my-test.jpg'
            var_export($spl_file->getSize()); // Get file size, e.g., 13364, in bytes
            var_export($spl_file->getPath()); // Get upload directory, e.g., '/tmp'
            var_export($spl_file->getRealPath()); // Get temporary file path, e.g., '/tmp/workerman.upload.SRliMu'
        }
        return response('ok');
    }
}

Note:

  • Files are temporarily named after being uploaded, e.g., /tmp/workerman.upload.SRliMu.
  • The upload file size is subject to the defaultMaxPackageSize limit, defaulting to 10M, which can be changed in the config/server.php file under max_package_size.
  • Temporary files will be automatically cleared after the request ends.
  • If no files are uploaded in the request, $request->file() returns an empty array.
  • Uploaded files do not support the move_uploaded_file() method; please use the $file->move() method instead, as shown in the following example.

Obtaining Specific Uploaded File

$request->file('avatar');

If the file exists, it returns the corresponding webman\Http\UploadFile instance; otherwise, it returns null.

Example

<?php
namespace app\controller;

use support\Request;

class UploadController
{
    public function file(Request $request)
    {
        $file = $request->file('avatar');
        if ($file && $file->isValid()) {
            $file->move(public_path().'/files/myfile.'.$file->getUploadExtension());
            return json(['code' => 0, 'msg' => 'upload success']);
        }
        return json(['code' => 1, 'msg' => 'file not found']);
    }
}

Obtaining Host

Retrieve the host information of the request.

$request->host();

If the request address is on a non-standard port 80 or 443, the host information may include the port, e.g., example.com:8080. If the port is not needed, the first parameter can be passed as true.

$request->host(true);

Obtaining Request Method

 $request->method();

The return value can be one of GET, POST, PUT, DELETE, OPTIONS, or HEAD.

Obtaining Request URI

$request->uri();

Returns the URI of the request, including the path and query string parts.

Obtaining Request Path

$request->path();

Returns the path portion of the request.

Obtaining Request Query String

$request->queryString();

Returns the query string portion of the request.

Obtaining Request URL

The url() method returns the URL without the Query parameters.

$request->url();

Returns something like //www.workerman.net/workerman-chat.

The fullUrl() method returns the URL with the Query parameters.

$request->fullUrl();

Returns something like //www.workerman.net/workerman-chat?type=download.

Note
The url() and fullUrl() methods do not return the protocol portion (do not return http or https).
This is because browsers automatically recognize the protocol for addresses starting with //example.com, automatically sending requests via http or https.

If you are using nginx as a reverse proxy, please add proxy_set_header X-Forwarded-Proto $scheme; to the nginx configuration, refer to nginx reverse proxy.
This way, you can use $request->header('x-forwarded-proto'); to determine whether it's http or https. For example:

echo $request->header('x-forwarded-proto'); // Outputs http or https

Obtaining Request HTTP Version

$request->protocolVersion();

Returns the string 1.1 or 1.0.

Obtaining Request Session ID

$request->sessionId();

Returns a string composed of letters and numbers.

Obtaining Client IP of the Request

$request->getRemoteIp();

Obtaining Client Port of the Request

$request->getRemotePort();

Obtaining Real Client IP of the Request

$request->getRealIp($safe_mode=true);

When the project uses a proxy (e.g., nginx), the IP obtained from $request->getRemoteIp() is often the proxy server's IP (like 127.0.0.1 192.168.x.x), not the real client's IP. In this case, you can try using $request->getRealIp() to obtain the real client's IP.

The $request->getRealIp() method will attempt to retrieve the real IP from the HTTP headers x-forwarded-for, x-real-ip, client-ip, x-client-ip, and via.

Since HTTP headers are easily spoofed, the IP obtained by this method is not 100% reliable, especially when $safe_mode is false. A more reliable way to obtain the real client IP through a proxy is to know the IP of the secure proxy server and clearly know which HTTP header carries the real IP. If the IP returned by $request->getRemoteIp() matches the known secure proxy server, then you can use $request->header('HTTP Header carrying real IP') to get the real IP.

Obtaining Server IP

$request->getLocalIp();

Obtaining Server Port

$request->getLocalPort();

Checking if an AJAX Request

$request->isAjax();

Checking if a PJAX Request

$request->isPjax();

Checking if JSON Return is Expected

$request->expectsJson();

Checking if Client Accepts JSON Return

$request->acceptJson();

Obtaining Request Plugin Name

Returns an empty string '' if it is not a plugin request.

$request->plugin;

Obtaining Request Application Name

Always returns an empty string '' when a single application is used; returns the application name when there are multiple applications.

$request->app;

Since closure functions do not belong to any application, requests from closure routes always return an empty string '' for $request->app.
For closure routes, refer to Routes.

Obtaining Request Controller Class Name

Obtains the corresponding class name of the controller.

$request->controller;

Returns something like app\controller\IndexController.

Since closure functions do not belong to any controller, requests from closure routes always return an empty string '' for $request->controller.
For closure routes, refer to Routes.

Obtaining Request Method Name

Obtains the corresponding method name of the controller for the request.

$request->action;

Returns something like index.

Since closure functions do not belong to any controller, requests from closure routes always return an empty string '' for $request->action.
For closure routes, refer to Routes.

Overwriting Parameters

Sometimes we want to overwrite request parameters, for example, filtering the request and then reassigning it to the request object; in this case, we can use the setGet(), setPost(), and setHeader() methods.

Overwriting GET Parameters

$request->get(); // Suppose it returns ['name' => 'tom', 'age' => 18]
$request->setGet(['name' => 'tom']);
$request->get(); // Finally returns ['name' => 'tom']

Note
As shown in the example, setGet() overwrites all GET parameters; the same behavior applies to setPost() and setHeader().

Overwriting POST Parameters

$post = $request->post();
foreach ($post as $key => $value) {
    $post[$key] = htmlspecialchars($value);
}
$request->setPost($post);
$request->post(); // Obtains the filtered post parameters

Overwriting HEADER Parameters

$request->setHeader(['host' => 'example.com']);
$request->header('host'); // Outputs example.com