Current Location: Home> Latest Articles> How to Modify Redirects in ThinkPHP: Detailed Guide on Routes, Parameters, and Redirect Methods

How to Modify Redirects in ThinkPHP: Detailed Guide on Routes, Parameters, and Redirect Methods

gitbox 2025-06-16

Modifying Redirect Operations in ThinkPHP

When using the ThinkPHP framework, page redirects are a common operation, especially after form submissions when you need to redirect to another page to display results. By default, ThinkPHP uses the redirect()

This code means that after the login operation, it will redirect to the index method of the index controller.

If you need to redirect to a method in another controller, you can modify the code as follows:

        public function login() {
            // ...
            $this->redirect('User/index');
        }
    

This code will redirect to the index method of the User controller after the login operation.

2. Pass Parameters During Redirection

Sometimes, you may need to pass parameters during a redirect. You can add parameters in the redirect() function like this:

        public function login() {
            // ...
            $this->redirect('User/index', ['id' => 1, 'name' => 'test']);
        }
    

This code will pass the parameters id and name to the target page, with values of 1 and 'test' respectively.

In the target controller, you can use the input() function to retrieve the passed parameters:

        public function index() {
            $id = input('id');
            $name = input('name');
            // ...
        }
    

In this code, the id and name parameters passed from the login method can be accessed in the index method.

3. Modify the Redirect Method

By default, ThinkPHP uses the header() function for redirects. If you want to use a meta-based redirect instead, you can modify the configuration file as follows:

        // Using header-based redirect
        'url_convert' => true,
        'url_common_param' => true,
        'url_route_on' => true,
        'url_html_suffix' => 'html',

        // Using meta-based redirect
        'url_meta_refresh' => '1;url=',
    

With this configuration, you can control which type of redirect to use.

4. Using Object-Based Redirects

ThinkPHP also allows redirects using objects. We can use the \Url object to generate the redirect link:

        use think\Url;

        public function index() {
            // ...
            $url = Url::build('User/index', ['id' => 1]);
            return redirect($url);
        }
    

This code generates a redirect URL in the index method and passes the id parameter to the target method of the User controller.

Summary

By modifying redirect routes, passing parameters, changing redirect methods, and using object-based redirects, developers can have flexible control over page redirects in ThinkPHP. These techniques improve code maintainability and scalability, making them very useful in real-world projects.