How can I upload a file to a Synology diskstation with PHP - php

I want to post to a Synology Disksation and upload a file with PHP. The Synology's API gives me an interface that I want to call with PHP. See the documentation below.
https://global.download.synology.com/download/Document/DeveloperGuide/Synology_File_Station_API_Guide.pdf#%5B%7B%22num%22%3A111%2C%22gen%22%3A0%7D%2C%7B%22name%22%3A%22XYZ%22%7D%2C69%2C711%2C0%5D
Here is my code, which I use for the post:
<?php
$params = array(
'path' => '/home/upload',
'create_parents' => 'true',
'overwrite' => 'true',
'api' => 'SYNO.FileStation.Upload',
'version' => 2,
'method' => 'upload'
'_sid' => [id of session after authenticate],
'file[]' => "#".path_to_file
);
$ch = curl_init();
$BODY = http_build_query($params);
curl_setopt($ch, CURLOPT_URL, 'http://ip_of_diskstation:5000/entry.cgi');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $BODY);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
var_dump($result);
?>
This call works, but the diskstation gives me the following JSON.
{"error":{"code":401},"success":false}
According to the documentation, there is a "Unknown error of file operation". Also, using "file_get_contents (path to file)" instead of "#".path_to_file gives me the same error from the diskstation.
How can I post a file and parameters to a synology diskstation?

Can you try to add _sid in your web api url like http://ip_of_diskstation:5000/entry.cgi?_sid=
I make it work using nodejs request library.
Below is the code:
let r = request.post( { url: `${web_url}/entry.cgi?_sid=${sid}` }, ( err, response, body ) => {
return callback( err, response );
});
let form = r.form();
form.append( 'api', 'SYNO.FileStation.Upload');
form.append( 'version', '2');
form.append( 'method', 'upload' );
form.append( 'overwrite', 'false' );
form.append( 'path', '<shared folder path>');
form.append( 'create_parents', 'true' );
form.append( '_sid', sid );
form.append( 'file', fs.createReadStream( file ), { 'filename' : <filename without the path>});
Regards,
Felix

You get :
"{"error":{"code":401},"success":false}"
Because the official document is wrong.
See Upload file through FileStation upload api for details.

From what I see the url that you used in CURLOPT_URL needs to be updated. Also the file that is in the $params needs to be updated.
Some side notes. Make sure your settings for the user's SID has permissions set properly. Also make sure you updated the $_FILES["uploadfile"] to include whatever name you used within the input element of the form (instead of uploadfile, which I used).
See this github link for where I found my reference. Postman helped me duplicate this in PHP.
$sid = '_sid=[YOURSID]';
$url = 'HOSTNAME/webapi/entry.cgi?' . $sid;
$SynologySharedPath = 'FILEPATH';
$params = array(
'api' => 'SYNO.FileStation.Upload',
'version' => '2',
'method' => 'upload',
'path' => $SynologySharedPath,
'create_parents' => 'true',
'overwrite' => 'true',
'file' => new \CurlFile($_FILES["uploadfile"]["tmp_name"], $_FILES["uploadfile"]["type"], $_FILES['uploadfile']['name'])
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_VERBOSE,true);
$result = curl_exec ($ch);
$curlresponse = json_decode($result, true);

Related

Using cURL to get JSON from an API returns nothing

I've started making a webpage that uses an API from another website to get phone numbers for verification of websites, which I've gotten working with Python already. However, when I try to use cURL to get the JSON data from the API it returns nothing. The code for the PHP is below.
echo "Requesting number...";
$url = 'api.php'; # changed from the actual website
$params = array(
'metod' => 'get_number', # misspelt because it is not an english website
'apikey' => 'XXXXXXXXXXXXXXXXXXXXXXXXX',
'country' => 'RU',
'service' => 'XXXXX',
);
$ch = curl_unit();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$result = curl_exec($ch);
if(curl_errno($ch) !== 0) {
error_log('cURL error when connecting to ' . $url . ': ' . curl_error($ch));
}
curl_close($ch);
print_r($result);`
I expect that when the code is executed on the server it should give all of the JSON from the file, which I can then use later to pick out only certain parts of it to use elsewhere. However the actual results are that it does not print anything, as seen here: https://imgur.com/sdCYhlw
I'm not sure why your code doesn't work, but a simpler alternative could be to use file_get_contents:
echo "Requesting number...";
$url = 'api.php'; # changed from the actual website
$postdata = http_build_query(
array(
'metod' => 'get_number', # misspelled because it is not an English website
'apikey' => 'XXXXXXXXXXXXXXXXXXXXXXXXX',
'country' => 'RU',
'service' => 'XXXXX'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
print_r($result);

Trouble with POST API using cURL

I'm trying to post to an API using cURL with no luck. I've been researching this for 2-days now and I can't seem to get it to work.
Here is an example of a URL that I can paste into a web browser and it works, no problem:
http://{myserver}:{port}/api.aspx?Action=AddTicket&Key=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx&Subject=Test&Description=Test&Username={domain}\{username}
(I obviously redacted some information).
I know that cURL is up to date and working on the server because I can make a simple request out to [http://www.google.com] and it returns the page properly and I've also confirmed it on the php.info page as being ENABLED.
I've tried every layout I can find for the cURL code such as settings the POSTFIELDS as an array as well as a string. I've followed along with multiple YouTube videos and web tutorials to the 'T' with no success. I've even tried setting the URL parameter in the $ch to the entire above URL just for the heck of it... No success.
Can anyone explain or give examples of how this should be formatted so that it simply posts a URL identical to the one above??
Much appreciated!
As requested, here's my code.
$url = 'http://{server}:{port}/api.aspx?Action=AddTicket';
$post_data = '&key=' . $key . '&subject=' . $subject . '&description=' . $details . '&username={domain}\{username}';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
if ($output === false) {
echo "cURL Error: " . curl_error($ch);
}
curl_close($ch);
print_r($output);
And here is my attempt using an array instead of a string for the POSTFIELDS.
$url = 'http://{server}:{port}/api.aspx?Action=AddTicket';
$post_data = array(
'key' => $key,
'subject' => $subject,
'description' => $details,
'username' => '{domain}\{username}'
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
$output = curl_exec($ch);
if ($output === false) {
echo "cURL Error: " . curl_error($ch);
}
curl_close($ch);
print_r($output);
EDIT
I've tried some of the examples given in the comments. Here's a small test I'm currently running.
$data = array(
'Action' => 'AddTicket',
'Key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
'Subject' => 'test',
'Description' => 'test',
'Username' => '{domain}\{username}'
);
$query = http_build_query($data);
$url = 'http://{server}:{port}/api.aspx?' . $query;
print_r($url);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_URL => $url
));
$resp = curl_exec($curl);
curl_close($curl);
Now, if I straight up take the $url variable from the above code and run this...
header("Location:" . $url);
die();
It works perfectly... so my problem has to be something in the cURL syntax or parameters...
EDIT
After adding the following code...
var_dump($resp);
var_dump(curl_getinfo($curl, CURLINFO_HTTP_CODE));
var_dump(curl_error($curl));
I get the following result...
string(0) ""
int(401)
string(0) ""
Anyone know what this means?
Your working example indicates that this is not a POST request at all, but instead a GET request.
Try building your URL like so:
$data = array(
'Action' => 'AddTicket',
'key' => $key,
'subject' => $subject,
'description' => $details,
'username' => '{domain}\{username}'
);
$query = http_build_query($data);
$url = 'http://{myserver}:{port}/api.aspx?' . $query;
Then you probably only need to perform a GET request to that URL.
Edit: Seeing your latest update, try using json_encode on your postfields.
The URL you're supplying uses GET parameters. Hopefully the below snippet should help;
$curl = curl_init();
// Heres our POSTFIELDS
$params = array(
'param1' => 'blah1',
'param2' => 'blah2'
);
$params_json = json_encode($params);
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://example.com',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => 1,
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_POSTFIELDS => $params_json
));
$response = curl_exec($curl);
$error = curl_error($curl);
curl_close($curl);

Bitshares API - Create an account under a registrar using PHP

I've been trying to create an account under a registrar account on Bitshares Test Net programatically using Graphene API and its blockchain. I read the API documentation and have concluded that the PHP code bellow is what I need to execute to be able to create a new account.
<?php
$url = 'https://testnet.bitshares.eu/';
$array = array(
'jsonrpc' => '2.0',
'method' => 'register_account',
'params' => array(
'name' => 'NEW_ACCOUNT_NAME',
'owner_key' => 'OWNER_KEY',
'active_key' => 'ACTIVE_KEY',
'registrar_account' => 'REGISTRAR_ACCOUNT',
'referrer_account' => 'REGISTRAR_ACCOUNT',
'referrer_percent' => 1,
'broadcast' => 1
),
'id' => 1
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, 'GraphenePHP/1.0');
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($array));
$response = curl_exec($ch);
curl_close($ch);
echo '<pre>';
print_r($response);
echo '</pre>';
The code above is not working. Also I am not getting any response. I have a feeling that I am missing something or the value of $url is incorrect.
Please help?
This Bitshares testnet link https://testnet.bitshares.eu/ sometimes does not work.
You can simply use real net or install testnet on your side for this.

Php Facebook - Upload Image from External Source

Good morning fellows,
I am having an issue with facebook api:
is it possible to upload a photo from an external source? For instance, point out an URL and the Facebook will get that...
My code is right next $args = array(
'message' => 'Photo from application',
'source' => $im_url
);
$url = 'https://graph.facebook.com/'.$album_id.'/photos?access_token='.$token;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$data = curl_exec($ch);the $im_url should point out to an external picture, like store on imageshack,etc.The error it gives me is {"error":{"message":"(#324) Requires upload file","type":"OAuthException"}}
Instead of "source", the term is "url". Problem solved
$args = array(
'message' => 'Photo from application',
'url' => $im_url

getting Bad Request during opening a querystring file in CURL

$URL:https://demo.firstach.com/https/TransRequest.asp?Login_ID=someit&Transaction_Key=somekey&Customer_ID=23&Customer_Name=Muhammad Naeem&Customer_Address=Address&Customer_City=city&Customer_State=HI&Customer_Zip=54000&Customer_Phone=--&Customer_Bank_ID=111111118&Customer_Bank_Account=12345678901234567890&Account_Type=Business Checking&Transaction_Type=Debit&Frequency=Once&Number_of_Payments=1&Effective_Date=12%2F05%2F2010&Amount_per_Transaction=10.00&Check_No=&Memo=&SECCType=WEB
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url); // set url to post to
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
curl_setopt($ch, CURLOPT_TIMEOUT, 0); // times out after Ns
curl_setopt($ch, CURLOPT_FAILONERROR, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_COOKIEFILE, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$result = curl_exec($ch); // run the whole process
print_r($result);
curl_close($ch);
i also used file_get_conent and fopen but all are returning me BAD REQUEST error,
please help me out
for more detail please see the link below
http://www.uqwibble.com/Phase-2/ach.php
Well assumign the code you posted is accurate then this line is the issue:
$URL:https://demo.firstach.com/https/TransRequest.asp?Login_ID=someit&Transaction_Key=somekey&Customer_ID=23&Customer_Name=Muhammad Naeem&Customer_Address=Address&Customer_City=city&Customer_State=HI&Customer_Zip=54000&Customer_Phone=--&Customer_Bank_ID=111111118&Customer_Bank_Account=12345678901234567890&Account_Type=Business Checking&Transaction_Type=Debit&Frequency=Once&Number_of_Payments=1&Effective_Date=12%2F05%2F2010&Amount_per_Transaction=10.00&Check_No=&Memo=&SECCType=WEB
here it looks liek you attemtp to define $URL but when you use it with cURL you are referencing $url. The varibales are case sensitive. Secondly you have $URL: which is not valid you want to use $url =.
Addiitonally i would encode the params like this:
$baseurl = 'https://demo.firstach.com/https/TransRequest.asp';
$params = array(
'Login_ID' => 'someit',
'Transaction_Key' => 'somekey',
'Customer_ID'= => 23,
'Customer_Name' => 'Muhammad Naeem',
'Customer_Address' => 'Address',
'Customer_City' => 'city',
'Customer_State' => 'HI',
'Customer_Zip' => '54000',
'Customer_Phone' => '--',
'Customer_Bank_ID' => '111111118'
'Customer_Bank_Account' => '12345678901234567890'
'Account_Type' => 'Business Checking'
'Transaction_Type' => 'Debit'
'Frequency' => 'Once'
'Number_of_Payments' => 1,
'Effective_Date'=> '12/05/2010',
'Amount_per_Transaction' => '10.00',
'Check_No'=> '',
'Memo'=> '',
'SECCType' => 'WEB'
);
$url = sprintf('%s?%s', $baseurl, http_build_query($params));
That way http_build_query will take care of all your url encoding and you can work with an array before hand so its easy to see whats going on and add/remove/change paramters. Alternatively if its a post request you could jsut use:
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
which will take care of all the parameter encoding and what not directly from the array this way they dont need to be appended manually to the $url.

Categories