Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Requests and responses

A request is what the browser sent: URL parameters, form fields, headers. A response is what the site sends back. In Yii two components handle them: Yii::$app->request and Yii::$app->response. They have no files of their own; you use them inside controller actions.

Reading parameters

Add a search action to controllers/PostController.php:

// controllers/PostController.php
use Yii;
 
public function actionSearch(): string
{
    $q = Yii::$app->request->get('q', '');
 
    return "You searched for: $q";
}

The URL /post/search?q=yii shows "You searched for: yii". The second argument of get() is the default value for the case when the parameter is missing.

Request methods

CallWhat it returns
$request->get('q')A URL parameter
$request->post('title')A field of the submitted form
$request->post()All form fields as an array
$request->isPosttrue if the request method is POST
$request->isAjaxtrue if the request was sent by a script
$request->userIPThe visitor's address
$request->headers->get('User-Agent')A request header

Here $request is Yii::$app->request.

Redirect

After saving data the visitor is sent to another page with the controller method redirect():

public function actionRandom()
{
    return $this->redirect(['post/view', 'id' => 5]);
}

The URL is given the same way as in Url::to(): a route and parameters. A browser that opens /post/random ends up at /posts/5. There are short variants too: $this->goHome() leads to the home page, $this->refresh() reopens the current page.

A JSON response

JSON is a text format for exchanging data between programs. The asJson() method turns an array into such a response:

public function actionStatus()
{
    return $this->asJson(['status' => 'ok', 'posts' => 12]);
}

The page /post/status prints {"status":"ok","posts":12} and sends the header Content-Type: application/json.

The 404 error

To answer "page not found", throw an exception:

use yii\web\NotFoundHttpException;
 
public function actionView(int $id): string
{
    if ($id > 100) {
        throw new NotFoundHttpException('Post not found.');
    }
 
    return "Post number $id";
}

The URL /posts/500 shows the standard error page with code 404 and your text. Other codes have similar classes: ForbiddenHttpException (403), BadRequestHttpException (400).

Sending a file

public function actionDownload()
{
    return Yii::$app->response->sendFile(Yii::getAlias('@app/files/price.pdf'));
}

The browser offers to save the file. The @app part is a path alias that means the project folder.

Common mistake

redirect() does not stop the action by itself; it only returns a response object. Without return the code keeps running and no redirect happens. Always write return $this->redirect(...).

Thanks for reading!

Donate to the site — we work hard for you.