Sending a GET request with a request body with PHP cURL

Published: April 16, 2020

Tags:

Some APIs require GET requests with request bodies. I was looking into how to do that today and struggling with Google. Eventually I found this answer on StackOverflow.

PHP code is as follows:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://maxchadwick.xyz');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_POSTFIELDS, 'THIS IS THE REQUEST BODY');

curl_exec($ch);

Some of the other answers on the StackOverflow thread are incorrect…If you remove CURLOPT_CUSTOMREQUEST it will NOT default to a GET if you use CURLOPT_POSTFIELDS but will instead be a POST.

I used Burp Suite to intercept the request and confirm the above was doing a GET with a request body.

Screenshot showing request intercepted in Burp Suite

Max Chadwick Hi, I'm Max!

I'm a software developer who mainly works in PHP, but also dabbles in Ruby and Go. Technical topics that interest me are monitoring, security and performance.

During the day I solve challenging technical problems at Something Digital where I mainly work with the Magento platform. I also blog about tech, work on open source and hunt for bugs.

If you'd like to get in touch with me the best way is on Twitter.