Skip to content

Commit a828d5c

Browse files
committed
Improve CSRF handling
1 parent c78b6f6 commit a828d5c

File tree

1 file changed

+7
-4
lines changed

1 file changed

+7
-4
lines changed

examples/client_auth.php

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,21 @@
33

44
$cookiejar = tempnam(sys_get_temp_dir(), 'cookiejar-');
55

6-
function call($method, $url, $data = false) {
6+
function call($method, $url, $data = false, $csrf = false) {
77
global $cookiejar;
88
$ch = curl_init();
99
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
1010
curl_setopt($ch, CURLOPT_URL, $url);
11+
$headers = array();
1112
if ($data) {
1213
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
13-
$headers = array();
1414
$headers[] = 'Content-Type: application/json';
1515
$headers[] = 'Content-Length: ' . strlen($data);
16-
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
1716
}
17+
if ($csrf) {
18+
$headers[] = 'X-XSRF-TOKEN: ' . $csrf;
19+
}
20+
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
1821
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1922

2023
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiejar);
@@ -25,7 +28,7 @@ function call($method, $url, $data = false) {
2528

2629
// in case you are using php-api-auth:
2730
$csrf = json_decode(call('POST','http://localhost/api.php/', 'username=admin&password=admin'));
28-
$response = call('GET','http://localhost/api.php/posts?include=categories,tags,comments&filter=id,eq,1&csrf='. $csrf);
31+
$response = call('GET','http://localhost/api.php/posts?include=categories,tags,comments&filter=id,eq,1', false, $csrf);
2932

3033
unlink($cookiejar);
3134

0 commit comments

Comments
 (0)