im a beginer and i traying to upload files to dropbox using dropbox-sdk-php
this is the code that I am using
live test : http://test.dedragon.net
$dropboxKey ='MY_KEY';
$dropboxSecret ='MY_SECRET';
$appName='MY_APPNAME';
$acessToken = "MY_ACCESTOKEN";
set_error_handler('error');
$appInfo = new Dropbox\AppInfo($dropboxKey,$dropboxSecret);
//Store CSRF token
$csrfTokenStore = new Dropbox\ArrayEntryStore($_SESSION['k6'],'dropbox-auth');
//define auth details
$webAuth = new Dropbox\WebAuth($appInfo,$appName,'http://test.dedragon.net',$csrfTokenStore);
$client = new Dropbox\client($acessToken,$appName,'UTF-8');
//time to upload file
if (!empty($_FILES)) {
$nombre = uniqid();
$tempFile = $_FILES['file']['tmp_name'];
$f = fopen($_FILES['file']['tmp_name'], "rb");
$ext = explode(".", $_FILES['file']['name']);
$ext =end($ext);
$nombredropbox = "/". $nombre .'.'.$ext;
$tama = explode(".", $_FILES['file']['size']);
try{
$client->uploadFile($nombredropbox,Dropbox\WriteMode::add(),$f);
}catch(Dropbox\Exception_InvalidAccessToken $e){
error('001',$e);
}
}
function error($numero,$texto){
$ddf = fopen('error.log','a');
fwrite($ddf,"[".date("r")."] Error $numero: $texto\r\n");
fclose($ddf);
}
shows me Status Code: 500
and Error appear
[05-Jun-2019 09:08:13 UTC] PHP Fatal error: Uncaught Dropbox\Exception_BadRequest: HTTP status 400
{"error": "v1_retired"} in /home/jjddqqslmq4q/public_html/test/terceros/dropbox/vendor/dropbox/dropbox-sdk/lib/Dropbox/RequestUtil.php:250
Stack trace:
#0 /home/jjddqqslmq4q/public_html/test/terceros/dropbox/vendor/dropbox/dropbox-sdk/lib/Dropbox/Client.php(558): Dropbox\RequestUtil::unexpectedStatus(Object(Dropbox\HttpResponse))
#1 /home/jjddqqslmq4q/public_html/test/terceros/dropbox/vendor/dropbox/dropbox-sdk/lib/Dropbox/Client.php(423): Dropbox\Client->chunkedUploadStart('%PDF-1.5\r\n%\xB5\xB5\xB5\xB5...')
#2 /home/jjddqqslmq4q/public_html/test/terceros/dropbox/vendor/dropbox/dropbox-sdk/lib/Dropbox/RequestUtil.php(279): Dropbox\Client->Dropbox\{closure}()
#3 /home/jjddqqslmq4q/public_html/test/terceros/dropbox/vendor/dropbox/dropbox-sdk/lib/Dropbox/Client.php(424): Dropbox\RequestUtil::runWithRetry(3, Object(Closure))
#4 /home/jjddqqslmq4q/public_html/test/terceros/dropbox/vendor/dropbox/dropbox-sdk/lib/Dropbox/Client.php(286): Dropbox\Client->_upload in /home/jjddqqslmq4q/public_html/test/terceros/dropbox/vendor/dropbox/dropbox-sdk/lib/Dropbox/RequestUtil.php on line 250
[05-Jun-2019 09:11:52 UTC] PHP Fatal error: Uncaught Dropbox\Exception_BadRequest: HTTP status 400
I changed the SDK to https://github.com/kunalvarma05/dropbox-php-sdk.
<?php
require_once("terceros/dropbox/vendor/autoload.php");
use Kunnu\Dropbox\Dropbox;
use Kunnu\Dropbox\DropboxApp;
use Kunnu\Dropbox\DropboxFile;
$dropboxKey ='MY_KEY';
$dropboxSecret ='MY_SECRET';
$acessToken = "MY_TOKEN";
set_error_handler('error');
$app = new DropboxApp($dropboxKey,$dropboxSecret,$acessToken);
$dropbox = new Dropbox($app);
if (!empty($_FILES)) {
$nombre = uniqid();
$tempFile = $_FILES['file']['tmp_name'];
$ext = explode(".", $_FILES['file']['name']);
$ext =end($ext);
$nombredropbox = "/". $nombre .'.'.$ext;
TRY{
$file = $dropbox->simpleUpload($tempFile,$nombredropbox, ['autorename' => true]);
//Uploaded File
}CATCH(\EXCEPTION $E){
ERROR('001',$E);
}
}
function error($numero,$texto){
$ddf = fopen('error.log','a');
fwrite($ddf,"[".date("r")."] Error $numero: $texto\r\n");
fclose($ddf);
}
?>
Related
After everything was created in Google Cloud below code was written to upload images from my server to google cloud but i am getting error with google storage class
My upload_gcs.php code below
require 'vendor/autoload.php';
use Google\Cloud\Storage\StorageClient;
use Google\Cloud\Core\Exception\GoogleException;
if (isset($_FILES) && $_FILES['file']['error']== 0) {
$allowed = array ('png', 'jpg', 'gif', 'jpeg');
$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if (!in_array(strtolower ($ext), $allowed)) {
echo 'The file is not an image.';
die;
}
$projectId = 'photo-upload-205311';
$storage = new StorageClient ([
'projectId' => $projectId,
'keyFilePath' => 'Photo Upload-3af18f61531c.json'
]);
$bucketName = 'photo-upload-205311.appspot.com';
$bucket = $storage->bucket($bucketName);
$uploader = $bucket-> getResumableUploader (
fopen ($_FILES['file']['tmp_name'], 'r'),[
'name' => 'images/load_image.png',
'predefinedAcl' => 'publicRead',
]);
try {
$uploader-> upload ();
echo 'File Uploaded';
} catch (GoogleException $ex) {
$resumeUri = $uploader->getResumeUri();
$object = $uploader->resume($resumeUri);
echo 'No File Uploaded';
}
}
else {
echo 'No File Uploaded';
}
Error which i am getting is below
> Warning: The use statement with non-compound name
> 'GoogleCloudStorageStorageClient' has no effect in upload_gcs.php on
> line 4
>
> Fatal error: Class 'StorageClient' not found in upload_gcs.php on line
> 16
Is my process correct or are there any other ways to upload image from my server to google cloud storage.
The correct namespace for the script has to be used otherwise it's unresolvable. See correction below.
<?php
require 'vendor/autoload.php';
use Google\Cloud\Storage\StorageClient;
use Google\Cloud\Core\Exception\GoogleException;
class GCPStorage {
function __construct()
{
$projectId = '<your-project-id>';
$bucketName = '<your-bucket-name>';
$storage = new StorageClient([
'projectId' => $projectId,
'keyFilePath' => '<your-service-account-key-file>'
]);
$this->bucket = $storage->bucket($bucketName);
}
function uploadToBucket()
{
if(/your-precondition/) {
return 'No File Uploaded';
}
$uploadedFileLocation = $_FILES['file']['tmp_name'];
$uploader = $this->bucket->getResumableUploader(
fopen($uploadedFileLocation, 'r'),
['name' => 'images/file.txt', 'predefinedAcl' => 'publicRead']
);
try {
$object = $uploader->upload();
} catch(GoogleException $ex) {
$resumeUri = $uploader->getResumeUri();
try {
$object = $uploader->resume($resumeUri);
} catch(GoogleException $ex) {
return 'No File Uploaded';
}
} finally {
return 'File Uploaded';
}
}
}
$gcpStorage = new GCPStorage;
echo $gcpStorage->uploadToBucket();
A small suggestion: assert your precondition early as a guard clause by returning early when it fails.
Following the instructions for these topics:
https://github.com/google/google-api-php-client/issues/788
https://developers.google.com/api-client-library/php/guide/media_upload
I tried to fix the problem below and upload files to Google Drive:
Fatal error: Uncaught GuzzleHttp\Exception\RequestException: cURL error 60: SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed (see http://curl.haxx.se/libcurl/c/libcurl-errors.html) in /secret/public_html/v5/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php:187 Stack trace: #0 /secret/public_html/v5/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php(150): GuzzleHttp\Handler\CurlFactory::createRejection(Object(GuzzleHttp\Handler\EasyHandle), Array) #1 /secret/public_html/v5/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php(103): GuzzleHttp\Handler\CurlFactory::finishError(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory)) #2 /secret/public_html/v5/vendor/guzzlehttp/guzzle/src/Handler/CurlHandler.php(43): GuzzleHttp\Handler\CurlFactory::fin in /secret/public_html/v5/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php on line 187
Using the APIs in PHP, when the file is less than 5 MB, it does not show the error, however, files larger than this generate the above error. Is the problem the API or the certificate? Even installing it on my linux server the error continues, does anyone know how to fix this problem? Or have you ever faced something like that?
Here is the code I'm using to upload up to 5 MB that is working.
<?php
$client = new Google_Client();
$client->setAuthConfig("client_secret.json");
$client->setIncludeGrantedScopes(true);
$client->setAccessType("offline");
$client->setAccessToken($access_token);
$drive_service = new Google_Service_Drive($client);
$mime_type = mime_content_type($uploadfile);
$file = new Google_Service_Drive_DriveFile();
$result = $drive_service->files->create($file, array(
"data" => file_get_contents($uploadfile),
"mimeType" => $mime_type,
"uploadType" => "media"
));
Following is the code I'm using to upload a larger 5 MB that is not working.
<?php
$client = new Google_Client();
$client->setAuthConfig("client_secret.json");
$client->setIncludeGrantedScopes(true);
$client->setAccessType("offline");
$client->setAccessToken($access_token);
$drive_service = new Google_Service_Drive($client);
$mime_type = mime_content_type($uploadfile);
$file = new Google_Service_Drive_DriveFile();
$file->title = $uploadname;
$chunkSizeBytes = 1 * 1024 * 1024;
$client->setDefer(true);
$request = $drive_service->files->create($file); // insert
$media = new Google_Http_MediaFileUpload($client, $request, $mime_type, null, true, $chunkSizeBytes);
$media->setFileSize(filesize($uploadfile));
$status = false;
$handle = fopen($uploadfile, "rb");
while (!$status && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
$result = false;
if($status != false) {
$result = $status;
}
fclose($handle);
$client->setDefer(false);
I tried to convert a pdf file to an image.
I check this website, and follow all step instructions.
1.obtain an api license key
2.download the API Class
3.Deploy the php file
4.create my pdf file
But when i run my file happens this error:
ERROR
Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from 'http://apis.pdfaid.com/pdfaidservices/Service1.svc?wsdl' : failed to load external entity "http://apis.pdfaid.com/pdfaidservices/Service1.svc?wsdl" in C:\xampp\htdocs\Web_V2\PdfaidServices.php:128 Stack trace: #0 C:\xampp\htdocs\Web_V2\PdfaidServices.php(128): SoapClient->SoapClient('http://apis.pdf...', Array) #1 C:\xampp\htdocs\Web_V2\teste_1.php(32): Pdf2Jpg->Pdf2Jpg() #2 {main} thrown in C:\xampp\htdocs\Web_V2\PdfaidServices.php on line 128
The part of the bold code is where raises the error
Could anyone help me please?
I would forever gratefull.
This is my file
<?php
include 'PdfaidServices.php';
$myPdf2Jpg = new Pdf2Jpg();
$myPdf2Jpg->apiKey = "xxxxxxxxxx";
$myPdf2Jpg->inputPdfLocation = "pdf_file.pdf";
$myPdf2Jpg->outputZipLocation = "UploadedPdf/pdf2jpg.zip";
$myPdf2Jpg->outputImageFormat = ".jpg";
$myPdf2Jpg->imageQuality = 50;
$result = $myPdf2Jpg->Pdf2Jpg();
?>
This is API Class PdfaidServices.php where erros happens
<?php
class Xps2PdfConverter
{
public $apiKey = "";
public $inputXpsLocation = "";
public $outputPdfLocation = "";
public $pdfAuthor = "";
public $pdfTitle = "";
public $pdfSubject = "";
public $pdfKeywords = "";
function Xps2PdfConvert()
{
if($this->apiKey == "")
return "Please specify ApiKey";
if($this->outputPdfLocation == "")
return "Please specify location to save output Pdf";
if($this->inputXpsLocation == "")
return "Please specify input XPS file Location";
else
{
$fileStream = file_get_contents($this->inputXpsLocation);
}
$parameters = array("FileByteStream" => $fileStream);
$wsdl = "http://apis.pdfaid.com/pdfaidservices/Service1.svc?wsdl";
$endpoint = "http://apis.pdfaid.com/pdfaidservices/Service1.svc";
$option=array('trace'=>1);
$client = new SoapClient($wsdl, $option);
$headers[] = new SoapHeader('http://tempuri.org/', 'apikey', $this->apiKey);
$headers[] = new SoapHeader('http://tempuri.org/', 'pdfTitle', $this->pdfTitle);
$headers[] = new SoapHeader('http://tempuri.org/', 'pdfAuthor', $this->pdfAuthor);
$headers[] = new SoapHeader('http://tempuri.org/', 'pdfSubject', $this->pdfSubject);
$headers[] = new SoapHeader('http://tempuri.org/', 'pdfKeywords', $this->pdfKeywords);
$headers[] = new SoapHeader('http://tempuri.org/', 'responseResult', "test");
$client->__setSoapHeaders($headers);
$result = $client->Xps2Pdf($parameters);
$clientResponse = $client->__getLastResponse();
if($clientResponse == "APINOK")
return "API is not Valid";
if($clientResponse == "NOK")
return "Error Occured";
else
{
$fp = fopen($this->outputPdfLocation, 'wb');
fwrite($fp, $result->FileByteStream);
fclose($fp);
return "OK";
}
}
}
class Pdf2Jpg
{
public $apiKey = "";
public $outputImageFormat = "";
public $inputPdfLocation = "";
public $outputZipLocation = "";
public $imageQuality = 50;
function Pdf2Jpg()
{
if($this->apiKey == "")
return "Please specify ApiKey";
if($this->outputImageFormat == "")
return "Please specify Output Image Format";
if($this->outputZipLocation == "")
return "Please specify Output Zip File Location";
if($this->inputPdfLocation == "")
return "Please specify input Pdf file Location";
else
{
$fileStream = file_get_contents($this->inputPdfLocation);
}
$parameters = array("FileByteStream" => $fileStream);
$wsdl = "http://apis.pdfaid.com/pdfaidservices/Service1.svc?wsdl";
$endpoint = "http://apis.pdfaid.com/pdfaidservices/Service1.svc";
$option=array('trace'=>1);
$client = new SoapClient($wsdl, $option);
$headers[] = new SoapHeader('http://tempuri.org/', 'apikey', $this->apiKey);
$headers[] = new SoapHeader('http://tempuri.org/', 'outputFormat', $this->outputImageFormat);
$headers[] = new SoapHeader('http://tempuri.org/', 'imageQuality', $this->imageQuality);
$headers[] = new SoapHeader('http://tempuri.org/', 'responseResult', "test");
$client->__setSoapHeaders($headers);
$result = $client->Pdf2Jpg($parameters);
$clientResponse = $client->__getLastResponse();
if($clientResponse == "APINOK")
return "API is not Valid";
if($clientResponse == "NOK")
return "Error Occured";
else
{
$fp = fopen($this->outputZipLocation, 'wb');
fwrite($fp, $result->FileByteStream);
fclose($fp);
return "OK";
}
}
}
?>
Please!! Someone can help me please?
Works fine from my machine. Do you have network connectivity to the said wsdl? What happens when you stick that wsdl URL in a browser?
I have some code created, which uploads a sample file and then should give the shareable url back, but it gives an error:
Fatal error: Call to undefined function createShareableLink() in /home/u983866586/public_html/db/dropbox.php on line 52
My code:
# Include the Dropbox SDK libraries
require_once "Dropbox/autoload.php";
use \Dropbox as dbx;
$appInfo = dbx\AppInfo::loadFromJsonFile("keys.json");
$webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0");
$authorizeUrl = $webAuth->start();
$authCode = "something";
$accessToken= "M4OYlxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
$dbxClient = new dbx\Client($accessToken, "PHP-Example/1.0");
$accountInfo = $dbxClient->getAccountInfo();
//~ print_r($accountInfo);
$f = fopen("working-draft.txt", "rb");
$result = $dbxClient->uploadFile("/working-draft.txt", dbx\WriteMode::add(), $f);
fclose($f);
//~ print_r($result);
$folderMetadata = $dbxClient->getMetadataWithChildren("/");
print_r($folderMetadata);
$f = fopen("working-draft.txt", "w+b");
$fileMetadata = $dbxClient->getFile("/working-draft.txt", $f);
fclose($f);
createShareableLink("/working-draft.txt");
The function createSareableLink is from: http://dropbox.github.io/dropbox-sdk-php/api-docs/v1.1.x/source-class-Dropbox.Client.html#1007-1038
but it is not working.
Arend-Jan
I think you just forgot to use "$dbxClient->" before "createShareableLink".
So that should work for you:
$linkToShare = $dbxClient->createShareableLink("/working-draft.txt");
echo $linkToShare;
I have a very small script that uploads and / or update files (wrote this about 1 year ago, borrowed 80% of the lines from the examples)
No major changes in the code since march (using 1.0.0-alpha) but mid-may the file updates stopped working, raising an Internal Server Error , i upgraded to 1.0.4-beta with no success :
PHP Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling PUT https://www.googleapis.com/upload/drive/v2/ [...] (500) Internal Error' in
google-api-php-client-1.0.4-beta/src/Google/Http/REST.php:80
code:
$client->setDefer(true);
$request = $service->files->update($update_id,$file);
$media = new Google_Http_MediaFileUpload(
$client,
$request,
'text/plain',
null,
true,
$chunkSizeBytes
);
$media->setFileSize(filesize($csvfile))
$status = false;
$handle = fopen($csvfile, "rb");
while (!$status && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
File inserts (HTTP POST) are still working (using the same code for uploading the chunks)
any ideas ?
I can update a file ( previously created or copied from a template ) with this code :
(...)
require_once 'src/Google/Client.php';
require_once 'src/Google/Service/Oauth2.php';
require_once 'src/Google/Service/Drive.php';
(...)
$client = new Google_Client();
// set scopes ...
(...)
$GDrive_service = new Google_Service_Drive($client);
(...)
// then I set parameters
(...)
$newTitle = $title ;
$newDescription = $description ;
$newMimeType = 'text/csv' ;
$newFileName = $filename ;
$service = $GDrive_service ;
(...)
$updatedFile = updateFile($service, $fileId, $newTitle, $newDescription, $newMimeType, $newFileName, $newRevision) ;
function updateFile($service, $fileId, $newTitle, $newDescription, $newMimeType, $newFileName, $newRevision) {
try {
// First retrieve the file from the API.
$file = $service->files->get($fileId);
// File's new metadata.
$file->setTitle($newTitle);
$file->setDescription($newDescription);
$file->setMimeType($newMimeType);
// File's new content.
$data = file_get_contents($newFileName);
$convert = 'true' ;
$additionalParams = array(
'uploadType' => 'multipart',
'newRevision' => $newRevision,
'data' => $data,
'mimeType' => $newMimeType,
'convert' => $convert,
);
// Send the request to the API.
$updatedFile = $service->files->update($fileId, $file, $additionalParams);
return $updatedFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
(...)
// this is info of the updated file
$fileId = $updatedFile->getId() ;
// link of file
$cF_link = $updatedFile->alternateLink ;
// pdf version
$enllacos = $updatedFile->exportLinks ;
$cF_PDF_link = $enllacos['application/pdf'] ;
(...)
This code is working with the 1.0.5-beta php client
Sergi