samir chauhan
samir chauhan

Reputation: 1543

Converting Curl command to PHP not working

I have curl command working through terminal and when I converts that command in PHP, it is giving me an error.

Here is Curl command from terminal:

[root@localhost ~]# curl -XPOST -v http://localhost:5636/api/1/event/AVyWHzgsJ-3JxxYdx60x/archive
* About to connect() to localhost port 5636 (#0)
*   Trying ::1...
* Connected to localhost (::1) port 5636 (#0)
> POST /api/1/event/AVyWHzgsJ-3JxxYdx60x/archive HTTP/1.1
> User-Agent: curl/7.29.0
> Host: localhost:5636
> Accept: */*
> 
< HTTP/1.1 200 OK
< Content-Type: application/json
< X-Evebox-Git-Revision: 8ef8639
< X-Evebox-Session-Id: IUi21/bP7TkbJ11jpYcihe1w/S41vyAbP1L1qBIJKJiL8E3440J3imOSGxKYO9j5ffqAPyv2Q3tCXqUQxhIqnw
< Date: Wed, 05 Jul 2017 06:34:31 GMT
< Content-Length: 14
< 
* Connection #0 to host localhost left intact
{"status":200}[root@localhost ~]#

Here is the curl command in PHP:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "http://localhost:5636/api/1/event/AVyWHzgsJ-3JxxYdx60x/archive");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

$result = curl_exec($ch);
if (curl_errno($ch)) {
  echo 'Error:' . curl_error($ch);
}
curl_close ($ch);

This is response: 400 Bad Request

Here is the Verbose Output:

Verbose information:
* About to connect() to localhost port 5636 (#6)
*   Trying ::1...
* Connected to localhost (::1) port 5636 (#6)
> POST /api/1/event/AVyWHzgsJ-3JxxYdx60x/archive HTTP/1.1
Host: localhost:5636
Accept: */*
Content-Length: -1
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

< HTTP/1.1 400 Bad Request
< Content-Type: text/plain; charset=utf-8
< Connection: close
< 
* Closing connection 6

400 Bad Request

Upvotes: 0

Views: 226

Answers (3)

Gaurav Garg
Gaurav Garg

Reputation: 137

Add this line, as your API will respond only to POST requests, and 400 error means you are asking API with Non-POST method,

Add this line and it should work ...

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");

Upvotes: 0

Roshni joshi
Roshni joshi

Reputation: 88

Use

curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)');

or using urlencode($url);

Upvotes: 0

Sudheesh Singanamalla
Sudheesh Singanamalla

Reputation: 2297

Using the Requests library you could convert that cURL query as

include('vendor/rmccue/requests/library/Requests.php');
Requests::register_autoloader();
$headers = array();
$response = Requests::post('http://localhost:5636/api/1/event/AVyWHzgsJ-3JxxYdx60x/archive', $headers);

Upvotes: 0

Related Questions