Bu örnek kimlik doğrulaması yapmıyor ama curl_setopt($curl_handle, CURLOPT_USERPWD, $username . ':' . $password); kodunu ekleyip o işlemide yapabilirsiniz.


Örnek


class Curl
{
/**
* Calls Rest API.
* @param array $data
* @return mixed
*/
public function call(array $data)
{
$payload = json_encode($data['payload']);

// Initialise the session
$curl = curl_init();

// Set API URL
curl_setopt($curl, CURLOPT_URL, $data['url']);
// Return the transfer as a string of the return value of curl_exec() instead of outputting it out directly
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Include the header in the output
curl_setopt($curl, CURLOPT_HEADER, true);
// Set request method
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $data['method']);

if ($data['method'] == 'POST') {
// Do a regular HTTP POST
curl_setopt($curl, CURLOPT_POST, true);
}

if ($data['method'] == 'POST' || $data['method'] == 'PUT') {
// The full data to post in a HTTP POST operation
curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($payload)
));
}

// Execute the request
$output = curl_exec($curl);
// Close curl resource to free up system resources
curl_close($curl);

// If connection failed
if (! $output) {
return 'Curl connection failure.';
}

// Output the profile information, includes the header
return $output;
}
}

Server tarafı


Aşağıdakine benzer bir kod ile curl ile gönderilen isteği kontrol edebilirsiniz.


if (! isset($_SERVER) || ! isset($_POST))
{
exit('Bad request');
}

if (! isset($_SERVER['PHP_AUTH_USER']) || ! isset($_SERVER['PHP_AUTH_USER']))
{
exit('Authentication details are missing');
}

$uid = $_SERVER['PHP_AUTH_USER'];
$pwd = $_SERVER['PHP_AUTH_PW'];

if ($uid != 'admin' || $pwd != 'admin')
{
exit('Invalid authentication credentials');
}

echo json_encode($_POST);