call drupal api with Apache HTTP auth (basic)
<?php
// API endpoint
$apiUrl = 'http://localhost/cms/web/api/articles';
// HTTP Basic Authentication credentials
$username = 'xxxx';
$password = 'yyyyyy';
// Initialize cURL session
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
// Execute cURL request
$response = curl_exec($ch);
// Check for cURL errors
if (curl_errno($ch)) {
http_response_code(500);
echo json_encode(['error' => 'cURL Error: ' . curl_error($ch)]);
curl_close($ch);
exit;
}
// Get HTTP status code
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close cURL session
curl_close($ch);
// Check HTTP response code
if ($httpCode !== 200) {
http_response_code($httpCode);
echo json_encode(['error' => "HTTP Error: $httpCode"]);
exit;
}
// Return raw JSON response
header('Content-Type: application/json');
echo $response;
留言
發佈留言