使用PHP cURL从URL获取CSRF-Token并将其发布到同一会话中的另一个URL

时间:2016-08-23 17:27:18

标签: php laravel curl csrf-protection

我正在尝试根据从supermariomakerbookmark.nintendo.net网站收集的信息创建一个队列系统。首先,我在URL https://supermariomakerbookmark.nintendo.net/courses/7E00-0000-0220-574B中发出GET请求,以查找字段中显示的CSRF令牌:

<meta name="csrf-token" content="xxxxxx">

之后,我需要向https://supermariomakerbookmark.nintendo.net/courses/7E00-0000-0220-574B/play_at_later发出POST请求,并在头文件中传递CSRF-Token和Cookie。 cookie由用户提供,并从数据库中检索。

这是我的代码:

$cookie = DB::table('CONFIG')->select('cookies')->first()->cookies;

// get csrf token
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://supermariomakerbookmark.nintendo.net/courses/$id");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$html = curl_exec($ch);

$dom = new \DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($html);

$metas = $dom->getElementsByTagName('meta');

for ($i = 0; $i < $metas->length; $i++){
  $meta = $metas->item($i);
  if($meta->getAttribute('name') == 'csrf-token')
    $csrfToken = $meta->getAttribute('content');
}

$headers = array();
$headers[] = "X-CSRF-Token: $csrfToken";
$headers[] = "Cookie: $cookie";

curl_setopt($ch, CURLOPT_URL, "https://supermariomakerbookmark.nintendo.net/courses/$id/play_at_later");
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$ret = curl_exec($ch);

但它不起作用,curl POST请求返回自定义500错误页面而不是200 OK。我正在Laravel中的Controller中执行此代码。

如果我尝试使用Postman发出POST请求,它可以正常工作。关于如何使其发挥作用的蚂蚁意识形态?

1 个答案:

答案 0 :(得分:0)

我和另一个网络服务有类似的问题。在我的情况下,问题是标题的名称。

尝试更改此代码并对其进行测试:

$headers = array();
$headers[] = "Cookie: X-CSRF-Token=$csrfToken";
$headers[] = "Cookie: X-CSRF-Token=$cookie";