Upload File to Dropbox from User's Machine using PHP API - php

I am newbie to Dropbox API. I have completed the code which upload the file (on my website host) to my Dropbox with a given token. The process runs successfully.
I want to design a page which allows the user select a file (from his/her local machine) and upload directly to my dropbox.
I have an idea that the controller will upload the file to host first then upload to dropbox. However this idea sucks as it takes more time and bandwidth to complete. And I have to delete the file on host after uploading.
This is the code which works on my host:
<?php
require_once "dropbox-sdk/lib/Dropbox/autoload.php";
use \Dropbox as dbx;
$dropbox_config = array(
'key' => 'my key',
'secret' => 'my secret key'
);
$appInfo = dbx\AppInfo::loadFromJson($dropbox_config);
$webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0");
$accessToken = 'my token code is given here';
$dbxClient = new dbx\Client($accessToken, "PHP-Example/1.0");
// Uploading the file
$f = fopen("working-draft.txt", "rb");
$result = $dbxClient->uploadFile("/working-draft.txt", dbx\WriteMode::add(), $f);
fclose($f);
//print_r($result);
// Get file info
$file = $dbxClient->getMetadata('/working-draft.txt');
// sending the direct link:
$dropboxPath = $file['path'];
$pathError = dbx\Path::findError($dropboxPath);
if ($pathError !== null) {
fwrite(STDERR, "Invalid <dropbox-path>: $pathError\n");
die;
}
// The $link is an array!
$link = $dbxClient->createTemporaryDirectLink($dropboxPath);
$dw_link = $link[0]."?dl=1";
echo "Download link: ".$dw_link."<br>";
?>
And I am using Codeigniter

I have an idea that the controller will upload the file to host first then upload to dropbox. However this idea sucks as it takes more time and bandwidth to complete.
Unfortunately, this is the only secure way to do this. Adding a file to your Dropbox requires knowing an OAuth access token for your account, and you can't allow others to know that token. (It would give them control of the account.) So the token needs to be kept secret, on your server. That means the file needs to be uploaded to your server and transferred to Dropbox from there.

Related

Download & Save Zoom Recording in directory by PHP

Some time ago this code was working fine. I was able to download a file into a directory by using a copy command but it stopped working. It is no longer downloading a file. It always creates a 0-byte file.
The code I'm using:
$video_url = 'https://api.zoom.us/rec/download/tJN4d7v5_Ts3HtzD4QSDVqJwW9XoJvms0nUbq_cPnRzhUCMAN1alZrVAN-AD8vw4clXzSccEqqZtfZw_';
$local_file = getcwd() ."/tmp/tmp_file.mp4";
copy($video_url, $local_file);
I have tried various ways to download and save but nothing helps.
Your $video_url returns 302 http response. Try this
$src = 'https://api.zoom.us/rec/download/tJN4d7v5_Ts3HtzD4QSDVqJwW9XoJvms0nUbq_cPnRzhUCMAN1alZrVAN-AD8vw4clXzSccEqqZtfZw_';
$fileName = 'tmp_file.mp4';
$dest = getcwd() . DIRECTORY_SEPARATOR . $fileName;
$ch = curl_init($src);
curl_exec($ch);
if (!curl_errno($ch)) {
$info = curl_getinfo($ch);
$downloadLink = $info['redirect_url'];
}
curl_close($ch);
if($downloadLink) {
copy($downloadLink, $dest);
}
You have to pass the access token in order to download the video recordings
here is the line you will update to pass the access token
curl_setopt($ch,CURLOPT_URL,download_URL?access_token)
As only host is allowed to record and download the meetings. By passing access token you will allow to download the meetings for every user.
Access token is the token you would be generating from JWT.

how to write a google drive download file to a directory using php

Am trying download a google drive files to a directory using the code below. when I run the code it only open the content of the file on the browser as per code below
// authentication google drive goes here
$file = $service->files->get($fileId);
$downloadUrl = $file->getDownloadUrl();
$request = new Google_Http_Request($downloadUrl, 'GET', null, null);
$httpRequest = $service->getClient()->getAuth()->authenticatedRequest($request);
echo $content= $httpRequest->getResponseBody();
Here is how am trying to download it to a directory called destinations
// Open file handle for output.
$content = $service->files->get($fileId, array("alt" => "media"));
// Open file handle for output.
$handle = fopen("/download", "w+");
// Until we have reached the EOF, read 1024 bytes at a time and write to the output file handle.
while (!$content->eof()) {
fwrite($handle, $content->read(1024));
}
fclose($handle);
echo "success";
here is the error i got
Fatal error: Uncaught Error: Call to a member function eof() on string in C:\xampp\htdocs\download.php
You want to download a file from Google Drive to the specific directory using google/apiclient with php.
The files you want to download are yours and/or shared with you.
If my understanding is correct, how about this modification?
Modification point:
Please use getBody() for $content.
$content->getBody()->eof()
$content->getBody()->read(1024)
Modified script:
In this modification, the filename is also retrieved by Drive API and used for saving the downloaded file. If you don't want to use it, please remove the script for it.
$fileId = "###"; // Please set the file ID.
// Retrieve filename.
$file = $service->files->get($fileId);
$fileName = $file->getName();
// Download a file.
$content = $service->files->get($fileId, array("alt" => "media"));
$handle = fopen("./download/".$fileName, "w+"); // Modified
while (!$content->getBody()->eof()) { // Modified
fwrite($handle, $content->getBody()->read(1024)); // Modified
}
fclose($handle);
echo "success";
In above script, the downloaded file is saved to the directory of ./download/.
Note:
When the method of Files: get of Drive API, the files except for Google Docs (Google Spreadsheet, Google Document, Google Slides and so on) can be downloaded. If you want to download Google Docs, please use the method of Files: export. Please be careful this.
So in above modified script, it supposes that you are trying to download the files except for Google Docs.
References:
PHP Quickstart
Download files
Files: get
Files: export
If I misunderstood your question and this was not the result you want, I apologize.

How to rename or move a file in Google Cloud Storage (PHP API)

I am currently trying to rename and/or move a cloud storage file to another name/position, but I can't get it to work. I am using https://github.com/google/google-api-php-client as client, the uploads works fine with:
...
$storageService = new \Google_Service_Storage( $client )
$file = new \Google_Service_Storage_StorageObject()
$file->setName( 'test.txt' );
$storageService->objects->insert(
$bucketName,
$file,
array(
'name' => $filename,
'data' => file_get_contents( $somefile )
)
);
...
So I have tried to change a filename by the $storageObject->objects->update() method, but I cannot find any documentation on this. I used $storageService->objects->get( $bucketName, $fileName ) to get a specific file I wanted to rename (with $file->setName()), but it seems I just cannot pass the file to the objects->update function. Am I doing it wrong?
Ok, it seems I cannot directly rename a file (please correct me if I'm wrong), I could only update the metadata. I managed to get it to work by copying the file to a new filename/destination and then delete the old file. I successfully used $storageService->objects->copy and $storageService->objects->delete for this. This doesn't feels right but at least it works.
As this is not very well documented with google, here a basic example:
//RENAME FILE ON GOOGLE CLOUD STORAGE (GCS)
//Get client and auth token (might vary depending on the way you connect to gcs – here with laravel framework facade)
//DOC: https://cloud.google.com/storage/docs/json_api/v1/json-api-php-samples
//DOC: https://developers.google.com/api-client-library/php/auth/service-accounts
//Laravel Client: https://github.com/pulkitjalan/google-apiclient
//Get google client
$gc = \Google::getClient();
//Get auth token if it is not valid/not there yet
if($gc->isAccessTokenExpired())
$gc->getAuth()->refreshTokenWithAssertion();
//Get google cloud storage service with the client
$gcStorageO = new \Google_Service_Storage($gc);
//GET object at old position ($path)
//DOC: https://cloud.google.com/storage/docs/json_api/v1/objects/get
$oldObj = $gcStorageO->objects->get($bucket, $path);
//COPY desired object from old position ($path) to new position ($newpath)
//DOC: https://cloud.google.com/storage/docs/json_api/v1/objects/copy
$gcStorageO->objects->copy(
$bucket, $path,
$bucket, $newpath,
$oldObj
);
//DELETE old object ($path)
//DOC: https://cloud.google.com/storage/docs/json_api/v1/objects/delete
$gcStorageO->objects->delete($bucket, $path);
I found that when using gcutils in conjunction with PHP, you can execute pretty much every php file command on app engine. Copy, delete, check if file exists.
if(file_exists("gs://$bucket/{$folder}/$old_temp_file")){
$old_path = "gs://$bucket/{$folder}/$old_temp_file";
$new_permanent_path = "gs://$bucket/{$folder}/$new_permanent_file";
copy($old_path, $new_permanent_path);
unlink($old_path);
}

php - generate time limited download link for files on another server

I put my files on my VPS and user can direct download all files. but I want to hide my actual file paths and make time limited download links. I googled it and find some solutions but most of them was for files that were on same server and some of them has some coding in VPS side, but i can't write any php code on my VPS because it doesn't support php.
also I try some script that works well but generated link wasn't resumable and didn't show file size until download finished. How can I solve these problems?
You could use mod_auth_token (http://code.google.com/p/mod-auth-token/) apache module, if you are running apache as web frontend.
This is how you can handle the PHP side of the token generation process:
<?php
// Settings to generate the URI
$secret = "secret string"; // Same as AuthTokenSecret
$protectedPath = "/downloads/"; // Same as AuthTokenPrefix
$ipLimitation = false; // Same as AuthTokenLimitByIp
$hexTime = dechex(time()); // Time in Hexadecimal
//$hexTime = dechex(time()+120); // Link available after 2 minutes
$fileName = "/file_to_protect.txt"; // The file to access
// Let's generate the token depending if we set AuthTokenLimitByIp
if ($ipLimitation) {
$token = md5($secret . $fileName . $hexTime . $_SERVER['REMOTE_ADDR']);
}
else {
$token = md5($secret . $fileName. $hexTime);
}
// We build the url
$url = $protectedPath . $token. "/" . $hexTime . $fileName;
echo $url;
?>
If you cant make changes to the actual downloadlinks they will stay available for download until they are deleted from the server.
Of course you can make a Script which encrypts the download URL based on the system time, but once the user calls them within time he gets the decrypted URL from the script.

How to copy an image to Amazon S3?

I have a problem a copying an image to Amazon S3
I am using the PHP copy function to copy the image from one server to other server ..it works on go-daddy host server. But it doesn't work for S3. Here is the code that is not working:
$strSource =http://img.youtube.com/vi/got6nXcpLGA/hqdefault.jpg
copy($strSource ,$dest);
$dest is my bucket url with folder present to upload images
I am not sure you could copy an image to AWS just like that. I would suggest using a library which talks to the AWS server and then running your commands.
Check this - http://undesigned.org.za/2007/10/22/amazon-s3-php-class
It provides a REST implementation for AWS.
For example, if you want to copy your image, you can do:
$s3 = new S3($awsAccessKey, $awsSecretKey);
$s3->copyObject($srcBucket, $srcName, $bucketName, $saveName, $metaHeaders = array(), $requestHeaders = array());
$awsAccessKey and $awsSecretKey are your secret keys for AWS a/c.
Check it out and hope it helps.
Not sure if you have used the AWS PHP SDK, but the AWS SDKs can come in handy in situations like this. The SDK can be used in conjunction with IAM roles to grant access to your S3 bucket. These are the steps:
Modify your code to use the PHP SDK to upload the files (if needed).
Create an IAM Role and grant the role permission to the needed S3 buckets.
When you start your EC2 instance, specify that you want to use the role.
Then your code will automatically use the permissions that you grant that role. IAM gives the instance temporary credentials that the SDK uses. These credentials are automatically rotated for you by IAM and EC2.
Here is my examnple from the documentation to copy an object in S3 Bucket
public function copyObject($sSourceKey, $sDestKey)
{
$this->checkKey($sSourceKey);
$this->checkKey($sDestKey);
$bRet = false;
// http://docs.aws.amazon.com/aws-sdk-php-2/latest/class-Aws.S3.S3Client.html#_copyObject
try {
$response = $this->_oS3Client->copyObject(
array(
'Bucket' => $this->getBucketName(),
'Key' => $sDestKey,
'CopySource' => urlencode($this->getBucketName() . '/' . $sSourceKey),
)
);
if (isset($response['LastModified'])) {
$bRet = true;
}
} catch (Exception $e) {
$GLOBALS['error'] = 1;
$GLOBALS["info_msg"][] = __METHOD__ . ' ' . $e->getMessage();
$bRet = false;
}
return $bRet;
}

Categories