Sending DELETE to API using PHP - php

I am brand new to using an API outside of an API wrapper. I can access the API using
curl -u username:password https://company.c
om/api/v1/resources/xxxxxxx
That loads up all the information, but what I need to do is send a DELETE to the url based on an array of filenames; e.g. ['/js/jquery.js']. The name of the parameter is Files.
I already have in code the directory and file name variables.
$storageFilename = $directoryname . "/" . $asset->name;
Above returns the /directoryname/filename from the database.

To send an HTTP(S) DELETE using the cURL library in PHP:
$url = 'https://url_for_your_api';
//this is the data you will send with the DELETE
$fields = array(
'field1' => urlencode('data for field1'),
'field2' => urlencode('data for field2'),
'field3' => urlencode('data for field3')
);
/*ready the data in HTTP request format
*(like the querystring in an HTTP GET, after the '?') */
$fields_string = http_build_query($fields);
//open connection
$ch = curl_init();
/*if you need to do basic authentication use these lines,
*otherwise comment them out (like, if your authenticate to your API
*by sending information in the $fields, above. */
$username = 'your_username';
$password = 'your_password';
curl_setopt($process, CURLOPT_USERPWD, $username . ":" . $password);
/*end authentication*/
curl_setopt($ch, CURLOPT_URL, $url);
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);
/* this answer builds on David Walsh's very good HTTP POST example at:
* http://davidwalsh.name/curl-post
* modified here to make it work for HTTPS and DELETE and Authentication */

Related

How to delete a single Marketing Campaign recipient with API and PHP

Trying to implement DELETE https://api.sendgrid.com/v3/contactdb/lists/{list_id}/recipients/{recipient_id} HTTP/1.1 in order to delete a single email recipient from a list, but I get this error message as the Result: {"errors":[{"message":"no valid recipients were provided"}]}.
Here is the code, which I modified from Sending DELETE to API using PHP:
<?php
$list = "971292";
$recipient = "joe#joeblowxyz.com";
$url = 'https://api.sendgrid.com/v3/contactdb/lists/' . $list . '/recipients/' . $recipient;
//this is the data you will send with the DELETE
**# DO I NEED THIS?**
$fields = array(
'field1' => 'field1',
'field2' => 'field2',
'field3' => 'field3'
);
/*ready the data in HTTP request format
*(like the querystring in an HTTP GET, after the '?') */
$fields_string = http_build_query($fields);
//open connection
$ch = curl_init();
/*if you need to do basic authentication use these lines,
*otherwise comment them out (like, if your authenticate to your API
*by sending information in the $fields, above. */
$username = 'myusername';
$password = 'mypassword';
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
/*end authentication*/
curl_setopt($ch, CURLOPT_URL, $url);
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 error message, "no valid recipients were provided" makes me think I am supposed to use a numeric recipient id, but I haven't been able to find it for the email address in question. Where is it?
In addition, is there anything else from the above code that is causing me problems?

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

Upload file to Bitbucket via PHP script

I try to upload my database to bitbucket downloads section of my repository via a PHP script using curl library. Normally i go to my phpmyadmin and export my database to a folder, then going to my bitbucket account under downloads section of my repository and upload manually. I need a script that automates these tasks.
I tried using curl library like this:
// bitbucket username and password
define('USERNAME', 'my_username');
define('PASSWORD', 'my_password');
$url = 'https://bbuseruploads.s3.amazonaws.com/';
//This needs to be the full path to the file you want to send.
$file_name_with_full_path = realpath('apache_pb2.gif');
$post = array('extra_info' => '123456', 'file_contents' => '#' . $file_name_with_full_path); // image file example here
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, USERNAME . ":" . PASSWORD);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$resp = curl_exec($ch);
// validate CURL status
if (curl_errno($ch))
throw new Exception(curl_error($ch), 500);
The result:
<error><code>InvalidArgument</code>
<message>Unsupported Authorization Type</message>
<argumentvalue>Basic hash_code_here</argumentvalue>
<argumentname>Authorization</argumentname>
<requestid>hash_code_here</requestid>
<hostid>hash_code_here</hostid>
</error>
If you need further clarifications please let me know.
Just for the case someone finds this old corpse here:
I solved it by this funktion function:
/**
* Uploads a file to Bitbucket Download area of the configured repository
* Does the same as thi bash command:
* curl -X POST "https://USER:PW#api.bitbucket.org/2.0/repositories/owner/slug/downloads/" --form files=#"test.txt"
* #param string $filename
* #param string $apiEndpoint
* #param string $apiUser
* #param string $apiPassword
* #return bool|string
* #throws Deployer\Exception\Exception
*/
public static function sendFileToDownload(
string $filename,
string $apiEndpoint,
string $apiUser,
string $apiPassword
) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $apiEndpoint);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLAUTH_BASIC, 1);
curl_setopt($curl, CURLOPT_USERPWD, "$apiUser:$apiPassword");
$data = [
'files' => curl_file_create($filename),
];
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$erg = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($erg === false || $status > 300) {
throw new Deployer\Exception\Exception("Result: ".print_r($erg, true), $status);
}
curl_close($curl);
}
}
For me the most important point was this section:
$data = [
'files' => curl_file_create($filename),
];
This results in a local file been uploaded to my repos download area with the name $filename (filename path).
Had this same problem today. "Unsupported Authorization Type" response from an API CURL request.
I spent a long time consulting with Google. In the end, I discovered that my URL had two slashes in it together (accidentally). See, the API I'm connecting to has a URL, and then an API endpoint. Like this:
https://www.example.com/api/v2/foo -or-
https://www.example.com/api/v2/bar
But I accidentally was combining them like this:
curl_setopt($curl, CURLOPT_URL, $url ."/". $endpoint);
given my data:
$url = "https://www.example.com/api/v2/"
$endpoint = "foo"
I ended up with this:
"https://www.example.com/api/v2//foo"
Problem solved by removing the ."/". and just making it this: .
BONUS POSSIBILITY: Something else interesting I learned in the process was that the API folks prefer double-quotes around json data posted to them. I haven't verified it makes a difference, but instead of wrapping double-quotes in single-quotes (or visa-versa), escaping the internal double-quotes is how I left things. And it's working.

Executing Curl with PHP

I'm trying to use Docverter to convert LaTeX/markdown files to PDF but am having trouble using PHP to do CURL to access Docverter via their API. I'm know I'm not a total idiot b/c i can get this to work adapting the shell script in this Docverter example and running from command line (Mac OSX).
Using PHP's exec():
$url=$_SERVER["DOCUMENT_ROOT"];
$file='/markdown.md';
$output= $url.'/markdown_to_pdf.pdf';
$command="curl --form from=markdown \
--form to=pdf \
--form input_files[]=#".$url.$file." \
http://c.docverter.com/convert > ".$output;
exec("$command");
This gives no error messages but doesn't work. Is there a path issue somewhere?
UPDATE Based on #John's suggestion, here's an example using PHP's curl_exec() adapted from here. Unfortunately this also doesn't work though at least it gives error messages.
$url = 'http://c.docverter.com/convert';
$fields_string ='';
$fields = array('from' => 'markdown',
'to' => 'pdf',
'input_files[]' => $_SERVER['DOCUMENT_ROOT'].'/markdown.md',
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
I solved my own problem. There were two main problems with the above code:
1) The $fields array was incorrectly formatted for the input_files[]. It needed a #/ and mime-type declaration (see code below)
2) The curl_exec() output (the actual newly created file contents) needed to be returned and not just true/false which is this function's default behavior. This is accomplished by setting the curl option curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); (see code below).
Full working example
//set POST variables
$url = 'http://c.docverter.com/convert';
$fields = array('from' => 'markdown',
'to' => 'pdf',
'input_files[]' => "#/".realpath('markdown.md').";type=text/x-markdown; charset=UTF-8"
);
//open connection
$ch = curl_init();
//set options
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data"));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //needed so that the $result=curl_exec() output is the file and isn't just true/false
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
//write to file
$fp = fopen('uploads/result.pdf', 'w'); //make sure the directory markdown.md is in and the result.pdf will go to has proper permissions
fwrite($fp, $result);
fclose($fp);

Retrieve username, password parameters passed through curl

I am trying to send username and password parameters to a url using curl, and I want to retrieve them. I send the parameters to a page, like the following:
<?php
$curl = curl_init('http://localhost/sample.php');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_USERPWD, 'key:123456');
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_USERAGENT, 'Sample Code');
$response = curl_exec($curl);
$resultStatus = curl_getinfo($curl);
if($resultStatus['http_code'] == 200) {
echo $response;
} else {
echo 'Call Failed '.print_r($resultStatus);
}
?>
Now in the sample.php page, how can I retrieve those parameters?
(here, username is key, password is 123456).
I suppose they must be available in the $_SERVER array, but they are not available.
Some of the parameters, like CURLOPT_USERAGENT are send in the HTTP headers and can be retrieved using special globals like $_SERVER['HTTP_USER_AGENT'] (see http://www.php.net/manual/de/reserved.variables.server.php).
Others, like CURLOPT_SSL_VERIFYPEER are only local to CURL and don't get send to the server.
By default, cURL issues an HTTP GET request. In this case, you'd have to append the parameters to the URL you're calling:
$curl = curl_init('http://localhost/sample.php?foo=bar&baz=zoid');
In sample.php, $_GET['bar'] and $_GET['baz'] would be available respectively. If it's a POST request, you want to issue, you'll need to set the parameters via curl_setopt:
$curl = curl_init('http://localhost/sample.php');
curl_setopt($curl, CURLOPT_POSTFIELDS, 'foo=bar&baz=zoid');
to send parameters to a web page you can use 1 of two methods GET or POST
GET is where the parameters are appended to the name of the resource you are getting
e.g $url = "http://localhost/sample.php?name=" . urlencode( $value )
the other choice is via a POST. post is sent to the server as a page of information to do this with curl you create a post with
curl_setopt($ch, CURLOPT_POSTFIELDS, 'name=' . urlencode( $value ) . '&name2=' . urlencode( $value2 ));
If on the other hand you are talking about Headers, then you can access them through the $_SERVER['headername'] array.
DC
you can find the username and password in the global $_SERVER array
$_SERVER : array
(
....
'PHP_AUTH_USER' => 'the_username'
'PHP_AUTH_PW' => 'the_password'
)

Categories