Hy Everyone,
I am using this code to download file from Dropbox Version 2 Php Api.But I don't get success yet in File downloading.Lets have a look on the script which i am using
function dbx_get_file($token, $in_filepath, $out_filepath)
{
$out_fp = fopen($out_filepath, 'w+');
if ($out_fp === FALSE)
{
echo "fopen error; can't open $out_filepath\n";
return (NULL);
}
$url = 'https://content.dropboxapi.com/2/files/download';
$header_array = array(
'Authorization: Bearer ' . $token,
'Content-Type:',
'Dropbox-API-Arg: {"path":"' . $in_filepath . '"}'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header_array);
curl_setopt($ch, CURLOPT_FILE, $out_fp);
$metadata = null;
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function ($ch, $header) use (&$metadata)
{
$prefix = 'dropbox-api-result:';
if (strtolower(substr($header, 0, strlen($prefix))) === $prefix)
{
$metadata = json_decode(substr($header, strlen($prefix)), true);
}
return strlen($header);
}
);
$output = curl_exec($ch);
if ($output === FALSE)
{
echo "curl error: " . curl_error($ch);
}
curl_close($ch);
fclose($out_fp);
return($metadata);
} // dbx_get_file()
Calling this Function Here.
dbx_get_file("<Access-token>", '/Screenshot_1.png', 'Screenshot_1.png');
I also replaced this "Access-token" with my Dropbox O-auth 2 Access Token.
Please suggest me the answer what i am doing wrong?Or is there any other way to download File from Dropbox using DropBox Version 2 PHP Api.
Thanks
I have done it using Requests Library https://github.com/rmccue/Requests/
Here is my Code
include('Requests-master/library/Requests.php');
Requests::register_autoloader();
$token="Your Access Token is here";
$response =
Requests::post("https://content.dropboxapi.com/2/files/download", array(
'Authorization' => "Bearer ".$token,
'Dropbox-Api-Arg' => json_encode(array('path' => '/Screenshot_1.png')),
));
$fileContent = $response->body;
/*Download the file using file_put_contents method*/
file_put_contents("Screenshot_1.png",$fileContent);
$metadata = json_decode($response->headers['Dropbox-Api-Result'], true);
echo "File " . $metadata["name"] . " has the rev " . $metadata["rev"] . ".\n";
File is downloading Successfully... :)
Related
if (strpos($message, "/translate") === 0) {
$word = substr ($message, 10);
$mymemori = json_decode(file_get_contents("https://api.mymemory.translated.net/get?q=".$word."&langpair=en|id"), TRUE)["matches"]["translation"];
file_get_contents($apiURL."/sendmessage?chat_id=".$chatID."&text=Hasil translate: ".$word." : $mymemori ");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_string);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
if(($html = curl_exec($ch)) === false) {
echo 'Curl error: ' . curl_error($ch);
die('111');
}
}
Hello guys i was trying to make translation bot on telegram using php but the output is still error or no output at all. Am using this API https://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en|id
Please help how to get the translation
Error output IMAGES
First, I suggest using cURL, Not file_get_contents.
Second, No need to echo anything, Because the URL will be visited by webhook, Not a human.
Third, You need a method to send requests to Telegram Bot API.
Use this new code:
define('Token', '<your_bot_token>');
# Reading the update from Telegram
$update = json_decode(file_get_contents('php://input'));
$message = $update->message;
$text = $message->text;
if (strpos($text, '/translate') === 0) {
$word = substr ($message, 10);
$mymemori = json_decode(file_get_contents("https://api.mymemory.translated.net/get?q=".$word."&langpair=en|id"), TRUE)["matches"]["translation"];
//
Bot('sendMessage', [
'chat_id' => $update->message->chat->id,
'text' => "Hasil translate: $word : $mymemori "
]);
}
function Bot(string $method, array $params = [])
{
$ch = curl_init();
$api_url = 'https://api.telegram.org/bot' . Token . "/$method";
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$result = curl_exec($ch);
if ($result->ok == false)
{
throw new Exception($result->description, $result->error_code);
}
return $result->result;
}
I have website created in PHP. Basically it is a send document kind of project. It uses a document store in Azure I will call and send it into Azure. Now I want to send in email as well as store in Google drive.
So it should be stored to drive with public access. I have create following code. It works properly I don't want any input from user.
$client->setAccessToken($_SESSION['accessToken']);
$service = new Google_DriveService($client);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$file = new Google_DriveFile();
foreach ($files as $file_name) {
$file_path = 'files/'.$file_name;
$mime_type = finfo_file($finfo, $file_path);
$file->setTitle($file_name);
$file->setDescription('This is a '.$mime_type.' document');
$file->setMimeType($mime_type);
$service->files->insert(
$file,
array(
'data' => file_get_contents($file_path),
'mimeType' => $mime_type
)
);
}
finfo_close($finfo);
I want upload from Azure URL using cURL or using API. When mail send it is automatically uploaded to drive at the same time.
Question Update
I have function to send a mail this is work perfectly. I would like to store an attachment to google drive and retrieve path store that path in to database.
This all work will be based on API no user interaction required. That file is PDF in formate and not specific bytes its different as per data of file.
Issue :
When I upload a file to Drive original file name is rename to untitled. Here is code.
function uploadFile($credentials, $filename, $targetPath)
{
global $GAPIS;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $GAPIS . 'upload/drive/v2/files?uploadType=media');
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
//curl_setopt($ch, CURLOPT_POSTFIELDS, array("title" =>"newfile.txt"));
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($filename));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Content-Type : text/plain', 'Content-Length:' . filesize($filename),
'Authorization: Bearer ' . getAccessToken($credentials))
);
$postResult = curl_exec($ch);
curl_close($ch);
return json_decode($postResult, true);
}
==========================================
Updated code (Issue with Added code but still getting issue with Untitle.pdf in drive)
==========================================
<?php
$GAPIS = 'https://www.googleapis.com/';
$GAPIS_AUTH = $GAPIS . 'auth/';
$GOAUTH = 'https://accounts.google.com/o/oauth2/';
$CLIENT_ID = '709846732498-xxxxxxxx';
$CLIENT_SECRET = 'XXXXXXXXXXXXXX';
$REDIRECT_URI = 'http' . ($_SERVER['SERVER_PORT'] == 80 ? '' : 's') . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'];
$SCOPES = array($GAPIS_AUTH . 'drive', $GAPIS_AUTH . 'drive.file', $GAPIS_AUTH . 'userinfo.email', $GAPIS_AUTH . 'userinfo.profile');
$STORE_PATH = 'credentials.json';
function uploadFile($credentials, $filename, $targetPath)
{
global $GAPIS;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $GAPIS . 'upload/drive/v2/files?uploadType=media');
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($filename));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Content-Type : application/pdf', 'Content-Length:' . filesize($filename),
'Authorization: Bearer ' . getAccessToken($credentials))
);
$postResult = curl_exec($ch);
curl_close($ch);
return json_decode($postResult, true);
}
function getStoredCredentials($path)
{
$credentials = json_decode(file_get_contents($path), true);
if (isset($credentials['refresh_token']))
return $credentials;
$expire_date = new DateTime();
$expire_date->setTimestamp($credentials['created']);
$expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));
$current_time = new DateTime();
if ($current_time->getTimestamp() >= $expire_date->getTimestamp())
{
$credentials = null;
unlink($path);
}
return $credentials;
}
function storeCredentials($path, $credentials)
{
$credentials['created'] = (new DateTime())->getTimestamp();
file_put_contents($path, json_encode($credentials));
return $credentials;
}
function requestAuthCode()
{
global $GOAUTH, $CLIENT_ID, $REDIRECT_URI, $SCOPES;
$url = sprintf($GOAUTH . 'auth?scope=%s&redirect_uri=%s&response_type=code&client_id=%s&approval_prompt=force&access_type=offline',
urlencode(implode(' ', $SCOPES)), urlencode($REDIRECT_URI), urlencode($CLIENT_ID)
);
header('Location:' . $url);
}
function requestAccessToken($access_code)
{
global $GOAUTH, $CLIENT_ID, $CLIENT_SECRET, $REDIRECT_URI;
$url = $GOAUTH . 'token';
$post_fields = 'code=' . $access_code . '&client_id=' . urlencode($CLIENT_ID) . '&client_secret=' . urlencode($CLIENT_SECRET)
. '&redirect_uri=' . urlencode($REDIRECT_URI) . '&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
function getAccessToken($credentials)
{
$expire_date = new DateTime();
$expire_date->setTimestamp($credentials['created']);
$expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));
$current_time = new DateTime();
if ($current_time->getTimestamp() >= $expire_date->getTimestamp())
return $credentials['refresh_token'];
else
return $credentials['access_token'];
}
function authenticate()
{
global $STORE_PATH;
if (file_exists($STORE_PATH))
$credentials = getStoredCredentials($STORE_PATH);
else
$credentials = null;
if (!(isset($_GET['code']) || isset($credentials)))
requestAuthCode();
if (!isset($credentials))
$credentials = requestAccessToken($_GET['code']);
if (isset($credentials) && isset($credentials['access_token']) && !file_exists($STORE_PATH))
$credentials = storeCredentials($STORE_PATH, $credentials);
return $credentials;
}
$credentials = authenticate();
$result = uploadFile($credentials, 'example.pdf', '');
if (!isset($result['id']))
throw new Exception(print_r($result));
else
echo 'File copied successfuly (file Id: ' . $result['id'] . ')';
echo '<pre>'; print_r($result);
going by https://developers.google.com/drive/api/v3/simple-upload , this should work:
<?php
$ch = curl_init ();
curl_setopt_array ( $ch, array (
CURLOPT_URL => 'https://www.googleapis.com/upload/drive/v3/files?uploadType=media',
CURLOPT_HTTPHEADER => array (
'Content-Type: application/pdf', // todo: runtime detection?
'Authorization: Bearer [YOUR_AUTH_TOKEN]'
),
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => file_get_contents ( '/path/to/file.pdf' ),
CURLOPT_RETURNTRANSFER => 1
) );
try {
if (false === ($resp = curl_exec ( $ch ))) {
throw new \RuntimeException ( 'curl error ' . curl_errno ( $ch ) . ": " . curl_error ( $ch ) );
}
$parsed = json_decode ( $resp, true );
if (! $parsed || $parsed ['code'] !== 200) {
throw new \RuntimeException ( 'google api error: ' . $resp );
}
} finally{
curl_close ( $ch );
}
var_dump($resp);
I am still not completely sure i understand your question. Assuming you just want to upload a file in php or curl here are two options.
Uploading to Google drive is in two parts the first part you create the meta data that being the file name and basic information about your fine. The second part is where you upload the actual data of your file.
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => 'My Report',
'mimeType' => 'application/vnd.google-apps.spreadsheet'));
$content = file_get_contents('files/report.csv');
$file = $driveService->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => 'text/csv',
'uploadType' => 'multipart',
'fields' => 'id'));
printf("File ID: %s\n", $file->id);
Code ripped from media upload
If you want to do this in curl inserting the meta data shouldnt be an issue your issue will be uploading the file itself. You will need to POST the metadata to create the empty file and capture its file-id. Then use the file-id for a content upload. You can find more information on the requests you will nee dot make here simple upload request.
The code will probably look something like this but again your going to have to pass the file id.
curl
--silent
--request POST
--data-binary "#c:\temp\myfile.jpg"
-OL MyFolder\myfile2.jpeg
-H "Slug: myfile3.jpg"
-H "Authorization: Bearer [your access token here]"
-H "Content-Type: image/jpeg {"fileid":"1234"}"
"https://www.googleapis.com/upload/drive/v3/files?uploadType=media"
Note i have not tested the upload in curl this is just a guess.
You can use Logic Apps to send the file from Azure Blob storage to Google Drive as well as an email attachment.
https://learn.microsoft.com/en-us/azure/connectors/connectors-create-api-azureblobstorage
Alternatively files stored in Azure Blobs can be addresses with a public URL assuming you have the right permissions set on the container and/or blob.
I tried to download a file via Icecat. The file need an access to be downloaded.
My problem is :
the file_get_content does'nt download the file. My directory is on 777 and the path is correct.
if I insert the document inside the directory, the file is not unzipped.
public function getIceCatFile() {
set_time_limit (0);
$url = 'https://data.Icecat.biz/export/freexml/EN/daily.index.xml.gz';
$context = stream_context_create(array('http' => array( 'header' => "Authorization: Basic " . base64_encode($this->username . ":" . $this->password) )));
if ($this->checkDirectoryIceCat() === true) {
// does'nt download the file inside the server directory
file_get_contents($url, true, $context);
$file = $this->IceCatDirectory . 'daily.index.xml.gz';
if (is_file($file)) {
$zip = new \ZipArchive;
// error failed same if I include the file inside the directory
$icecat_file = $zip->open($this->IceCatDirectory . 'files.index.xml.gz');
if ($icecat_file === true) {
$zip->extractTo($icecat_file);
$zip->close();
echo 'file downloaded and unzipped';
} else {
echo 'failed';
}
} else {
echo 'error no file found in ' . $file;
}
}
}
Make a try like this to download file that has username and password authentication using PHP Curl,
$localfile = fopen($file_store_locally, 'wb'); // open with write enable
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $localfile);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "username:password"); // see here for auth
curl_exec($ch);
curl_close($ch);
fclose($localfile); //store file data to local file
I have a PHP script that uploads files into Dropbox. When I run it from command-line as a standalone script, it works perfectly.
However, when I incorporate my code into the larger project, the file fails to upload, cURL returns "errno" 0 (meaning, no cURL errors), and there's no output from Dropbox's API.
Here is the code that works:
$token = '<token>';
$url = "https://content.dropboxapi.com/2/files/upload";
$post_body = file_get_contents("/other/server/url/test.txt");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $token,
'Content-Type: application/octet-stream',
'Dropbox-API-Arg: {"path": "/Dropbox/path/subfolder/test.txt","mode": "add", "autorename": true, "mute": false}'));
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_body);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = json_decode(curl_exec($ch), true);
curl_close($ch);
print_r($data);
.... and here is the broken code:
private function dropbox_uploadFile( $path, $file_source, $file_name = "test1.txt") {
echo "<br /><br />PATH: ". $path . '/' . $file_name . "<br /><br />";
echo "<br /><br />SOURCE: ". $file_source . "<br /><br />";
$token = '<token>';
$url = "https://content.dropboxapi.com/2/files/upload";
$post_body = file_get_contents( $file_source );
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $token,
'Content-Type: application/octet-stream',
'Dropbox-API-Arg: {"path": ' . $path.'/'.$file_name. '","mode": "add", "autorename": true, "mute": false}'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_body);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false); // to prevent cURL error #60
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = json_decode(curl_exec($ch), true);
if( ! $data ) {
echo "<pre>";
print_r(curl_getinfo($ch));
echo "</pre>";
echo "ERROR: " . curl_errno( $ch ) . "<br /><br />";
}
curl_close($ch);
print_r($data);
}
I broke out the API call itself, like this:
$res = curl_exec($ch);
print_r($res);
$data = json_decode($res, true);
That showed me the actual error from the API:
Error in call to API function "files/upload": HTTP header "Dropbox-API-Arg": could not decode input as JSON
For different types of errors, the API will return either plain text or JSON, with the response Content-Type header telling you which. In your code, you were only handling JSON, and json_decode apparently silently fails when it isn't supplied valid JSON.
Anyway, that error indicates the supplied JSON for the upload arguments is itself invalid. The problem seems to be a missing quote at the beginning of the path value, fixed here:
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $token,
'Content-Type: application/octet-stream',
'Dropbox-API-Arg: {"path": "' . $path.'/'.$file_name. '","mode": "add", "autorename": true, "mute": false}'));
I went here trying some tips, and I ma using SWIFT.
Hope can help OTHERS.
After some (hard) mailing with dropbox support...
Error in my case was due to unescaping special chars in path.
If You want to upload:
let unescapedFileName = "αβγ.jpg"
You have to escape:
let unescapedFileName = "αβγ.jpg"
let escapedFileName = DB_asciiEscape(unescapedFileName)
Here an Unit test:
func testUtf8Decode(){
let unescapedFileName = "αβγ.jpg"
let escapedFileName = DB_asciiEscape(unescapedFileName)
print(escapedFileName)
let contains = escapedFileName.contains("\\u03b1\\u03b2\\u03b3")
XCTAssert(contains, "not escaped")
}
where function is:
func DB_asciiEscape(_ s: String) -> String {
let out = s.unicodeScalars.reduce("", { (partialResult: String, char: UnicodeScalar) -> String in
if !char.isASCII {
return partialResult + String(format:"\\u%04x", char.value)
} else {
if (char == "\u{7F}") {
return partialResult + "\\u007f"
} else {
return partialResult + "\(char)"
}
}
})
return out
}
I have the ZF first old function working before but somehow ZF it was failing, and then i made the unittest module.
I am trying to use the google translation v2 but it never works anymore, did Google stop there service for public use or is it PHP Bug or somewhere else confusing very much.
Always returning 403 with both following functions.
Any idea whats going wrong?
<?php
## Test: How to's
/*
$ php tst.php
403
$ curl http://ajax.googleapis.com/ajax/services/language/translate -d "v=1.0&q=dog&langpair=en|ru" -H "Referer: http://google.com"
{"responseData": null, "responseDetails": "Please use Translate v2. See http://code.google.com/apis/language/translate/overview.html", "responseStatus": 403}sun#sun-M14xR2:/var/www/html/vooyz.com/unittest$
*/
// V1 - Old not working
function googleTranslatePostV1($text, $destLang = 'nl', $srcLang = 'en') {
$url = 'http://ajax.googleapis.com/ajax/services/language/translate';
$http_response = '';
$text = urlencode($text);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_REFERER, !empty($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : "");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "v=1.0&q=" . $text . "&langpair=$srcLang|$destLang");
$http_response = curl_exec($ch);
$json = json_decode($http_response, true);
if ($json['responseStatus'] != '200') {
return $json['responseStatus'];
} else {
return $json['responseData']['translatedText'];
}
curl_close($ch);
}
// V2 - Curl way not working
function googleTranslatePostV2($text, $destLang = 'nl', $srcLang = 'en') {
$url = 'https://www.googleapis.com/language/translate/v2';
$http_response = '';
$text = urlencode($text);
$postArr = array('key' => 'sdfdsfdsfds',
'q' => $text,
'source' => $srcLang,
'target' => $destLang);
$ch = curl_init();
//curl_setopt($ch, CURLOPT_POSTFIELDS,'hl=en&ie=UTF8&text=-->this+is+a+test<--&langpair=en%7Car');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_REFERER, !empty($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : "");
curl_setopt($ch, CURLOPT_POST,true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$postArr);
$http_response = curl_exec($ch);
var_dump($http_response);
$json = json_decode($http_response, true);
if ($json['responseStatus'] != '200') {
return $json['responseStatus'];
} else {
return $json['responseData']['translatedText'];
}
curl_close($ch);
}
// V2 - Google way
function googleTranslateV2Method1($text, $destLang = 'nl', $srcLang = 'en') {
require_once 'google/src/Google_Client.php';
require_once 'google/src/contrib/Google_TranslateService.php';
$client = new Google_Client();
$client->setApplicationName('Google Translate PHP Starter Application');
$client->setDeveloperKey('dsfdsfdsf');
$service = new Google_TranslateService($client);
//$langs = $service->languages->listLanguages();
//print "<h1>Languages</h1><pre>" . print_r($langs, true) . "</pre>";
$translations = $service->translations->listTranslations($text, 'hi');
return $translations;
}
echo googleTranslatePostV1("V1: " . "How are you?") . "\n";
echo googleTranslatePostV2("V2: " . "How are you?") . "\n";
echo googleTranslateV2Method1("V2: " . "How are you?") . "\n";
?>
$ curl http://ajax.googleapis.com/ajax/services/language/translate -d "v=1.0&q=dog&langpair=en|ru" -H "Referer: http://google.com"
{"responseData": null, "responseDetails": "Please use Translate v2. See http://code.google.com/apis/language/translate/overview.html", "responseStatus": 403}
http://code.google.com/apis/language/translate/overview.html : Google
Translate API is available as a paid service. See the Pricing and FAQ
pages for details.