Home > database >  perform a curl request with PHP
perform a curl request with PHP

Time:09-17

I am trying to make a call to an API using curl (from the backend of my application directly). It is the first time I use it so I digged around to learn how to do it. The documentation say that this is the request:

curl --location -g --request POST '{{url}}/api/rest/issues/' \
--header 'Authorization: {{token}}' \
--header 'Content-Type: application/json' \
--data-raw '{
  "summary": "This is a test issue",
  "description": "This is a test description",
  "category": {
    "name": "General"
  },
  "project": {
    "name": "project1"
  }
}'

This should be the code if I execute it from the terminal (if I get it right). If I want to move execute it in a php script I have to convert this to something like:

<?php

$pars=array(
    'nome' => 'pippo',
    'cognome' => 'disney',
    'email' => '[email protected]',
);

//step1
$curlSES=curl_init(); 
//step2
curl_setopt($curlSES,CURLOPT_URL,"http://www.miosito.it");
curl_setopt($curlSES,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curlSES,CURLOPT_HEADER, false); 
curl_setopt($curlSES, CURLOPT_POST, true);
curl_setopt($curlSES, CURLOPT_POSTFIELDS,$pars);
curl_setopt($curlSES, CURLOPT_CONNECTTIMEOUT,10);
curl_setopt($curlSES, CURLOPT_TIMEOUT,30);
//step3
$result=curl_exec($curlSES);
//step4
curl_close($curlSES);
//step5
echo $result;
?>

that I will adapt to my needs. Is this correct? Is there another way to keep it as simple as the documented curl request?

CodePudding user response:

I would use an HTTP client like Guzzle.

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'http://www.miosito.it', [
    'form_params' => [
        'nome' => 'pippo',
        'cognome' => 'disney',
        'email' => '[email protected]',
    ]
]);

echo (string) $response->getBody();

CodePudding user response:

There are several ways to do curl. Your code seems okay, you can try out my code too.

$pars=array(
    'nome' => 'pippo',
    'cognome' => 'disney',
    'email' => '[email protected]',
);

If sometimes you need to send json encoded parameters then use below line.

// $post_json = json_encode($pars);

Curl code as per below

$apiURL = 'http://www.miosito.it';
$ch = @curl_init();
@curl_setopt($ch, CURLOPT_POST, true);
@curl_setopt($ch, CURLOPT_POSTFIELDS, $pars);
@curl_setopt($ch, CURLOPT_URL, $apiURL);
@curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
@curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = @curl_exec($ch);
$status_code = @curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_errors = curl_error($ch);
@curl_close($ch);
echo "<br>Curl Errors: " . $curl_errors;
echo "<br>Status code: " . $status_code;
echo "<br>Response: " . $response;

Please let me know if there you need something else.

  • Related