首页 > 解决方案 > curl works in CLI, but not in PHP

问题描述

curl works in CLI, but not in PHP.

The following command works in the command line:

curl -X POST --header "Content-Type: application/json" --header "Authorization: Basic [token]" https://api.example.com/v1/token -v -k

* About to connect() to api.example.com port 443 (#0)
..

> POST /v1/token HTTP/1.1
> User-Agent: curl/7.29.0
> Host: api.example.com
> Accept: */*
> Content-Type: application/json
> Authorization: Basic [token]
> 
< HTTP/1.1 200 OK
< Date: Fri, 30 Apr 2021 02:52:24 GMT
< Content-Type: application/json; charset=utf-8
< Content-Length: 325
< Connection: keep-alive
< X-Powered-By: Express
< ETag: W/"145-rseWkvhNxxhur+O7jUfApznKiww"
< 
* Connection #0 to host api.example.com left intact
{"accesstoken":"token","type":"Bearer","expired":"20210501115224"}

And in PHP using the code below:

test.php

<?php
$host = 'https://api.example.com/v1/token';

$headers = array(
    'Content-Type: application/json',
    'Authorization: Basic [token]'
);

$oCurl = curl_init();
curl_setopt($oCurl, CURLOPT_URL, $host);
curl_setopt($oCurl, CURLOPT_POST, true);
curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($oCurl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($oCurl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($oCurl, CURLOPT_VERBOSE, true);

$response = curl_exec($oCurl);

curl_close($oCurl);

$ php test.php

* About to connect() to api.example.com port 443 (#0)
..

> POST /v1/token HTTP/1.1
Host: api.example.com
Accept: */*
Content-Type: application/json
Authorization: Basic [token]
Content-Length: -1
Expect: 100-continue

< HTTP/1.1 100 Continue
< HTTP/1.1 400 Bad Request
< Server: nginx
< Date: Fri, 30 Apr 2021 04:22:08 GMT
< Content-Type: text/html
< Content-Length: 150
< Connection: close
< 
* Closing connection 0

The result is a HTTP Status code 400 Bad Request. Is there something I'm doing wrong?

Please Help. Any ideas would be greatly appreciated.

标签: phpcurlphp-curl

解决方案


Content-Length: -1 looks weird.

Seems like cURL is adding that automatically, because your request does not contain a POST body - but then it should be set to 0, if it gets set at all.

Add 'Content-Length: 0' to your $headers array, so that cURL won’t add the header itself with the wrong value.


推荐阅读