yii2: Captcha: Could not load the image.

What steps will reproduce the problem?

Controller

class SiteController extends Controller
{
    ...
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }
    ...
}

Model

class SignupForm extends Model
{
    public $username;
    public $email;
    public $password;
    public $captcha;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
        ...
            ['captcha', 'captcha']
        ...
        ];
    }
}

View

<?= $form->field($model, 'captcha')->widget(\yii\captcha\Captcha::classname(), [
    // configure additional widget properties here
]) ?>

What is the expected result?

Load the image.

What do you get instead?

In my program, Captcha can be displayed properly on some computers, but there are some computers can not be loaded properly, and the browser will appear “Could not load the image”.

screenshot from 2016-07-03 02-48-53

The same computer, download and install “Yii 2 Basic Application Template” can be displayed, but not in my program.

Additional info

I searched the Internet. If the output buffer is not empty, you can not load the image.The solution is to empty the output buffer before output captcha. For example, in [[\yii\captcha\CaptchaAction::run()]]

        } else {
            ob_clean();  //Add this line, can solve this problem. Or add in other suitable places
            $this->setHttpHeaders();
            Yii::$app->response->format = Response::FORMAT_RAW;
            return $this->renderImage($this->getVerifyCode());
        }
Q A
Yii version 2.0.x
PHP version 7.0.4-7ubuntu2.1
Operating system ubuntu 16.04

Is it a bug?

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 1
  • Comments: 19 (6 by maintainers)

Most upvoted comments

Well, that is expected. PHP files should never start with blank lines or BOM else you’ll have broken HTTP headers and unexpected input.

https://stackoverflow.com/questions/48017676/yii2-captcha-image-not-showing

or

please change in \vendor\yiisoft\yii2\captcha\CaptchaAction.php and will show image.

@daliha look at @shi-yang comment above

I had same issue and ob_clean() solved it. Thanks @shi-yang.

I had same issue and ob_clean() solved it (yii 2.0.9). Thanks @shi-yang.