cURL X-CSRF令牌问题

时间:2015-01-09 06:34:32

标签: php curl proxy csrf

我使用cURL(下面)有这个PHP代理。只要获得POST,标头X-CSRF标记就会设置为null。 X-CSRF令牌是使用代理之间POST标头的唯一区别。

所以我想知道如何修复它以便正确设置X-CSRF令牌,而不使用代理?

$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0');

$browserRequestHeaders = getallheaders();
$curlRequestHeaders = array();
foreach ($browserRequestHeaders as $name => $value) {
  $curlRequestHeaders[] = $name . ": " . $value;
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $curlRequestHeaders);


switch ($_SERVER["REQUEST_METHOD"]) {
  case "POST":
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents("php://input"));
  break;
  case "PUT":
    curl_setopt($ch, CURLOPT_PUT, TRUE);
    curl_setopt($ch, CURLOPT_INFILE, fopen("php://input"));
  break;
}

//Other cURL options.
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt ($ch, CURLOPT_FAILONERROR, TRUE);
curl_setopt($ch, CURLOPT_NOBODY, 0);

// Cookie cURL options.
curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile); 
curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);

//handle other cookies cookies
foreach ($_COOKIE as $k=>$v) {
  if(is_array($v)){
    $v = serialize($v);
  }
    curl_setopt($ch,CURLOPT_COOKIE,"$k=$v; domain=.$cookiedomain ; path=/");
  }

// Set the request URL.
curl_setopt($ch, CURLOPT_URL, $url);

// Make the request.
$response = curl_exec($ch);
curl_setopt($ch, CURLOPT_POST, 0);
$responseInfo = curl_getinfo($ch);
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
curl_close($ch);

图片显示标题http://i.stack.imgur.com/78fVV.jpg

2 个答案:

答案 0 :(得分:1)

您正在使用AJAX调用,如图所示,X-CSRF-Token标头未在这些调用中设置。您需要按照Adding X-CSRF-Token header globally to all instances of XMLHttpRequest();中的说明明确设置,例如with(从那里复制):

(function() {
var send = XMLHttpRequest.prototype.send,
    token = $('meta[name=csrf-token]').attr('content');
XMLHttpRequest.prototype.send = function(data) {
    this.setRequestHeader('X-CSRF-Token', token);
    return send.apply(this, arguments);
};
}());

所以修复不是在PHP中,而是在你的AJAX调用代码中。将token = $('meta[name=csrf-token]').attr('content');替换为从HTML获取CSRF令牌的代码。

答案 1 :(得分:0)

必须代理$_SESSION中客户端和服务器之间的php ID。