Skip to content

Commit d3be958

Browse files
committed
Improve the csrf_field helper
The helper can now be called multiple times during a single request and always output the valid CSRF token. Before, every call generated a new token, making all previous tokens invalid.
1 parent 477a603 commit d3be958

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

src/helpers.php

+9-3
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,20 @@
88
/**
99
* Generate a CSRF token form field.
1010
*
11-
* @param string $token The CSRF token. If empty a new one will be generated.
11+
* This function can be called multiple times and will reuse the same token during a
12+
* single request.
13+
*
14+
* @param string $t The CSRF token to use. If empty a new one will be generated and reused for the duration of a request.
1215
*
1316
* @return string
1417
*/
15-
function csrf_field($token = null)
18+
function csrf_field($t = null)
1619
{
20+
// remember the token for multipme function calls
21+
static $token = null;
1722
$token = $token ?: csrf();
18-
return '<input type="hidden" name="'.Form::CSRF_FIELD.'" value="'.$token.'">';
23+
// the token parameter overrides the generated token
24+
return '<input type="hidden" name="'.Form::CSRF_FIELD.'" value="'.($t ?: $token).'">';
1925
}
2026
}
2127

tests/HelperTest.php

+8-1
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,18 @@
44

55
class HelperTest extends TestCase
66
{
7-
public function testFunction ()
7+
public function testFunction()
88
{
99
$this->assertTrue(function_exists('csrf_field'));
1010
$this->assertTrue(function_exists('honeypot_field'));
1111
$this->assertTrue(function_exists('uniform_captcha'));
1212
$this->assertTrue(function_exists('captcha_field'));
1313
}
14+
15+
public function testCsrfField()
16+
{
17+
// the token should not be regenerated during a single request
18+
$this->assertEquals(csrf_field(), csrf_field());
19+
$this->assertContains('value="abc"', csrf_field('abc'));
20+
}
1421
}

0 commit comments

Comments
 (0)