[英]Post Json and audio file with php (curl) to a laravel API
[英]PHP Laravel api sent json post with curl
我的问题如下
我有一个计数器api ,它使用laravel 。 我需要发送一个json的帖子到这个api ,但是当我发送没有标题时, 419
页面返回为过期,当我发送标题时,我得到一个csrf token missmatch
不匹配错误。 但是,我从元数据中获取csrf令牌并将其放入标头中。
我想指出,我不使用 Laravel,我将发布的 api 使用的是 Laravel。
我的代码:
<?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);
?>
如果这对您的应用有意义,您可以为特定route
完全禁用CSRF token
。
检查文档并编辑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.