How to make php api call to CloudFlare to Purge individual files by URL from cache - api

this code worked good to Purge All files from cache .
Example:
$authKey = "MyKEY";
$authEmail = "myEMAIL";
$zoneId = "MYZONEID";
$endpoint = "purge_cache";
$data = [
"purge_everything" => true
];
$url = "https://api.cloudflare.com/client/v4/zones/{$zoneId}/{$endpoint}";
$opts = ['http' => [
'method' => 'DELETE',
'header' => [
"Content-Type: application/json",
"X-Auth-Key: {$authKey}",
"X-Auth-Email: {$authEmail}",
],
'content' => json_encode($data),
]];
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
But I need Purge individual files by URL how can I do that via PHP ?
On api page I found this link: https://api.cloudflare.com/#zone-purge-individual-files-by-url
but I don't now how to make it via php ?

You need to pass an array with files - like explained on the API Docs
In your example that would be something like
$data = '{"files":[
"http://www.example.com/css/styles1.css",
"http://www.example.com/css/styles2.css",
"http://www.example.com/css/styles3.css"
]}';

Related

API Question - How to create relationships and query with multiple GET calls using cURL

I was just handed a project and not sure how to handle it. I have limited API experience, but have been able to pull the data using the code below. In this example I want to display a cruise sailing. I have an API endpoint url of https://api.website.com/sailing/123456 (example). This gives me a ton of data, but not everything i need. For example, it gives me the "supplier_id" (this would be something like 22). I want the supplier_name, so I can display "Carnival Cruise" instead of "22". Supplier_name is in another endpoint url - https://api.website.com/suppliers. This is where I am stuck. My thought is to bring in multiple GETS and then query it down. For example, If I brought in both endpoint URLs in this example and relate the two using supplier_id (exists in both examples), then I could bring in my Supplier Name. Am I way off here? I'm used to working with a DB and queries, so maybe I'm on the wrong path. Please help if you can. Thanks!
<?php
/* Sample call to get cruise sailings with filter/fields constraints */
$curl = curl_init();
$api_endpoint = "https://api.website.com/sailing/123456";
$api_key = "a57fecd04e71402fba73cb2e63a262aa";
$dataArray = array(
"start_at" => 1,
"max_return" => 170
);
$request_url = $api_endpoint . "?" . http_build_query($dataArray);
curl_setopt_array(
$curl,
array(
CURLOPT_URL => $request_url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"accept: application/json",
"api_key: {$api_key}"
)
)
);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
/* SIMPLE DUMP OF DATA
echo $response;*/
}
$data = json_decode($response);
$total = $data->meta->total;
$startAt = $data->meta->start;
$maxReturn = $data->meta->count;
// Table view of data
echo '<table border=1><tr><th>Sailing ID</th><th>Title</th><th>Supplier ID</th><th>Supplier Name</th></tr>';
echo '<td>' .$item->sailing_id.'</td>';
echo '<td>' .$item->title.'</td>';
echo '<td>' .$item->supplier_id.'</td>';
echo '<td>' .$item->supplier_name.'</td></tr>';
echo '</table>';
?>

The result of the search query differs in the API and Shutterstock website

please help me.
The result of the search query differs in the API and Shutterstock website.
What am I doing wrong?
API returns only 4 results, but at shutterstock - thousands
My code:
$queryFields = [
"query" => "осень лес векторы"
];
$options = [
CURLOPT_URL => "https://api.shutterstock.com/v2/images/search?" . http_build_query($queryFields),
CURLOPT_USERAGENT => "php/curl",
CURLOPT_HTTPHEADER => [
"Authorization: Bearer xxxxx"
],
CURLOPT_RETURNTRANSFER => 1
];
$handle = curl_init();
curl_setopt_array($handle, $options);
$response = curl_exec($handle);
curl_close($handle);
$decodedResponse = json_decode($response);
echo "<pre>";
print_r( $decodedResponse );
echo "</pre>";
Thank you.
The default API access (Self Serve, or Free product) is limited to a subset of Shutterstock's library - only about 1 million images. That's why you only see 4 results for your search compared to the website. If you need access to more content, just reach out to the team - https://developers.shutterstock.com/contact-us

Guzzle 6 is following redirects on local docker server, but not on production server

I am using Guzzle 6 Http Client to scrape web pages and analyze them from SEO perspective, however interesting thing is, that Guzzle does not follow redirects at all, when being used in production, but code is exatly the same. Here is the snippet I am using to request page and track redirects.
$onRedirect = function (RequestInterface $request, ResponseInterface $response, UriInterface $uri): void {
$this->totalRedirects++;
};
$response = $this->httpClient->request('GET', $url, [
'allow_redirects' => [
'max' => self::MAX_REDIRECTS,
'referer' => true,
'track_redirects' => true,
'on_redirect' => $onRedirect
],
'headers' => [
'User-Agent' => self::USER_AGENT
],
'http_errors' => true
]);
$redirectUrls = $response->getHeader('X-Guzzle-Redirect-History');
$redirectStatuses = $response->getHeader('X-Guzzle-Redirect-Status-History');
foreach ($redirectUrls as $key => $redirectUrl) {
$this->responses[] = new HttpResponse($redirectUrl, $redirectStatuses[$key]);
}
//Save last successful response
$this->responses[] = new HttpResponse($url, $response->getStatusCode());
My redirect middleware is not triggered at all, using this in production and it returns only "307", while in docker I get "307" and "200". This have been tested using samaritans page - (https://www.samaritans.org/)
Both Production and docker are using PHP 7.2 and Guzzle 6

Is it still possible to use Itunes Connect API endpoints instead of Java Reporter tool?

Prior to the newest Itunes Connect update all requests were HTTP requests made through Curl in our application. After the update, Apple is recommending to use their new reporter tool.
https://github.com/mikebarlow/itc-reporter I want to do something similar to this if possible. This supposedly works without the reporter tool and it looks like it is still just making HTTP requests. I won't use this code in my project because it requires us to update PHP version which we have planned for another time.
Is it possible to make simple HTTP requests using Curl to get data? I don't want to use Guzzle if I don't have to!
$json = '{"userid":"{{USERNAME}}","password":"{{PASSWORD}}","version":"2.0","mode":"Robot.XML","account":"{{VENDOR_ID}}","queryInput":"[p=Reporter.properties, Sales.getReport, {{VENDOR_ID}},Sales,Summary,Weekly,20170108]"}'
CURLOPT_URL => 'https://reportingitc-reporter.apple.com/reportservice/sales/v1',
CURLOPT_HEADER => false,
CURLOPT_HTTPHEADER => array('Accept: text/xml, text/plain', 'Content-Type: text/xml, text/plain'),
CURLOPT_USERAGENT => 'Java/1.8.0_92',
CURLOPT_TIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $json,
this is the request I've made while testing and when I run it I get the HTML response saying "Forbidden, You do not have access to this page"
I tried this while urlencoding username and password but I get the same result. I would love to be able to still get this data using Curl or we will have to work on adding the reporter tool into our application.
the postfield just needed to be changed accordingly
function build_json_request(, $access_token, $account_id,
$args_arr=array())
{
$args = $args_arr;
$json = array(
'accesstoken' => urlencode($access_token),
'version' => '2.2',
'mode' => 'Robot.XML',
'account' => $account_id
);
$queryInput = array(
'p=Reporter.properties',
array_shift($args)
);
if(! empty($args))
$queryInput[] = implode(',', $args);
$json['queryInput'] = '[' . implode(', ', $queryInput) . ']';
return json_encode($json);
}
$json = build_json_request('Sales.getReport', $access_token, $account_id, array('Sales.getReport', $vendor_id, 'Sales', 'Summary', 'Daily', $date) );
$output = process_curl(array(
CURLOPT_URL => 'https://reportingitc-reporter.apple.com/reportservice/sales/v1',
CURLOPT_HEADER => false,
CURLOPT_TIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => 'jsonRequest='.$json,
));

Firebase GET data via REST API PHP CURL

Trying to do a simple read via PHP cURL. I can read my data successfully if my security rules let everyone in e.g.
{
"rules": {
".read": true,
".write": true
}
}
However if I restrict read/write to a specific username e.g.
{
"rules": {
".read": "auth.username == 'admin'",
".write": "auth.username == 'admin'"
}
}
I get permission denied.
The code is as follows...
require('JWT.php');
$secret = 'MY_FIREBASE_SECRET';
$data = array('username' => 'admin');
$token = JWT::encode($data, $secret);
$url = "https://MY_FIREBASE.firebaseio.com/messages.json?auth=$token";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url
));
$response = curl_exec($curl);
Its worth noting, if I just use my FB secret instead of a token in the URL I am able to successfully read the data (auth=$secret). I have also successfully tested reading the data in the Forge simulator using "custom auth" e.g. {'username': 'admin'}
I'm using the PHP JWT library: https://github.com/luciferous/jwt/blob/master/JWT.php
Not sure if I'm getting permission denied because my cURL call is not correct or I'm not constructing the token properly. I have tried using POST and GET via cURL but I'm getting the same result.
Any suggestions would be much appreciated...
Thanks for the super quick response Andrew. I tried your suggestion. Unfortunately, I'm still getting 'permission denied'. Here is my updated code...
require('JWT.php');
$secret = 'my-secret';
$user = array( 'v' => 0, 'iat' => time(), 'd' => array('username' => 'admin', 'type' => 'admin', 'fullname' => 'Administrator'));
$token = JWT::encode($user, $secret);
$curl = curl_init();
$url = "https://myfirebase.firebaseio.com/messages.json?auth=$token";
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url
));
$response = curl_exec($curl);
curl_close($curl);
I did get this working by changing the .read rule for our data to
"auth != null" - but that doesn't seem to quite as secure...
For reference our data structure is simply
+ myfirebase
+ messages
- 000001 = "this is the 1st test message"
- 000002 = "this is the 2nd test message"
BTW: Our application will only have 1 user reading/writing data. If I can not get the token to work... Is there a better way to authenticate calls via the REST API without resorting to passing our secret key in the URL? e.g. &auth='my-secret'
The Firebase JWT has some structure to it that is missing here. There's a detailed explanation of what should be in these auth tokens here:
https://www.firebase.com/docs/security/jwt-auth-token-format.html
Here is a snippet with the appropriate structure.
require_once('JWT.php');
$fbSecret = 'your-secret';
$user = array( 'v' => 0, 'iat' => <timestamp>,
'd' => array('username' => 'jimbob', 'type' => 'admin',\
'fullname' => 'Jim Bob')
);
$token = JWT::encode($user, $fbSecret);
Note that the "d" field contains the actual payload. "v", and "iat" are also required. "iat" should be the number of seconds since the epoch (it's the number that (new Date()).getTime() returns in Javascript).