K7

K7Blog

须知少年凌云志 曾许人间第一流.
proton
telegram

Implementing failover with a PHP file + Cloudflare!

Due to unforeseen circumstances, the server experienced a failure.

The timing is uncertain, as I may be sleeping or online and able to address it promptly.

So I created this simple tool, which requires the domain to be hosted on Cloudflare.

File: Click here to download

Specific tutorial:#

  1. Log in to Cloudflare and click on a domain. Find the Zone ID and copy it into the PHP file.

    // Zone ID
    $id = '';

  2. Below the Zone ID, there is a section called Get your API token. Click on it.

Click on "Create Token" and use the Edit Zone DNS template.

Select your domain in the Zone Resources row, and you can add whitelist for client IP address filtering.

After creating it, copy it into the PHP file.

// API token created, write it after Bearer
$Authorization = 'Authorization: Bearer ';

ps. There should be a space between Bearer and your token.

  1. After adding the two pieces of information, go to line 25.

    // Get DNS record ID list, when set to true, accessing the PHP URL will display the JSON format of the DNS record list.
    $get_dnsid = false;

Change false to true, and then upload it to the server for access.

Some JSON will appear, select the ID of the record you currently need for failover.

Fill it in:

// DNS record ID to be modified, $get_dnsid = true to get the record list, set dnsid and then set $get_dnsid to false
$dnsid = '';

Then change $get_dnsid = true; to $get_dnsid = false;!

  1. Modify other parameters

    // IP for ping check
    $pingip='baidu.com';

Change it to the address you want to ping.

$dnstype = 'A';
// Name
$dnsname = '';
// Modified IP
$dnscontent = '';
// Proxy
(bool)$dnsproxied = true;
// TTL
$dnsttl = 3600;

The above parameters are for modifying the IP of the record after a failure. The first one is the default A record.

The second one is the record content, the third one is the IP of the backup server, the fourth one is set to false to disable Cloudflare's CDN function.

By default, it is enabled. The fifth one is the TTL time, defaulting to one hour. You can change it to automatic by setting the value to 1.

  1. Ping address port

    if (pingDomain($pingip, 80) === -1) {

From line 43, the default port here is 80, but you can change it to another port.

After setting up everything above, just set the monitoring access URL.

Friendly reminder, the way this file pings is different from how you ping in the terminal on your computer.

This method is similar to port scanning. Setting the port to 80 or 443 can monitor web services.

Setting the port to 3306 can monitor MySQL, but the port must be open for the IP where the PHP file is deployed.

For example, if you open port 7777 in the control panel, but there is no process using that port, it will also be considered a failure.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.