1+ <?php
2+ class cloudflare_api
3+ {
4+
5+
6+ //Timeout for the API requests in seconds
7+ const TIMEOUT = 5 ;
8+
9+ private $ URL = 'https://api.cloudflare.com/client/v4/ ' ;
10+ //Stores the email login
11+ private $ auth_email ;
12+ private $ auth_key ;
13+
14+
15+ public function __construct ()
16+ {
17+
18+ $ num_args = func_num_args ();
19+ if ($ num_args == 2 ){
20+ $ parameters = func_get_args ();
21+ $ this ->auth_email = $ parameters [0 ];
22+ $ this ->auth_key = $ parameters [1 ];
23+ }else {
24+ //throw error
25+ }
26+
27+ }
28+
29+ public function purge_files ($ domain , $ files ){
30+ $ data = [
31+ 'files ' => $ files
32+ ];
33+ $ this ->delete ('zones/ ' .$ domain .'/purge_cache ' , $ data );
34+ }
35+
36+ private function delete ($ endpoint ,$ data ){
37+ return $ this ->http_request ($ endpoint ,$ data ,'delete ' );
38+ }
39+ /**
40+ * Handle http request to cloudflare server
41+ */
42+ private function http_request ($ endpoint ,$ data , $ method )
43+ {
44+ //setup url
45+ $ url = $ this ->url .$ endpoint ;
46+
47+
48+ //headers set
49+ $ headers = ["X-Auth-Email: {$ this ->auth_email }" , "X-Auth-Key: {$ this ->auth_key }" ];
50+ $ headers [] = 'Content-type: application/json ' ;
51+
52+ //json encode data
53+ $ json_data = json_encode ($ data );
54+
55+ $ ch = curl_init ();
56+ curl_setopt ($ ch , CURLOPT_VERBOSE , 0 );
57+ curl_setopt ($ ch , CURLOPT_FORBID_REUSE , true );
58+ curl_setopt ($ ch , CURLOPT_URL , self ::$ URL [$ type ]);
59+ curl_setopt ($ ch , CURLOPT_RETURNTRANSFER , 1 );
60+ curl_setopt ($ ch , CURLOPT_POST , 1 );
61+ curl_setopt ($ ch , CURLOPT_POSTFIELDS , $ json_data );
62+ curl_setopt ($ ch , CURLOPT_TIMEOUT , self ::TIMEOUT );
63+ curl_setopt ($ ch , CURLOPT_SSL_VERIFYPEER , false );
64+
65+ if ($ method === 'post ' )
66+ curl_setopt ($ ch , CURLOPT_POST , true );
67+
68+ if ($ method === 'put ' )
69+ curl_setopt ($ ch , CURLOPT_CUSTOMREQUEST , 'PUT ' );
70+
71+ if ($ method === 'delete ' )
72+ curl_setopt ($ ch , CURLOPT_CUSTOMREQUEST , 'DELETE ' );
73+
74+
75+
76+ //get request
77+ if (!isset ($ method ) || $ method == 'get ' )
78+ $ url .= '? ' .http_build_query ($ data );
79+
80+ //add headers
81+ curl_setopt ($ ch , CURLOPT_HTTPHEADER , $ headers );
82+ curl_setopt ($ ch , CURLOPT_URL , $ url );
83+
84+
85+ $ http_result = curl_exec ($ ch );
86+ $ error = curl_error ($ ch );
87+ $ http_code = curl_getinfo ($ ch , CURLINFO_HTTP_CODE );
88+ curl_close ($ ch );
89+
90+ if ($ http_code != 200 ) {
91+ return array (
92+ 'error ' => $ error
93+ );
94+ } else {
95+ return json_decode ($ http_result );
96+ }
97+ }
98+ }
0 commit comments