AnsweredAssumed Answered

Any way to predict the value layout of curl_exec()?

Question asked by Lee Newton on Aug 6, 2019
Latest reply on Aug 6, 2019 by Jay Savage

Hi, hope all is well.
I run a successful curl request as you can see below:

$ch = curl_init()
$headers = ['Authorization: Bearer ' . my_token_here];
$url = "https://my.test.instructure.com/api/v1/accounts/1/courses?per_page=100";
   curl_setopt_array($ch, [
      CURLOPT_RETURNTRANSFER => TRUE,
      CURLINFO_HEADER_OUT => TRUE,
      CURLOPT_URL => $url,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_SSL_VERIFYPEER => TRUE,
      CURLOPT_HTTPHEADER => $headers,
      CURLOPT_CUSTOMREQUEST => 'GET',
      CURLOPT_HEADER => TRUE,
      CURLOPT_RETURNTRANSFER, TRUE
   ]);

Then I try to get more data from it:

$resp = curl_exec($ch);
$header_size = curl_getinfo( $ch, CURLINFO_HEADER_SIZE );
$header = substr( $resp, 0, $header_size );
$body = substr( $resp, $header_size );
...

And extract data from that:

$explData = explode("\n",$resp);


The data I get from $explData, looks like this:

array (
   0 => 'HTTP/1.1 200 OK',
   1 => 'Date: Tue, 06 Aug 2019 13:52:47 GMT',
   2 => 'Content-Type: application/json; charset=utf-8',
   ... => ...,
   13 => 'X-Permitted-Cross-Domain-Policies: none',
   14 => 'X-XSS-Protection: 1; mode=block',
   15 => 'X-Canvas-User-Id: 135180000000000804',
   16 => 'Link: <https://my.test.instructure.com/api/v1/accounts/1/courses?page=1&per_page=100>; rel="current",  <https://my.test.instructure.com/api/v1/accounts/1/courses?page=2&per_page=100>; rel="next",<https://my.test.instructure.com/api/v1/accounts/1/courses?page=1&per_page=100>; rel="first",<https://my.test.instructure.com/api/v1/accounts/1/courses?page=213&per_page=100>; rel="last" ',
   ...
)

The array value that matters is #16, the Link section, since I need to be able to get the pagination links. However, until just today, the dataset had this value set at position 15 in the array.
So when I wanted to get the links, I was able to simply do:

$links = $explData[15];

However, that changed to 16, and my program stopped functioning as a result.
I can make a program that scans $explData for an array that starts with "Link:" and go from there, but I want to know if that is necessary. Or is it possible to consistently know where the Link section would always be?

Outcomes