简体   繁体   English

PHP Laravel api 发送 json 邮寄 curl

[英]PHP Laravel api sent json post with curl

My problem is as follows我的问题如下

I have a counter api and it uses laravel .我有一个计数器api ,它使用laravel I need to send a post as json to this api , but when I send without headers, 419 page returns as expired, when I send headers, I get a csrf token missmatch error.我需要发送一个json的帖子到这个api ,但是当我发送没有标题时, 419页面返回为过期,当我发送标题时,我得到一个csrf token missmatch不匹配错误。 However, I take the csrf token from the meta and put it in the headers.但是,我从元数据中获取csrf令牌并将其放入标头中。

I want to point out that I do not use Laravel, the api I will post is using Laravel.我想指出,我不使用 Laravel,我将发布的 api 使用的是 Laravel。

My Code:我的代码:

<?php 
$data = 'JSON DATA'; 
$wow = json_encode($data);

$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookie.txt");
curl_setopt($ch, CURLOPT_URL,"laravel api url");

$dom = new DOMDocument;
$dom->loadHTML($resultado);
$tags = $dom->getElementsByTagName('meta');
for ($i = 0; $i < $tags->length; $i++) {
    $grab = $tags->item($i);
    if ($grab->getAttribute('name') == 'csrf-token') {
        $token = $grab->getAttribute('content');
    }
}

ob_start();      // prevent any output
curl_exec ($ch); // execute the curl command
ob_end_clean();  // stop preventing output

curl_close ($ch);
unset($ch);

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt");
curl_setopt($ch, CURLOPT_URL,"LARAVEL API URL");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $wow);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Accept: application/json, text/plain, */*',
    'Accept-Encoding: gzip, deflate, br',
    'X-CSRF-TOKEN: '.$token.''));

$buf2 = curl_exec ($ch);

curl_close ($ch);

echo htmlentities($buf2);
?>  

You can disable CSRF token completely for a specific route , if that makes sense for your app.如果这对您的应用有意义,您可以为特定route完全禁用CSRF token

Check the DOCs and edit app/Http/Middleware/VerifyCsrfToken.php检查文档并编辑app/Http/Middleware/VerifyCsrfToken.php VerifyCsrfToken.php

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'stripe/*',
        'http://example.com/foo/bar',
        'http://example.com/foo/*',
    ];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM