Code Monkey home page Code Monkey logo

cloudflare-php's Introduction

Cloudflare SDK (v4 API Binding for PHP 7)

Build Status

Installation

The recommended way to install this package is via the Packagist Dependency Manager (cloudflare/sdk). You can get specific usage examples on the Cloudflare Knowledge Base under: Cloudflare PHP API Binding

Cloudflare API version 4

The Cloudflare API can be found here. Each API call is provided via a similarly named function within various classes in the Cloudflare\API\Endpoints namespace:

Note that this repository is currently under development, additional classes and endpoints being actively added.

Getting Started

$key     = new Cloudflare\API\Auth\APIKey('[email protected]', 'apiKey');
$adapter = new Cloudflare\API\Adapter\Guzzle($key);
$user    = new Cloudflare\API\Endpoints\User($adapter);

echo $user->getUserID();

Contributions

We welcome community contribution to this repository. CONTRIBUTING.md will help you start contributing.

Licensing

Licensed under the 3-clause BSD license. See the LICENSE file for details.

cloudflare-php's People

Contributors

anthonysterling avatar axelabhay avatar beltofte avatar benedict-erwin avatar bnalonezi avatar bubbleupdotnet avatar czpechy avatar darinrandal avatar easelify avatar exportsmedia avatar hans00 avatar hemeraone avatar icyapril avatar indeed-a-genius avatar jacobbednarz avatar jorgenphi avatar kamilsolarczyk avatar kanasite avatar kleisauke avatar legacybetadev avatar levidurfee avatar limenet avatar owenvoke avatar pauladams8 avatar pezhvak avatar phily245 avatar thellimist avatar tylervigario avatar typhonius avatar zaherg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cloudflare-php's Issues

API token support

Hi guys

Will support for the new API tokens be added soon?

Thanks!

Invalid request headers

According to my sentry logs about 2 weeks ago I started getting this error:

"code":6003,"message":"Invalid request headers",

The error happens on this code:

$zones = new \Cloudflare\API\Endpoints\Zones($this->adapter);
$zones->getZoneID($domain);

The code was working fine for half a year before that, I have the latest version of this package and php 7.2.8.

I can see the full request URL in my error log, when I try that URL in my desktop REST client together with the X-Auth-Email and X-Auth-Key headers then it works fine, so I am not sure what the problem might be?

Add a repository description

Currently the GitHub repository description is empty and just shows No description, website, or topics provided.

Page rule 'Origin Cache Control' directive

What id must I use to specify 'Origin Cache Control' in page rule actions?
I couldn't found it anywhere.
For 'Always Online' (example) id is 'always_online', but I've tried id 'origin_cache_control' and doesn't worked.

Documentation

Hello,

Would be nice to have some documentation with examples of some complex methods, like page rules, DNS records, etc.

CustomHostnames lack ability to set the "custom_metadata" parameter

See https://developers.cloudflare.com/ssl/ssl-for-saas/hostname-specific/custom-metadata/ for reference.

Here is a cURL example:

$ curl -sXPATCH "https://api.cloudflare.com/client/v4/zones/{zone_id}/custom_hostnames/{hostname_id}"\
     -H "X-Auth-Email: {email}" -H "X-Auth-Key: {key}"\
     -H "Content-Type: application/json"\
     -d '{"ssl":{"method":"http","type":"dv"},"custom_metadata":{"customer_id":"12345","redirect_to_https": true}}'

Note that the API documentation doesn't actually show that parameter: https://api.cloudflare.com/#custom-hostname-for-a-zone-create-custom-hostname

Purge Cache file

If we use "cachePurge" with id and url of the image, and that it does not exist, it blocks the execution of the code that follows, it's a pity. Solutions ? Thank you

Unable to UpdateRecord

I'am unable to update record. Specifically to disable Cloudflare proxy. Code:

$key = new \Cloudflare\API\Auth\APIKey('[email protected]', '123...');
$adapter = new Cloudflare\API\Adapter\Guzzle($key);
$zones = new \Cloudflare\API\Endpoints\Zones($adapter);
$zoneID = $zones->getZoneID("domain.tld");

$details = [
    'proxied' => false,
];

$recordID = '123...';

$dns = new \Cloudflare\API\Endpoints\DNS($adapter);
$output= $dns->updateRecordDetails($zoneID, '$recordID', $details);

Output:

response: {"success":false,"errors":[{"code":1004,"message":"DNS Validation Error","error_chain":

CustomHostnames lack ability to set the "custom_origin_server" parameter

Both the documentation and the API are missing the "custom_origin_server" parameter.

POST /client/v4/zones/REDACTED/custom_hostnames
Accept: */*
Accept-Encoding: gzip, deflate
X-Auth-Email: REDACTED
X-Auth-Key: REDACTED
Content-Type: application/json
Accept-Language: en-ca
{
  "custom_origin_server": "REDACTED",
  "hostname": "REDACTED",
  "ssl": {
    "method": "http",
    "type": "dv"
  }
}
{
    "result": {
        "id": "REDACTED",
        "hostname": "REDACTED",
        "ssl": {
            "id": "REDACTED",
            "type": "dv",
            "method": "http",
            "status": "initializing"
        },
        "custom_origin_server": "REDACTED"
    },
    "success": true
}

screen shot 2018-06-26 at 3 26 29 pm

AccessRules return

I'm writing a AccessRules manager for our application. When creating an item, it just returns true instead of the ID for storage.

Would it be possible to get the id on return instead of having to make a second API to call to search for it.

Support for Stream API

Hi,

I was searching for Stream API support in the library but did not found any.

If there is already API method in the library for the Cloudflare Stream then please let me know.

Thank You

Cache purge Error 1014

My request :
$zones->cachePurge($zoneID, [$url], []);

But the response contains this error, what's the problem?

{"success":false,"errors":[{"code":1014,"message":""files", "tags", or "hosts" must be an array"}],"messages":[]," (truncated...)

400 Bad Request trying simple test script.

Hi folks, I'm just getting started using your sdk. I attempted to write a small test script based on simple example. When I attempt to run it I get back a lot of error messages of which I have pasted below.

Error received:

PHP Fatal error: Uncaught GuzzleHttp\Exception\ClientException: Client error: GET https://api.cloudflare.com/client/v4/user resulted in a 400 Bad Request response:
{"success":false,"errors":[{"code":6003,"message":"Invalid request headers","error_chain":[{"code":6103,"message":"Inval (truncated...)
in /home/dev/repos/cwpdev/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113

Stack trace:
#0 /home/dev/repos/cwpdev/vendor/guzzlehttp/guzzle/src/Middleware.php(65): GuzzleHttp\Exception\RequestException::create()
#1 /home/dev/repos/cwpdev/vendor/guzzlehttp/promises/src/Promise.php(203): GuzzleHttp\Middleware::GuzzleHttp{closure}()
#2 /home/dev/repos/cwpdev/vendor/guzzlehttp/promises/src/Promise.php(156): GuzzleHttp\Promise\Promise::callHandler()
#3 /home/dev/repos/cwpdev/vendor/guzzlehttp/promises/src/TaskQueue.php(47): GuzzleHttp\Promise\Promise::GuzzleHttp\Promise{closure}()
#4 /home/dev/repos/cwpdev/vendor/guzzlehttp/promises/src/Promise.php(246): GuzzleHttp\Promise\TaskQueue->run()
#5 /home/dev/repos/cwpdev/ in /home/dev/repos/cwpdev/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php on line 113

This is my code:
`<?php

require_once('vendor/autoload.php');

$key = new \Cloudflare\API\Auth\APIKey('[email protected]', 'xxxxx');
$adapter = new Cloudflare\API\Adapter\Guzzle($key);
$user = new \Cloudflare\API\Endpoints\User($adapter);

echo 'Your user ID is: ' . $user->getUserID() . PHP_EOL;
`
I have verified that I am using the correct email address and Api key for my account.
Any direction would be most appreciated.

Creating New Zone Example, Wiki & Hosting Partner SDK

Greetings,
I would be really awesome to have a documentation that shows how to add zones, delete zones and more with the list of all the possible functions and API available in the SDK.

I have gone through https://support.cloudflare.com/hc/en-us/articles/115001661191-Cloudflare-PHP-API-Binding but it doesn't seem to have an example of creating a new zone.

Also, what if we want a PHP SDK for hosting partners to add domains directly via the hosting partner API in the user's account.

Thanks!

Get RecordID from ->addRecord

Hello.

I am having a bit of a problem getting a response from $dns->addRecord.
I'm creating an SRV record with it, but I need the record ID so I can store it for later use.

I've been unable to find a solution myself.

Here's the code I currently have:

$dns->addRecord($cf_zone, 'SRV', '', '', 0, 0, false, [
    		    'weight' => 5,
    		    'priority' => 0,
    	    	    'proto' => '_tcp',
                    'port' => $srvInfo['port'],
    	      	    'target' => $srvFQDN,
    	    	    'service' => '_cust',
                'name' => $data['domain'],
            ])```

code: 0, message: Failed to get an object from container when using updateRecordDetails

Here is a snippet of code that I have written that uses the updateRecordDetails() method:

$details = array(
    'type' => $type,
    'name' => $zone->name,
    'content' => $content,
    'ttl' => $ttl,
    'proxied' => $proxied
);
$response = $this->dns->updateRecordDetails($zone->id, $record->id, $details);

Here are the values for the $details copied from the debugger window in PHPStorm (which are now stored in $options->json within Guzzles transfer method)

"{\"type\":\"CNAME\",\"name\":\"base-domain.com\",\"content\":\"base-domain.wpengine.com\",\"ttl\":1,\"proxied\":true}"

And here is the full error I get

Server error: `PUT https://api.cloudflare.com/client/v4/zones/9f10dd80a2d804cf230f7f(redacted)/dns_records/d83b317a7ea57fdd27810c(redacted)` resulted in a `500 Internal Server Error` response:
{"success":false,"errors":[{"code":0,"message":"Failed to get an object from container."}],"messages":[],"result":null}

 C:\laragon\www\NS\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php:113
 C:\laragon\www\NS\vendor\guzzlehttp\guzzle\src\Middleware.php:65
 C:\laragon\www\NS\vendor\guzzlehttp\promises\src\Promise.php:203
 C:\laragon\www\NS\vendor\guzzlehttp\promises\src\Promise.php:156
 C:\laragon\www\NS\vendor\guzzlehttp\promises\src\TaskQueue.php:47
 C:\laragon\www\NS\vendor\guzzlehttp\promises\src\Promise.php:246
 C:\laragon\www\NS\vendor\guzzlehttp\promises\src\Promise.php:223
 C:\laragon\www\NS\vendor\guzzlehttp\promises\src\Promise.php:267
 C:\laragon\www\NS\vendor\guzzlehttp\promises\src\Promise.php:225
 C:\laragon\www\NS\vendor\guzzlehttp\promises\src\Promise.php:62
 C:\laragon\www\NS\vendor\guzzlehttp\guzzle\src\Client.php:131
 C:\laragon\www\NS\vendor\guzzlehttp\guzzle\src\Client.php:89
 C:\laragon\www\NS\vendor\cloudflare\sdk\src\Adapter\Guzzle.php:74
 C:\laragon\www\NS\vendor\cloudflare\sdk\src\Endpoints\DNS.php:108
 C:\laragon\www\NS\src\api\CloudflareWpengine.php:112
 C:\laragon\www\NS\tests\Unit\CloudFlareWPEngineTest.php:26

I've tried debugging this but wasn't able to come to a conclusion as to what's causing the problem. This works find when using Postman to send the request though so I'm currently stumped.

Creating a SRV record does not work

Ill be submitting a PR linking to this issue, but the SDK is missing code to create and update SRV records and the fix seems simple enough.

In addition, if you change items like proto with a bad value 'tcp' instead of '_tcp' it the API cannot handle the error message and shows %s:

Caught exception: Client error: POST https://api.cloudflare.com/client/v4/zones/xxxxxxx/dns_records resulted in a 400 Bad Request response:
{"success":false,"errors":[{"code":1004,"message":"DNS Validation Error","error_chain":[{"code":9150,"message":"%s"}]}],"messages":[],"result":null}

Support for Workers KV Store

API endpoints of Workers, particularly the Workers KV store, are not presently covered by the SDK.

PHP backends should be able to read from and write to the Workers KV persistent key-value storage. Ideally, bulk writes should be also supported.

Can not create MX record: priority parameter missing

cloudflare/sdk version: 1.0.8 installed via composer

Code:
$key = new \Cloudflare\API\Auth\APIKey($myEmail, $myKey);
$adapter = new Cloudflare\API\Adapter\Guzzle($key);
$zoneID = $zones->getZoneID($myDomain);
$dns = new \Cloudflare\API\Endpoints\DNS($adapter);
$dns->addRecord($zoneID, "MX", 'testmx', 'mail.mydomain.com', 1, false);

Thrown exception:
Uncaught GuzzleHttp\Exception\ClientException: Client error: POST https://api.cloudflare.com/client/v4/zones/my_zone_id/dns_records resulted in a 400 Bad Request response:
{"success":false,"errors":[{"code":1004,"message":"DNS Validation Error","error_chain":[{"code":9008,"message":"Invalid (truncated...)
in /var/www/tests/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:113

Then I've tried to create TXT record and then update it to MX:
$dns->addRecord($zoneID, "TXT", 'testmx', 'mail.mydomain.com', 1, false);
// ... get record id ...
$dns->updateRecordDetails($zoneID, $recordId, [
'type' => 'MX',
'name' => 'testmx',
'content' => 'mail.mydomain.com',
]);

Thrown exception was like after first try.

And then I've tried to add integer parameter 'priority' to options array, and oh, miracle, it works!
But this parameter is not described at API v4 Documentation.
// ... get record id ...
$dns->updateRecordDetails($zoneID, $recordId, [
'type' => 'MX',
'name' => 'testmx',
'content' => 'mail.mydomain.com',
'priority' => 5,
]);

In that time simple cURL POST request to create DNS-record works to:

$ch = curl_init('https://api.cloudflare.com/client/v4/zones/' . $zoneID . '/dns_records')
$data = json_encode([
'type' => 'MX',
'name' => 'curlmx',
'content' => 'mail.mydomain.com',
'ttl' => 1,
'proxied' => false,
'priority' => 5,
]);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt(
$ch, CURLOPT_HTTPHEADER,
[
'X-Auth-Key: ' . $myKey,
'X-Auth-Email: ' . $myEmail,
'Content-Type: application/json',
]
);
$result = curl_exec($ch);
print_r(json_decode($result, true));

Success result:
Array
(
[result] => Array
(
[id] => .............
[type] => MX
[name] => curlmx.domain.com
[content] => mail.mydomain.com
[proxiable] =>
[proxied] =>
[ttl] => 1
[priority] => 5
[locked] =>
[zone_id] => ..............
[zone_name] => domain.com
[modified_on] => 2017-11-27T11:26:32.936498Z
[created_on] => 2017-11-27T11:26:32.936498Z
[meta] => Array
(
[auto_added] =>
[managed_by_apps] =>
)

    )

[success] => 1
[errors] => Array
    (
    )

[messages] => Array
    (
    )

)

Is this library still maintained?

I would like to use this library for a project, but there are so many problems with it currently that it is easier to just communicate with the Cloudflare API manually.

At the moment, this library lacks many features of the Cloudflare API and does not seem to be actively maintained.

Some issues that need addressing:

  • PHP syntax issues (see PR #114)
  • API token support (see PR #101)
  • Inconsistent return types
  • Inconsistent code style

It would also be good to see some work on integrating other API endpoints, I submitted a PR a while back and there are some others that could be merged.

Strict PHP Return types not correct for DNS getRecordID()

In DNS.php, the function getRecordID is declared with return type string, but returns false.

Can we change this to either empty string, or throw and exception instead of having conflicting return types?

    public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
    {
        $records = $this->listRecords($zoneID, $type, $name);
        if (isset($records->result[0]->id)) {
            return $records->result[0]->id;
        }
        return false;
    }

could change final lines to:

            return $records->result[0]->id ?? : '';

Issues w/ creating Firewall rules

I keep getting a strange issue with this library and trying to create firewall rules. Some of the time, the code below works, but most of the time, I get a 400 bad request error with code "10202" filter at index 0.

I don't see where there are any issues with my expression and don't understand why this sometimes works but I get an error also with the same exact code being run.

require __DIR__ . '/vendor/autoload.php';

$key     = new Cloudflare\API\Auth\APIKey('***', '***');
$adapter = new Cloudflare\API\Adapter\Guzzle($key);
$zones   = new Cloudflare\API\Endpoints\Zones($adapter);
$fw      = new Cloudflare\API\Endpoints\Firewall($adapter);

$sites = $zones->listZones('', '', 1, 300, '', '', 'all');

foreach ( $sites->result as $site ) :
	$site_id = $site->id;
	$site_name = $site->name;

	$expression = 'ip.geoip.country ne {"US" "MX" "CA"}';
	$config = new Cloudflare\API\Configurations\FirewallRuleOptions();
	$config->setActionBlock();
	$result = $fw->createFirewallRule(
        $site_id,
        $expression,
        $config,
        'Country Block'
    );

endforeach;

Export DNS records

When I perform

GET zones/:zone_identifier/dns_records/export

the result is empty. How can I export the DNS zone for a backup.

How to print the entire exception

I can't read the most important part of the exception because it gets truncated.
How can i force it to not truncate them?
I'm using this lib from cli via composer.

Client error: `PUT https://api.cloudflare.com/client/v4/zones/-/dns_records/-` resulted in a `400 Bad Request` response:
{"success":false,"errors":[{"code":1004,"message":"DNS Validation Error","error_chain":[{"code":9020,"message":"Invalid  (truncated...)

Adding MX records with priority 0 fails

I came across this while setting up MX records for Microsoft 365. Their suggested setting for the priority of their MX record is 0.

When I tried to update my DNS record using a priority 0, I received the following error:

{"result":null,"success":false,"errors":[{"code":1004,"message":"DNS Validation Error","error_chain":[{"code":9100,"message":"priority is a required field."}]}],"messages":[]}

Any other priority works, and I've traced it back to a issue with the addRecord function.

I've created a fix for it. Hopefully this is helpful.

#135

Analytics Datas

Hello,

Can I get analytics data via API? If the answer is yes, can you show me a small example of how I can do it?

Thank you

Purge cache is not working

Hi, the method to purge the cache is not working since a few weeks. I'm currently using the method
Zones::cachePurge() but it doesn't seem to work properly.
But checking the Cloudflare API v4 and the code, I notice that the Cloudflare API requires a POST method but this library is using DELETE. So I'm proposing a fix.

Changing guzzle adapter options

I've come across this issue while testing your api. Guzzle throws an exception complaining there's no ca file on a windows box. For those OS' without a default known ca file, see guzzle verify, it is not possible to set a default ca-file without altering the php.ini or PATH environment. To solve this issue,

Either

//to set options to the guzzle client
public getClient() { return $this->client; }

Or

public function __construct(Auth $auth, string $baseURI = null, $guzzleConfig = [])
{
    if ($baseURI === null) {
        $baseURI = 'https://api.cloudflare.com/client/v4/';
    }

    $headers = $auth->getHeaders();

    $config = [
        'base_uri' => $baseURI,
        'headers' => $headers,
        'Accept' => 'application/json'
    ] + $guzzleConfig;

    $this->client = new Client($config);
}    

Or

public function __construct(Auth $auth, string $baseURI = null, $caFile = false)
{
    if ($baseURI === null) {
        $baseURI = 'https://api.cloudflare.com/client/v4/';
    }

    $headers = $auth->getHeaders();

    $config = [
        'base_uri' => $baseURI,
        'headers' => $headers,
        'Accept' => 'application/json'
    ];

    if ($caFile !== false) $config['verify'] = $caFile;

    $this->client = new Client($config);
} 

can be done.

invalid parameters for forwarding url

Invalid parameters for forwarding_url in page rules.

fix commit

public function setForwardingURL(int $statusCode, string $forwardingUrl)
    {
        if (!in_array($statusCode, ['301', '302'])) {
            throw new ConfigurationsException('Status Codes can only be 301 or 302.');
        }
        $this->addConfigurationOption('forwarding_url', [
            'value' => [
                'status_code' => $statusCode,
                'url' => $forwardingUrl,
            ]
        ]);
    }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.