Connect to Cloudflare API
To begin managing DNS records via the Cloudflare API using PHP, you need to establish a connection. This involves making HTTP requests to their API endpoints.
$apiToken = 'YOUR_API_TOKEN';
$endpoint = 'https://api.cloudflare.com/client/v4/';
$headers = [
'Authorization: Bearer ' . $apiToken,
'Content-Type: application/json'
];
Fetch DNS Records
To manage existing DNS records, you first need to fetch them. Use the GET
request to retrieve records.
$zoneId = 'YOUR_ZONE_ID';
$url = $endpoint . 'zones/' . $zoneId . '/dns_records';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$dnsRecords = json_decode($response, true);
Create a DNS Record
To add a new DNS record to your domain, you can perform a POST
request.
$record = [
'type' => 'A',
'name' => 'subdomain.example.com',
'content' => '192.0.2.1',
'ttl' => 120,
'proxied' => false
];
$url = $endpoint . 'zones/' . $zoneId . '/dns_records';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($record));
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
Update an Existing DNS Record
If you need to update an existing DNS record, identify it by its recordId
, then perform a PUT
request.
$recordId = 'YOUR_RECORD_ID';
$updatedRecord = [
'type' => 'A',
'name' => 'subdomain.example.com',
'content' => '203.0.113.5',
'ttl' => 120,
'proxied' => false
];
$url = $endpoint . 'zones/' . $zoneId . '/dns_records/' . $recordId;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($updatedRecord));
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
Delete a DNS Record
To delete a DNS record, use the DELETE
HTTP method and the specific recordId
.
$recordId = 'YOUR_RECORD_ID';
$url = $endpoint . 'zones/' . $zoneId . '/dns_records/' . $recordId;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
$response = curl_exec($ch);
curl_close($ch);
$result = json_decode($response, true);
Handle API Errors
While interacting with the Cloudflare API, handle potential errors gracefully by checking the response codes and messages.
if ($result['success']) {
echo 'Operation was successful!';
} else {
echo 'Error: ' . $result['errors'][0]['message'];
}
Security Considerations
- Store API tokens securely using environment variables or a secure vault, to avoid hardcoding them directly into your scripts.
- Handle HTTP responses carefully to avoid exposing sensitive information in the event of an error.