Search code examples
phpcurlphp-curl

PHP: performing cURL --location --request for a RESTful API


I can't manage to perform quite simple requests to a RESTful API from a PHP script.

The following:

curl --location --request GET 'https://api.thatrestfulsite.com/api/utilities/listassets?apiKey=0123456789'

works nicely when invoked from the command line or within a bash script but I'm getting mad attempting to perform the same cURL request from a PHP script, i.e. attempting to translate the same cURL request using curl_setopt.

I mean, the following code:

$url = 'https://api.thatrestfulsite.com/api/utilities/listassets?apiKey=0123456789'
$ch = curl_init();
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURL_HTTP_VERSION_2TLS, true );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$output = curl_exec( $ch );
$http_status = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
echo "HTTP STATUS: $http_status\nREQ OUTPUT: $output";
curl_close( $ch );

...fails with an unexpected HTTP 301 (Moved Permanently) status.

I'm new to curl_setopt (tricky subject IMHO) and I'm not sure but I suppose the issue is that, although I have read the documentation, I've not been able to find a way to correctly translate the '--location' instruction.

Can you please tell me what I'm missing?

Thank you in advance.


Solution

  • curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);