foreaxuse
foreaxuse

Reputation: 1

PHP Laravel api sent json post with curl

My problem is as follows

I have a counter api and it uses 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. However, I take the csrf token from the meta and put it in the headers.

I want to point out that I do not use Laravel, the api I will post is using 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);
?>  

Upvotes: 0

Views: 806

Answers (1)

Ron
Ron

Reputation: 6591

You can disable CSRF token completely for a specific route, if that makes sense for your app.

Check the DOCs and edit app/Http/Middleware/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/*',
    ];
}

Upvotes: 1

Related Questions