yii\web\Response::setStatusCode PHP Method

setStatusCode() public method

This method will set the corresponding status text if $text is null.
public setStatusCode ( integer $value, string $text = null )
$value integer the status code
$text string the status text. If not set, it will be set automatically based on the status code.
    public function setStatusCode($value, $text = null)
    {
        if ($value === null) {
            $value = 200;
        }
        $this->_statusCode = (int) $value;
        if ($this->getIsInvalid()) {
            throw new InvalidParamException("The HTTP status code is invalid: {$value}");
        }
        if ($text === null) {
            $this->statusText = isset(static::$httpStatuses[$this->_statusCode]) ? static::$httpStatuses[$this->_statusCode] : '';
        } else {
            $this->statusText = $text;
        }
    }

Usage Example

 /**
  * Uploads the file and update database
  */
 public function run()
 {
     $file = UploadedFile::getInstanceByName('attachment[file]');
     $result = $this->insertMedia($file);
     $response = new Response();
     $response->setStatusCode(200);
     $response->format = Response::FORMAT_JSON;
     if ($result['success'] === true) {
         $response->setStatusCode(200);
         $response->data = ['file' => ['url' => '/' . $result['data']['source'], 'media_id' => $result['data']['id']]];
         $response->send();
     } else {
         $response->statusText = $result['message'];
         $response->setStatusCode(500);
         $response->send();
         Yii::$app->end();
     }
 }
All Usage Examples Of yii\web\Response::setStatusCode