简体   繁体   中英

How to use an array in an API using curl

I am trying to access the cdnify API to purge cache for an individual file ( https://cdnify.com/learn/api#purgecache )

This is my current code

    $cdn_api_user = env('CDNIFY_API');
    $cdn_api_password = env('CDNIFY_API_PASS');
    $cdn_api_resource = env('CDNIFY_API_RESOURCE');

    $cdnifyapicacheurl = 'https://' . $cdn_api_user . ':' . $cdn_api_password . '@' . 'cdnify.com/api/v1/resources/' . $cdn_api_resource . '/cache';

    return print $cdnifyapicacheurl;

    $fields = array(
        'files' => $storageFilename
    );

    $fields_string = http_build_query($fields);

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $cdnifyapicacheurl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
    curl_setopt($ch, CURLOPT_POST, count($fields));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
    //unless you have installed root CAs you can't verify the remote server's certificate.  Disable checking if this is suitable for your application
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    //perform the HTTP DELETE
    $result = curl_exec($ch);

    //close connection
    curl_close($ch);

the env variables at the top call in my api key, password, and resource for the url. I have verified I am logging in via that url.

When I debug through my code i get an error on

    $fields = array(
        'files' => $storageFilename
    );

which is Array to string conversion .

The $storageFilename variable returns

$storageFilename = "/" . $directoryname . "/" . $asset->name;

which is the filename required for the API call of DELETE.

I can't get passed that $fields array. The other stuff below it may or may not run properly. I am just stuck on how to write this part out.

CURLOPT_POST is just there to indicate if some post data should be included in the HTTP request, so its value should a boolean ( true or false ).

If your array $fields represents the data to be posted, you need to use http_build_query() to assign them to CURLOPT_POSTFIELDS :

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));

There is a return in your code that stops the code the curl code is not getting executed remove it or comment it using // and try again and CURLOPT_POST value is boolean true or false that indicates if you want to use post method or not, your CURL code is really messed up you want to use http delete method or post method ?? You can only use one method, please learn how to use php cURL first http://php.net/manual/en/book.curl.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM