To perform requests via cURL the following steps are necessary:
•Install cURL session (curl-init)
•Send request (curl-setopt, curl_exec)
•Process response (read required data from the response, handle errors)
•Reset all cURL options (curl_reset) - the function re-initializes all options set on the given cURL handle to the default values. This is necessary when, e.g. the HTTP method is changed between subsequent requests.
•Finish cURL session (curl_close)
Scheme
// initialize cURL session
$curlHandle = curl_init()
// Set options for the request (target URL, Cookie file, etc.).
// The options differ depending on the type of requests.
curl_setopt($curlHandle, CURLOPT_URL,
'http://example.org/jobrouter/api/rest/v2/path/to/some/get/router')
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlHandle, CURLOPT_COOKIEJAR, 'path/to/cooke/file.cookie');
// Send request
$response = curl_exec($curlHandle);
// Read and check status code
$code = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
if ($code >= 400) {
echo "error during performance";
}
// Read further information from the response ...
// Finish cURL session
curl_close($curlHandle);
Options
cURL offers numerous options for the processing of requests. Some important options are listed in the following table
Option |
Meaning |
CURLOPT_URL |
URL of the resource to be used (e.g. http://example.org/jobrouter/api/rest/v2/application/sessions) |
CURLOPT_HTTPHEADER |
Data send in the header of the request (e.g. content type) |
CURLOPT_RETURNTRANSFER |
Set this option to true to be able to read the data from the response. |
CURLOPT_COOKIEFILE |
Name of a file containing cookie data |
CURLOPT_COOKIEJAR |
The name of a file, where all internal cookies are saved while closing the curl handle, e.g. after calling curl_close() |
CURLOPT_CUSTOMREQUEST |
Determines the request method. Permitted values are GET, POST, DELETE, etc. |
CURLOPT_POST |
Set this option to true, if it is a POST request. |
CURLOPT_POSTFIELDS |
Data transmitted in a POST request |
CURLOPT_HTTPAUTH |
States authentication method. If you use REST-API with Windows authentication, please chose the option CURLAUTH_NTLM and transfer an emtpy username-password pair in the option CURLOPT_USERPWD: curl_setopt($curlHandle, CURLOPT_HTTPAUTH, CURLAUTH_NTLM); curl_setopt($curlHandle, CURLOPT_USERPWD, ":"); The options has to be set for each request, though it is not necessary for anonymous authentications. |