cloudflare / cloudflare-php Goto Github PK
View Code? Open in Web Editor NEWPHP library for the Cloudflare v4 API
License: BSD 3-Clause "New" or "Revised" License
PHP library for the Cloudflare v4 API
License: BSD 3-Clause "New" or "Revised" License
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;
78436a6e227b5c72b1fdc8784afe7a7e
As this endpoint is currently missing, I am intent to implement this endpoint and will create a PR once it's ready for review.
Invalid parameters for forwarding_url in page rules.
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,
]
]);
}
see
cloudflare-php/src/Endpoints/Zones.php
Line 161 in 63be6cf
this ends up passing 'tag' => null if no tags (or files I assume) are passed. This is in violation of the API contract which is now being enforced
https://github.com/cloudflare/cloudflare-php/blob/master/src/Adapter/Adapter.php#L26
interface Adapter
{
/**
* Adapter constructor.
*
* @param Auth $auth
* @param string $baseURI
*/
public function __construct(Auth $auth, string $baseURI);
An interface should not enforce any constructor as this is an implementation-issue
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:
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.
Here's the commit for when @elithrar added to cloudflare-go: cloudflare/cloudflare-go@86147da.
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
(
)
)
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...)
Please update guzzlehttp/guzzle to version 7.
Thank you in advance.
Currently the GitHub repository description is empty and just shows No description, website, or topics provided.
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":
Very similar to the method getZoneID for the Zones endpoint
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?
I guess the friendsofphp/php-cs-fixer dependency is only used for local development. Consider moving the dependency to 'require-dev'.
The packages has quite a few dependencies that pulled in. See https://packagist.org/packages/friendsofphp/php-cs-fixer
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
}
To extract information from DNS::addRecord()... Easy fix.
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.
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.
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.
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}
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...)
It's 'ssl' not 'smart_errors'
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
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.
https://api.cloudflare.com/#zone-settings-change-security-level-setting
The only related fields I can find for this are related to Page Rules, there does not appear to be an option to change the overall zone security level.
Hi guys
Will support for the new API tokens be added soon?
Thanks!
Is there a method that implements the functionality of this cloudflare api endpoint? I found a method deleteHostname but that's for custom hostnames that are routed via CNAME.
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.
Hello there,
I was looking for this endpoint #zone-settings-change-browser-cache-ttl-setting which supposed be in ZoneSettings class
is it really missing?
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
Hello,
Would be nice to have some documentation with examples of some complex methods, like page rules, DNS records, etc.
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
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
Hello.
I noticed phpmd
is listed in require-dev
but doesn't appear to be used, should something be implemented or is this safe to remove?
Line 12 in 49ed1c9
Thanks,
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 ?? : '';
what if using httplug (https://github.com/php-http/httplug) instead of using guzzle directly?
Hi,
How I can install without Composer?
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'],
])```
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.
It looks like the latest update has not been tagged
So this: https://github.com/cloudflare/cloudflare-php/blob/master/src/Endpoints/Zones.php
is out of date on this: https://packagist.org/packages/cloudflare/sdk#1.1.4
Meaning that features are missing
Hello,
The wrong priority data type must be the interger
cloudflare-php/src/Endpoints/DNS.php
Line 41 in 63be6cf
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.
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!
https://api.cloudflare.com/#zone-settings-change-automatic-https-rewrites-setting
I can't seem to find this anywhere... is this added yet?
Thanks!
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.
Deprecated: Array and string offset access syntax with curly braces is deprecated in ...cloudflare/sdk/src/Endpoints/DNS.php on line 131
Probably needs some love on 7.4
When I perform
GET zones/:zone_identifier/dns_records/export
the result is empty. How can I export the DNS zone for a backup.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.