相关疑难解决方法(0)

如何修复PHP中的"Headers already sent"错误

运行我的脚本时,我收到几个这样的错误:

警告:不能更改头信息-头已经发出(输出开始/some/file.php:12)在/some/file.php线23

错误消息中提到的行包含header()setcookie()调用.

这可能是什么原因?以及如何解决它?

php header

833
推荐指数
10
解决办法
133万
查看次数

使用PHPUnit测试PHP头文件

我正在尝试使用PHPunit来测试输出一些自定义标头的类.

问题是在我的机器上这个:

<?php

class HeadersTest extends PHPUnit_Framework_TestCase {

    public function testHeaders()
    {
        ob_start();

        header('Location: foo');
        $headers_list = headers_list();
        header_remove();

        ob_clean();

        $this->assertContains('Location: foo', $headers_list);
    }
}
Run Code Online (Sandbox Code Playgroud)

甚至这个:

<?php

class HeadersTest extends PHPUnit_Framework_TestCase {

    public function testHeaders()
    {
        ob_start();

        header('Location: foo');
        header_remove();

        ob_clean();
    }
}
Run Code Online (Sandbox Code Playgroud)

返回此错误:

name@host [~/test]# phpunit --verbose HeadersTest.php 
PHPUnit 3.6.10 by Sebastian Bergmann.

E

Time: 0 seconds, Memory: 2.25Mb

There was 1 error:

1) HeadersTest::testHeaders
Cannot modify header information - headers already sent by (output started at /usr/local/lib/php/PHPUnit/Util/Printer.php:173)

/test/HeadersTest.php:9 …
Run Code Online (Sandbox Code Playgroud)

php phpunit unit-testing output-buffering

87
推荐指数
4
解决办法
3万
查看次数

Symfony PHPUnit:无法启动会话,因为标头已发送

版本:

  • PHP:8.1
  • PHP 单元:9.5.21
  • 交响乐6.1

当 PhpUnit 运行以下测试时,我收到有关会话无法启动的错误。有谁知道这个问题以及如何解决它?

以下主题无法回答我的问题,或者建议的解决方案对我不起作用:

我尝试了第二个链接建议的解决方案:@session_start()@runInSeparateProcess没有任何效果。也许我只是误解了我的问题,但我现在被困了一个星期。

protected function setUp(): void
{
  @session_start();
  parent::setUp();
}

/**
 * @runInSeparateProcess
 */
public function testLoginFailure(): void
{
    $client = static::createClient();
    $crawler = $client->request('GET', '/login');

    $form = $crawler->selectButton('Login')->form();

    $form['email']->setValue('bob@gmail.com');
    $form['password']->setValue('123abcABC%');

    $crawler = $client->submit($form);
    $this->assertResponseIsSuccessful();
}
Run Code Online (Sandbox Code Playgroud)
<!-- Failed to start the session because headers have already been sent by &quot;C:\Users\cimba\Documents\project\vendor\phpunit\phpunit\src\Util\Printer.php&quot; at line 104. (500 Internal Server Error) -->

C:\Users\cimba\Documents\project\vendor\symfony\framework-bundle\Test\BrowserKitAssertionsTrait.php:142
C:\Users\cimba\Documents\project\vendor\symfony\framework-bundle\Test\BrowserKitAssertionsTrait.php:33
C:\Users\cimba\Documents\project\tests\InternalLoginTest.php:51 …
Run Code Online (Sandbox Code Playgroud)

php phpunit symfony php-8.1 symfony6

3
推荐指数
1
解决办法
2999
查看次数