@@ -199,8 +199,14 @@ public function request(string $method, string $url, array $options = []): Respo
199199 if (\extension_loaded ('zlib ' ) && !isset ($ options ['normalized_headers ' ]['accept-encoding ' ])) {
200200 $ options ['headers ' ][] = 'Accept-Encoding: gzip ' ; // Expose only one encoding, some servers mess up when more are provided
201201 }
202+ $ body = $ options ['body ' ];
202203
203- foreach ($ options ['headers ' ] as $ header ) {
204+ foreach ($ options ['headers ' ] as $ i => $ header ) {
205+ if (\is_string ($ body ) && '' !== $ body && 0 === stripos ($ header , 'Content-Length: ' )) {
206+ // Let curl handle Content-Length headers
207+ unset($ options ['headers ' ][$ i ]);
208+ continue ;
209+ }
204210 if (': ' === $ header [-2 ] && \strlen ($ header ) - 2 === strpos ($ header , ': ' )) {
205211 // curl requires a special syntax to send empty headers
206212 $ curlopts [\CURLOPT_HTTPHEADER ][] = substr_replace ($ header , '; ' , -2 );
@@ -216,7 +222,7 @@ public function request(string $method, string $url, array $options = []): Respo
216222 }
217223 }
218224
219- if (!\is_string ($ body = $ options [ ' body ' ] )) {
225+ if (!\is_string ($ body )) {
220226 if (\is_resource ($ body )) {
221227 $ curlopts [\CURLOPT_INFILE ] = $ body ;
222228 } else {
@@ -228,15 +234,16 @@ public function request(string $method, string $url, array $options = []): Respo
228234 }
229235
230236 if (isset ($ options ['normalized_headers ' ]['content-length ' ][0 ])) {
231- $ curlopts [\CURLOPT_INFILESIZE ] = substr ($ options ['normalized_headers ' ]['content-length ' ][0 ], \strlen ('Content-Length: ' ));
232- } elseif (!isset ($ options ['normalized_headers ' ]['transfer-encoding ' ])) {
233- $ curlopts [\CURLOPT_HTTPHEADER ][] = 'Transfer-Encoding: chunked ' ; // Enable chunked request bodies
237+ $ curlopts [\CURLOPT_INFILESIZE ] = (int ) substr ($ options ['normalized_headers ' ]['content-length ' ][0 ], \strlen ('Content-Length: ' ));
238+ }
239+ if (!isset ($ options ['normalized_headers ' ]['transfer-encoding ' ])) {
240+ $ curlopts [\CURLOPT_HTTPHEADER ][] = 'Transfer-Encoding: ' .(isset ($ curlopts [\CURLOPT_INFILESIZE ]) ? '' : ' chunked ' );
234241 }
235242
236243 if ('POST ' !== $ method ) {
237244 $ curlopts [\CURLOPT_UPLOAD ] = true ;
238245
239- if (!isset ($ options ['normalized_headers ' ]['content-type ' ])) {
246+ if (!isset ($ options ['normalized_headers ' ]['content-type ' ]) && 0 !== ( $ curlopts [\ CURLOPT_INFILESIZE ] ?? null ) ) {
240247 $ curlopts [\CURLOPT_HTTPHEADER ][] = 'Content-Type: application/x-www-form-urlencoded ' ;
241248 }
242249 }
0 commit comments