为什么在初始页面加载时在未定义的索引中返回此curl函数?

I'm using the function below to get the file size of images hosted in the Cloud. I need to display this size on my page. When the page is loaded the first time it returns a notice: Undefined index: content-length. When reloading the page, the notice disappears and the page is displayed fine. Why is this happening and what should I do about it?

$post_id = get_the_ID();
$post_thumbnail_id = get_post_thumbnail_id( $post_id );

//retrieve the size in bytes

$filePath = get_the_post_thumbnail_url($post_id, 'full');
  if (filter_var($filePath, FILTER_VALIDATE_URL)) {
    $ch = curl_init();
    $headers = [];
    curl_setopt($ch, CURLOPT_URL, $filePath);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    // this function is called by curl for each header received
    curl_setopt($ch, CURLOPT_HEADERFUNCTION,
    function($curl, $header) use (&$headers)
     {   
     $len = strlen($header);
     $header = explode(':', $header, 2);
     if (count($header) < 2) // ignore invalid headers
     return $len;

      $name = strtolower(trim($header[0]));
      if (!array_key_exists($name, $headers))
        $headers[$name] = [trim($header[1])];
      else
        $headers[$name][] = trim($header[1]);

        return $len;
       }  
    );
 $data = curl_exec($ch);
}

//convert the size in bytes to MB
$filemb = $headers['content-length']['0'] / 1000 / 1000;
$filemb = round($filemb,2);

// do my stuff

Amongst other things I took the advice of 04FS and Geoffrey and worked out a different approach. I created a Custom Field (filesize) in WooCommerce and at product creation, I set the field with the value returned by the function above.

So, I'm storing it in my own database. Because of that, the page speed will not be decreased. I think it will also be beneficial for bandwidth usage.

So it is only retrieved once.

@04FS and @Geoffrey.... thanks!

EDIT:

It appears not reliable after all. Sometimes it is set and sometimes it don't> Have to figure that one out.....