Giter Club home page Giter Club logo

cloudconvert-php's Introduction

cloudconvert-php

This is the official PHP SDK for the CloudConvert API v2.

Tests Latest Stable Version Total Downloads

Install

To install the PHP SDK you will need to be using Composer in your project.

Install the SDK alongside Guzzle:

composer require cloudconvert/cloudconvert-php guzzlehttp/guzzle

This package is not tied to any specific HTTP client by using PSR-7, PSR-17, PSR-18, and HTTPlug. Therefore, you will also need to install packages that provide psr/http-client-implementation and psr/http-factory-implementation (for example Guzzle).

Creating Jobs

use \CloudConvert\CloudConvert;
use \CloudConvert\Models\Job;
use \CloudConvert\Models\Task;


$cloudconvert = new CloudConvert([
    'api_key' => 'API_KEY',
    'sandbox' => false
]);


$job = (new Job())
    ->setTag('myjob-1')
    ->addTask(
        (new Task('import/url', 'import-my-file'))
            ->set('url','https://my-url')
    )
    ->addTask(
        (new Task('convert', 'convert-my-file'))
            ->set('input', 'import-my-file')
            ->set('output_format', 'pdf')
            ->set('some_other_option', 'value')
    )
    ->addTask(
        (new Task('export/url', 'export-my-file'))
            ->set('input', 'convert-my-file')
    );

$cloudconvert->jobs()->create($job)

You can use the CloudConvert Job Builder to see the available options for the various task types.

Uploading Files

Uploads to CloudConvert are done via import/upload tasks (see the docs). This SDK offers a convenient upload method:

use \CloudConvert\Models\Job;
use \CloudConvert\Models\Task;


$job = (new Job())
    ->addTask(new Task('import/upload','upload-my-file'))
    ->addTask(
        (new Task('convert', 'convert-my-file'))
            ->set('input', 'upload-my-file')
            ->set('output_format', 'pdf')
    )
    ->addTask(
        (new Task('export/url', 'export-my-file'))
            ->set('input', 'convert-my-file')
    );

$job = $cloudconvert->jobs()->create($job);

$uploadTask = $job->getTasks()->whereName('upload-my-file')[0];

$cloudconvert->tasks()->upload($uploadTask, fopen('./file.pdf', 'r'), 'file.pdf');

The upload() method accepts a string, PHP resource or PSR-7 StreamInterface as second parameter.

You can also directly allow clients to upload files to CloudConvert:

<form action="<?=$uploadTask->getResult()->form->url?>"
      method="POST"
      enctype="multipart/form-data">
    <? foreach ((array)$uploadTask->getResult()->form->parameters as $parameter => $value) { ?>
        <input type="hidden" name="<?=$parameter?>" value="<?=$value?>">
    <? } ?>
    <input type="file" name="file">
    <input type="submit">
</form>

Downloading Files

CloudConvert can generate public URLs for using export/url tasks. You can use the PHP SDK to download the output files when the Job is finished.

$cloudconvert->jobs()->wait($job); // Wait for job completion

foreach ($job->getExportUrls() as $file) {

    $source = $cloudconvert->getHttpTransport()->download($file->url)->detach();
    $dest = fopen('output/' . $file->filename, 'w');
    
    stream_copy_to_stream($source, $dest);

}

The download() method returns a PSR-7 StreamInterface, which can be used as a PHP resource using detach().

Webhooks

Webhooks can be created on the CloudConvert Dashboard and you can also find the required signing secret there.

$cloudconvert = new CloudConvert([
    'api_key' => 'API_KEY',
    'sandbox' => false
]);

$signingSecret = '...'; // You can find it in your webhook settings

$payload = @file_get_contents('php://input');
$signature = $_SERVER['HTTP_CLOUDCONVERT_SIGNATURE'];

try {
    $webhookEvent = $cloudconvert->webhookHandler()->constructEvent($payload, $signature, $signingSecret);
} catch(\CloudConvert\Exceptions\UnexpectedDataException $e) {
    // Invalid payload
    http_response_code(400);
    exit();
} catch(\CloudConvert\Exceptions\SignatureVerificationException $e) {
    // Invalid signature
    http_response_code(400);
    exit();
}

$job = $webhookEvent->getJob();

$job->getTag(); // can be used to store an ID

$exportTask = $job->getTasks()
            ->whereStatus(Task::STATUS_FINISHED) // get the task with 'finished' status ...
            ->whereName('export-it')[0];        // ... and with the name 'export-it'
// ...

Alternatively, you can construct a WebhookEvent using a PSR-7 RequestInterface:

$webhookEvent = $cloudconvert->webhookHandler()->constructEventFromRequest($request, $signingSecret);

Signed URLs

Signed URLs allow converting files on demand only using URL query parameters. The PHP SDK allows to generate such URLs. Therefore, you need to obtain a signed URL base and a signing secret on the CloudConvert Dashboard.

$cloudconvert = new CloudConvert([
    'api_key' => 'API_KEY',
    'sandbox' => false
]);

$job = (new Job())
    ->addTask(
        (new Task('import/url', 'import-my-file'))
            ->set('url', 'https://my.url/file.docx')
    )
    ->addTask(
        (new Task('convert', 'convert-my-file'))
            ->set('input', 'import-my-file')
            ->set('output_format', 'pdf')
    )
    ->addTask(
        (new Task('export/url', 'export-my-file'))
            ->set('input', 'convert-my-file')
    );

$signedUrlBase = 'SIGNED_URL_BASE';
$signingSecret = 'SIGNED_URL_SIGNING_SECRET';
$url = $cloudConvert->signedUrlBuilder()->createFromJob($signedUrlBase, $signingSecret, $job, 'CACHE_KEY');

Setting a Region

By default, the region in your account settings is used. Alternatively, you can set a fixed region:

// Pass the region to the constructor
$cloudconvert = new CloudConvert([
    'api_key' => 'API_KEY',
    'sandbox' => false,
    'region'  => 'us-east'
]);

Unit Tests

vendor/bin/phpunit --testsuite unit

Integration Tests

vendor/bin/phpunit --testsuite integration

By default, this runs the integration tests against the Sandbox API with an official CloudConvert account. If you would like to use your own account, you can set your API key using the CLOUDCONVERT_API_KEY enviroment variable. In this case you need to whitelist the following MD5 hashes for Sandbox API (using the CloudConvert dashboard).

53d6fe6b688c31c565907c81de625046  input.pdf
99d4c165f77af02015aa647770286cf9  input.png

Resources

cloudconvert-php's People

Contributors

adrienbrault avatar christiangaertner avatar ethanpooley avatar josiasmontag avatar le-yak avatar les-lim avatar lukassteiner avatar m4tthumphrey avatar mfullbrook avatar otprogram avatar quentint avatar stayallive avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cloudconvert-php's Issues

Upload big files.

Hi,
When i tried to upload(for converting) a big file around 700MB,
$process-> waitForConversion() stopped,while the enconding take more time than 120 sec(default argument to waitForConversion() function ).
How to convert a big file and set script to wait untill it is done for downloading without stopping my script?

The original function is:
public function waitForConversion($timeout = 120) {
$time = 0;
/*
* Check the status every second, up to timeout
*/
while ($time <= $timeout) {
sleep(1);
$time++;
$data = $this -> status();
if ($data -> step == 'error') {
throw new Exception($data -> message);
return false;
} elseif ($data -> step == 'finished' && isset($data -> output) && isset($data -> output -> url)) {
return true;
}
}
throw new Exception('Timeout');
return false;
}

Can modify it like so:
public function waitForConversion() {
$time = 0;
/*
* Check the status every second, up to timeout
*/
while ($time) {
sleep(1);
$time++;
$data = $this -> status();
if ($data -> step == 'error') {
throw new Exception($data -> message);
return false;
} elseif ($data -> step == 'finished' && isset($data -> output) && isset($data -> output -> url)) {
return true;
}
}
throw new Exception('Timeout');
return false;
}

Thanks

PHP Parse error: syntax error, unexpected 'use' (T_USE)

Hi;
I did all steps but I have a error.

PHP Parse error: syntax error, unexpected 'use' (T_USE)

Composer.json

{
"name": "cloudconvert/cloudconvert-php",
"description": "PHP Wrapper for CloudConvert APIs",
"homepage": "https://github.com/cloudconvert/cloudconvert-php",
"authors": [
{
"name": "Josias Montag",
"email": "[email protected]"
}
],
"require": {
"guzzlehttp/guzzle": "6."
},
"require-dev": {
"phpunit/phpunit": "4.0.
",
"phpdocumentor/phpdocumentor": "2.",
"squizlabs/php_codesniffer": "1.
",
"clue/phar-composer": "~1.0"
},
"autoload": {
"psr-4": {"CloudConvert\": "src/"}
}
}

Question

The file are stored for unlimited time, can i share it ?

unexpected 'use' (T_USE)

Hi, i am using cloudconvert for first time.
But i am getting and error "Parse error: syntax error, unexpected 'use' (T_USE)"

My code:

require 'phar://cloudconvert-php.phar/vendor/autoload.php';
use CloudConvert\Api;
$api = new Api("apikey");

I don't know why it is coming this error should i need to include anything else?

How to install this just as a php package

Hi Sorry for the noob question but I have tried to place this in my project just by using require('Api.php') but I get an error on " use \CloudConvert\Api; " Is there another way to do this like...
$Api = new \CloudConvert\Api();
$api = $Api("api-key");

Really interested t try this but I am not familiar with phar etc. Was hoping to jump in and do a quick test.

Upload method fails with very long filepaths

We were seeing conversion failures using the upload() method with filepaths at about 256 characters (approximately).

Additionally specifying the base filename in the CURL request appears to resolve the issue.

Exception when conversion minutes exceeded

Hey,

Is there a possibility the API tells you when your conversion minutes are exceeded? If so, it would be cool if that was a specific exception so I can do something like that:

catch (ConversionMinutesExceededException $e) {
   $this->addError('The images could not be converted because there are no conversion minutes left anymore. Visit https://cloudconvert.com and adjust your plan and buy new minutes!';
}

Danke ;-)

Library missing file

Hi!
I try to use your PHP library directly from Github but there's a missing file (/vendor/autoload.php) in your package.

Can it be installed without composer? If so, how could I proceed?

Thanks!

how to get width/height of a converted video in output callback api ??

hiii Alll,
I just started using cloudconvert service and all conversions are working properly but one thing that i am missing, I am using cloudconvert callback api and i want something like i want default height, width and duration of a converted video after conversion finishes via callback api as a response at the last
Can anybody help me please ??

Fatal error: PayloadTooLargeError: too many parameters

Fatal error: Uncaught exception 'CloudConvert\Exceptions\ApiException' with message 'PayloadTooLargeError: too many parameters' in /home1/talendro/public_html/test/pdfconvert/src/Api.php:148 Stack trace: #0 /home1/talendro/public_html/test/pdfconvert/src/Api.php(169): CloudConvert\Api->rawCall('GET', '//hostq3ua8k.cl...', Array, false) #1 /home1/talendro/public_html/test/pdfconvert/src/ApiObject.php(60): CloudConvert\Api->get('//hostq3ua8k.cl...', Array, false) #2 /home1/talendro/public_html/test/pdfconvert/src/Process.php(105): CloudConvert\ApiObject->refresh(Array) #3 /home1/talendro/public_html/test/pdfconvert/generate.php(54): CloudConvert\Process->wait() #4 {main} thrown in /home1/talendro/public_html/test/pdfconvert/src/Api.php on line 148

Below is my code which I used, please suggest on this which parameter need to be added or removed.

$api = new Api("API_KEY");
$api->convert([
"inputformat" => "$extension",
"outputformat" => "pdf",
"input" => "upload",
"file" => fopen('upload/docs/'.$newfilename, 'r'),
])
->wait()
->download();

Note : It is working fine in localhost when run in same code in server its being comes above error thank you for advance.

help

Can you tell me how cloudconvert works?

Tried to get contents through url but ended up with No such file or directory

Hi,
Thanks for the reply.

I tried what you asked me to do.
i.e.
$html = file_get_contents($process->output->url);

But i get this
file_get_contents(//host123d1qi.cloudconvert.com/download/~1PUC9D6lRgRKIuQNorl-qw86llQ): failed to open stream: No such file or directory

Here is how i am doing it .

       $api = new Api("****API KEY***");

$process = $api->createProcess([
    'inputformat' => $inputFormat,
    'outputformat' => $outputformat
]);

$process->start([
    'outputformat' => $outputformat,
    'converteroptions' => [
        'quality' => 75,
    ],
    'input' => 'download',
    'file' => $file,
    'callback' => URL::to('/download')

]);
echo "converted";
$html = file_get_contents($process->output->url);
var_dump($html);
die();

Using new API in CakePHP

Hello

First of all thanks for a great utility. I can't tell you how much I use it and love it. I am integrating with your service from a PHP application that is built using CAKEPHP 2.5.4

To begin with I used your legacy CloudConvert.class.php and it worked wonderfully and still continues to do so. However, I noticed you have published a newer version that uses Guzzle etc. I am unfamiliar with Guzzle and also when I try and include your classes in my application I get some compilation errors in Api.php, ApiObject.php etc.

Do you have any advice on

  1. How to integrate seamlessly with CakePHP?
  2. If I do intend to use the newer version if I should download Guzzle as well?

Unable to install using composer

Hi,

I'm trying to install cloudconvert-php package on my local system ubuntu 14.04.
To install this package following are the steps that I've done.

  1. Created project directory in /var/www/htm/ folder named "cloud-convert"
  2. Download cloudconvert-php package and extracted into "cloud-convert" directory
  3. Installed composer globally using https://getcomposer.org/doc/00-intro.md#globally
  4. Run command "composer install"

I did all above but it is throwing an error, Please see attached image for error.
cloud-convert-installation-error

Please guide me if I am missing something.

Thanks In Advance
Atul

Download of converted files fails with large files

The API works fine with smaller files but when I try to upload a 200Mb+ mp4 the process fails.
The file appears locally but only partially downloaded (file size 0 bytes) and the process goes to a 500 error with the message

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 221789177 bytes) in phar:///Sites/website/cloudconvert-php.phar/vendor/guzzlehttp/psr7/src/Stream.php on line 94

I have tried updating my local php.ini to increase the max_filesize and other limits, but the error still occurs.

Use without composer

Can I use cloud convert API without composer? I'm using shared server and it doesn't allow to install composer

Upload file from path

PHP 5.4.27
Is it possible to upload a video file from an existing path instead of having the file in the same folder as the class?
Ex:

$process-> upload("../app_videos/oc_black(1).mp4", "webm" );

Or:

$process-> upload("http://www.domain.com/app_videos/oc_black(1).mp4", "webm" );

Full code:

$apikey="(...my_key...)";
$process = CloudConvert::createProcess("mp4", "webm", $apikey);
$process-> upload("../app_videos/oc_black(1).mp4", "webm" );

if ($process-> waitForConversion()) {
    echo "success";
} else {
    echo "failure";
}

I've tried each one and get this error:
Fatal error: Uncaught exception 'Exception' with message 'couldn't open file "../app_videos/oc_black(1).mp4"' in /(...)/CloudConvert.class.php on line 200

Thank you

api file i can t read

Download doesn't start

Hi,
I'm using the wrapper and Cloudconvert to convert SVG charts to EMF charts. The conversion works and the file gets converted and stored on cloudconvert. But I don't seem to be able to initiate the download.

Here is my code.

convert([ 'inputformat' => 'svg', 'outputformat' => 'emf', 'input' => 'download', "file" => "http://****/operationsChart.svg", "save" => true, "download" => true ]) ->wait() ->download(); ?>

Am I missing something essential?

Fatal error: Class 'CloudConvert\Api' not found

# Fatal error: Class 'CloudConvert\Api' not found in /home/demosoftwarecomp/public_html/UpendraTesting/FileConvert/TestingUploading.php on line 6

I download this file using composer.json and i uploaded to my cpanel server but its notwoking. how i can fix this error.

The api doesn't work or show notification on my user account.โ€

Dear @cloudconvert,
Today I've written code that uses the php wrapper for CloudConvert.org, but it seems that I can't get it to work.
besides that There aren't any signs on my CloudConvert's user dashboard that indicate the use of the mentioned api.

I Also tried Converting with the auto-generated GET request from https://cloudconvert.com/apiconsole, However I mostly encounter the following response:

 {"id":"Gn4NJ3DgbXSyhziKf1tc","url":"//hostprmxl2.cloudconvert.com/process/Gn4NJ3DgbXSyhziKf1tc","percent":-1,"message":"Download from FTP failed (code undefined):
Timeout while connecting to server","step":"error","starttime":1434246957,"expire":1434248767,"input":
{"type":"ftp","filename":"284.docx","name":"284","ext":"docx"},"output":
{},"endtime":1434246967,"minutes":0,"code":400}

I'm attaching my code for further investigation on that matter(the asterisks are used to protect sensitive data:

$api = new Api("***-***************************************************************************");
$api->convert([
    "input" => [
        "ftp" => [
            "host" => "ftp.***********.com",
            "port" => "21",
            "user" => "mxnsnjfc",
            "password" => "********************",
        ],
    ],
    "output" => [
        "ftp" => [
            "host" => "ftp.************.com",
            "port" => "21",
            "user" => "mxnsnjfc",
            "password" => "******************************",
            "path" => "public_html/word/$id/img/",
        ],
    ],
    "inputformat" => $extension,
    "outputformat" => "jpg",
    "file" => "public_html/word/$id/$id.$extension",
])
->wait();

Thanks in advance,
Ed Smith.

CloudConvert takes a lot of time

Hello;
I'm using CloudConvert to convert a .ppt to pdf, and it takes a lot of time(+30 secs) to respond;
how can I reduce this time please? any body can help me!!

Default mode is not "convert"

Hi,

I send the request to API by:

		$process = $this->api->createProcess([
			'inputformat' => 'gif',
		]);

		$process->start([
			'outputformat' => 'mp4'
			'input' => 'download',
			'files' => [
				'http://replygif.net/i/486.gif',
				'http://replygif.net/i/1528.gif'
			],
			'callback' => $callbackUrl,
		]);

And I get to my callback url:

array (
  'id' => 'nwmjWLJDrVyAQc9lpEev',
  'url' => '//host123d1qe.cloudconvert.com/process/nwmjWLJDrVyAQc9lpEev',
  'step' => 'error',
)

The error message is: Conversion type not supported: gif to mp4 (mode archive)

It works when I add 'mode' key with 'convert' value

		$process->start([
			'mode' => 'convert',
			'outputformat' => 'mp4',
			'input' => 'download',
			'files' => [
				'http://replygif.net/i/486.gif',
				'http://replygif.net/i/1528.gif'
			],
			'callback' => $callbackUrl,
		]);

According to the documentation 'convert' is default value.

Just Getting Contents rather than downloading

Hi,
I am trying to convert the doc,docx,pdf.. files to .html file and get contents of html file. I was wondering if we can just get the contents of the file rather than downloading.
Kindly guide me if it is possible.

If it is not possible then i hope we can send the file to s3 for sure. Kindly guide me through this.

Thanks.

Upload to S3 Bucket failed: null

Hi! Im not sure what the problem is. I really cant find what is wrong. All my other s3 fields get parsed to CloudConvert but not my Bucket.

Any thoughts on what might be wrong?

$process = CloudConvert::createProcess("mov", "mp4", Configure::read('CloudConvert.api_key'));
        $process->setOption('output[s3][accesskeyid]', 'myamazonkeyhere');
        $process->setOption('output[s3][secretaccesskey]', 'myawssecrethere');
        $process->setOption('output[s3][bucket]', 'clicksys');
        $process->setOption('output[s3][region]', 'eu-west-1');
        $process->setOption('output[s3][key]', 'ClickReal/');
        $process->setOption('output[s3][acl]', 'public-real');
        $process->setOption('preset', 'Qn0AyRoD7e');
        $process->setOption('download', 'false');
        $process->setOption('filename', basename($this->args[1]));

        $process->upload($this->args[1], "mp4" );
        if ($process->waitForConversion()) {
            debug($process->status());
            $this->out("Conversion done :-)");
        } else {
            $this->out('Something went wrong :-(');
        }

unable to download output file in php

May be i am doing a little mistake, In php i am converting pdf to jpg and i am not getting a particular code for downloading the output file via api reference of cloud convert, for that i create a process and then start a process as referred the api document below is my code:

solution-1

<?php
require __DIR__ . '/vendor/autoload.php';
	use \CloudConvert\Api;
	$api = new Api("***********************");

	$process = $api->createProcess([
		    "inputformat" => "pdf",
		    "outputformat" => "jpg",
		]);
	$process->start([
	    "input" => "download",
	    "file" => "http://myDomainUrl/test.pdf",
	    "output" => [
	        "s3" => [
	            "accesskeyid" => "**************",
	            "bucket" => "***************",
	            "secretaccesskey" => "****************",
	            "region" => "************"
	        ]
	    ],
	    "save" => true
	]);

	while($process->step != "finished" && $process->step != 'error'){
        $process = $process->refresh();
       	var_dump($process->percent);
       	echo "<br>".$process->step;
       	if($process->percent == 100 && $process->step == "finished"){
       		break;
       	}
    }
    die("converted");

above file runs perfectly but it does not download the output file to s3 path that i mentioned, at the end of my code if i check the step it gives me 'finished' and message = file initialized, But i am not getting what parameter should i pass to download it in my code, if i use
$process->download("filename.ext");
so it gives the message that there is not output file for that, But if i use $app->convert() it works for me but i can not use that one, code like below

solution-2

<?php
$api = new Api(****************************);
$api->convert([
	    "input" => "download",
	    "file" => "http://myDomainUrl/test.pdf",
	    "output" => [
	        "s3" => [
	            "accesskeyid" => "**************",
	            "bucket" => "***************",
	            "secretaccesskey" => "****************",
	            "region" => "************"
	        ]
	    ],
	    "save" => true
	]);

By this above code(solution-2) i am getting the output files on s3, How can i get the output files by the solution-1, please help me

Getting problem in animated webp image to jpg

I am converting animated webp image to jpg below is my php code:

<?php
	require __DIR__ . '/vendor/autoload.php';
	use \CloudConvert\Api;
	 
	$api = new Api("**************************");
	 
	$api->convert([
	    "inputformat" => "webp",
	    "outputformat" => "jpg",
	    "input" => "upload",
	    "file" => fopen('inputfile.webp', 'r'),
	])
	->wait()
	->download();
?>

When i am executing it, every time it gives me the error message like
{"error":"convert: no images defined `/data/test_animation.jpg' @ error/convert.c/ConvertImageCommand/3254.\r\n","code":422}

If i convert for static webp format then it works fine but only with animated webp format i am facing this issue, do i have to pass the frame number to convert it or write any command ? please correct me where i am wrong.

Thanks

errors when i uconvert file size more than 60 mb

i have errors when i convert file pdf size 60mb Client error: POST https://eliza.infra.cloudconvert.com/process/505c9db3-08c8-425d-8bd5-bb56ff1a5894 resulted in a 400 Bad Request response: {"id":"505c9db3-08c8-425d-8bd5-bb56ff1a5894","url":"//eliza.infra.cloudconvert.com/process/505c9db3-08c8-425d-8bd5-bb56f (truncated...) How can i fix it this my code public function convertJPG(Request $request) { $files = $request->file('file'); set_time_limit(900); $ConvertPDF = new CloudConvert(); $ConvertPDF->setApiKey('PUJBbPxiTOWUXxiIUIRiv8ftcM8PpzRTxiWK8CLdqUJvalWydIcpl3nCh3YdIzng'); if ($files) { if ($this->checkFilePDF($files)) { $fileJPGs = []; $destinationPath = 'uploads'; foreach ($files as $file) { $fileName = $file->getClientOriginalName(); $file->move($destinationPath, $fileName); $fileJPG = 'uploads/' . str_replace("pdf", "jpg", $fileName); $currentFile = "uploads/" . $fileName; if (file_exists($currentFile)) { $variables = ['name' => 'John Doe', 'address' => 'Wall Street']; $success = $ConvertPDF->file($currentFile)->templating($variables)->to($fileJPG); $success = true; } else { $success = false; } }

Deprecated prefix '@' in upload (PHP 5.5)

Hi! Awesome library and awesome cloudConvert!

I find this problem for php5.5:
in the upload function there's a call to the 'req' private method that use CURLOPT_POSTFIELDS passing args like 'file' => '@'.$filename. The '@' prefix is deprecated in this version and i have to use CURLFILE instead.

Line 77:
replace 'file' => '@'.$filepath
by 'file' => new CURLFile($filepath)

What algorithms used for convert pdf to word?

I am using cloudconvert api for pdf2word for my homeworks at school.
But i would like to understand how converter work? What algo are using in your pdf2word converter?
Thank you.

Convert videos with fixed width and set the height proportionally.

Hi,
I have been used this api for more than a year.But i have to run some test because my videos are not showed well on smart tv.My videos are 16/9 and sometimes on smart tv the picture is stretched.
For now i use this configuration:

$process -> setOption("converteroptions[video_codec]","H264");
$process -> setOption("converteroptions[video_resolution]","768x432");
$process -> setOption("converteroptions[video_ratio]","16:9");
$process -> setOption("converteroptions[video_profile]","baseline");
$process -> setOption("converteroptions[video_profile_level]","3.0");
$process -> setOption("converteroptions[video_crf]","0");
$process -> setOption("converteroptions[faststart]","true");
$process -> setOption("converteroptions[audio_bitrate]","80");
$process -> setOption("converteroptions[audio_channels]","1");
$process -> setOption("converteroptions[audio_codec]","AAC");

Can you tell me how to keep width 768 and let height in proportionally with aspect ratio?
I mean using this api or at least a ffmpeg command(that have all this options) so i can use as a Custom Command in this api.
Thanks

Multiple output files Download not working

According to your documentation Multiple output conversion is not working as mentioned in your API documentation
Getting error

warning invalid argument supplied for foreach()

My code looks like this

<?php
    require __DIR__ . '/vendor/autoload.php';
    use \CloudConvert\Api;
    $api = new Api("APIKEY");
    if(isset($_POST['submit'])){
        $fileName = $_FILES["file"]["name"];
        $fileFormat = end((explode(".", $fileName)));
        $fileBaseName = explode(".", $fileName);
        $requiredFormat = $_POST['required_format'];
        $filePath = $_FILES["file"]["tmp_name"];
        if (!file_exists('original_file')) {
            mkdir('original_file', 0777, true);
        }
        move_uploaded_file($filePath,"original_file/".$fileName);

        $process = $api->createProcess([
            "inputformat" => $fileFormat,
            "outputformat" => $requiredFormat,

        ]);

        $process->start([
            "wait" => true,
            "save"=> true,
            "input" => "upload",
            "file" => fopen("original_file/".$fileName, 'r'),
            "filename" => $fileName,
        "outputformat" => $requiredFormat,
        ]);

               // This is not working
        foreach ($process->output->files as $file) {
            $process->download($fileBaseName[0] . "." . $requiredFormat, $file);
        }
            // or:
                 this is working
        $process->downloadAll('./tests/');

complete code is here

Maybe I am doing anything wrong I want that multiple files zip to be downloaded

Callback Not Working

Dear Team,
Thanks for the awesome plugin. We are trying to implement Callback option for our conversion, but we never got hooked back,
$callback = "http://example.com/converted"

$api = new Api("***"); $process = $api->createProcess([ "inputformat" => "pdf", "outputformat" => "jpg", ]); $process->start([ "outputformat" => "jpg", "converteroptions" => [ "quality" => 75, ], "input" => "upload", "file" => fopen($filePath, "r"), "callback" => $callback ]);

page number not showing in new generated pdf file

Hi ,

Can you please confirm , My DOC file has been converted successful into PDF but not showing the page number in the file . I need to know which parameter need to be added for page number to be shown. below is my code . please help on this.

$api = new Api("XXXXX");
$api->convert([
"inputformat" => "$extension",
"outputformat" => "pdf",
"input" => "upload",

"file" => fopen('upload/docs/'.$newfilename, 'r'),

])
->wait()

->download();

any help would be appreciate

Unable to upload file on S3 with php raw request(curl)

Hello cloudconvert,
I am converting pdf to jpg by downloading the input file from an url(url has public read access) and after conversion i want to upload output jpg files on S3, I am doing the whole process with php raw request(curl), in the response i am getting success in the json response but with the message "message": "Waiting for upload" every time and the process is finishing here without uploading the upload files below is my code:

<?php
	//create process
	$curl = curl_init();
	curl_setopt_array($curl, array(
		CURLOPT_URL => "https://api.cloudconvert.com/process",
		CURLOPT_RETURNTRANSFER => true,
		CURLOPT_ENCODING => "",
		CURLOPT_MAXREDIRS => 10,
		CURLOPT_TIMEOUT => 30,
		CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		CURLOPT_CUSTOMREQUEST => "POST",
		CURLOPT_POSTFIELDS => json_encode(array(
			"inputformat" => "pdf",
			"outputformat" => "jpg"
		)),
		CURLOPT_HTTPHEADER => array(
			"authorization: Bearer ******************",
			"cache-control: no-cache"
		),
	));

	$response = curl_exec($curl);
	$err = curl_error($curl);

	if($err){
	  echo "cURL Error #:" . $err;
	}
	else{
	    $resArr = (array) json_decode($response, true);
		$url = "https:".$resArr["url"];
                //start process
		curl_setopt_array($curl, array(
			CURLOPT_URL => $url,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_ENCODING => "",
			CURLOPT_MAXREDIRS => 10,
			CURLOPT_TIMEOUT => 30,
			CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			CURLOPT_CUSTOMREQUEST => "POST",
			CURLOPT_POSTFIELDS => json_encode(array(
				"input" => "download",
				"file" => "https://myinputUrl.com/item.pdf",  //file has read access
				"outputformat" => "jpg",
				"output" => array(
					"s3" => array(
						"accesskeyid" => "*******",
						"bucket" => "*******",
						"secretaccesskey" => "***********",
						"region" => "*********",
						"acl" => "public-read",
						"path" => "myDirectory/"
					)
				),
				"callback" => "******************",
				"save" => false
			)),
			CURLOPT_HTTPHEADER => array(
				"authorization: Bearer ***************************"
			),
		));

		$response = curl_exec($curl);
		$err = curl_error($curl);
		curl_close($curl);
		if($err){
		  echo "hello error<br>";
		  echo "cURL Error #:" . $err;
		}
		else{
			echo "hello sucess<br>";
		  	echo $response;
		}
	}

My S3 credentials are right, above code response me like below json:

{
    "id": "*************",
    "url": "//*******************",
    "expire": *******,
    "percent": 0,
    "message": "Waiting for upload",
    "step": "input",
    "starttime": *********,
    "output": {
        "url": "//*******/download/~******"
    },
    "input": {
        "type": "upload"  //i am not getting why this type showing me upload as i mentioned above "input":"download"
    },
    "upload": {
        "url": "//*********/upload/~-**********"
    }
}

Please help me where i am wrong, and how can i upload the out files to s3

The cloudconvert api sometimes doesn't work or show a notification on user account

Dear @cloudconvert,
This week our website has encountered a serious problem: The api sometimes doesn't convert files to (.txt and .jpg) or doesn't convert to .jpg. For example: I may upload 1.pdf and get (1.txt and 1.jpg) or 1.txt or nothing(1.pdf talks about the same file).
The php conversion script sometimes takes a very long time to execute, and sometimes the script finishes to execute within seconds from the ajax call.
After waiting for about two minutes I get the following text response and a 500 error:

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<HTML><HEAD>
<TITLE>500 Internal Server Error</TITLE>
</HEAD><BODY>
<H1>Internal Server Error</H1>
The server encountered an internal error or misconfiguration and was unable to complete your request
<HR>
<I>*******.com</I>
</BODY></HTML>

Usually, files are being converted to txt. When a file isn't converted, I get the following error:
Something else went wrong: cURL error 28: See http://curl.haxx.se/libcurl/c/libcurl-errors.html

When a specific conversion succeeds, I sometimes get the following message:
"Something else went wrong: Invalid process ID!"(probably because the process expires).

Furthermore,

 $process->percent //==-1 for some reason..

keeps returning -1(even when the conversion finished with success).

I've attached my php code(a code being called with ajax) here:

<?php
/*
*The following code converts any file to txt.
*/ 
try{
    $api = new Api("***-**************************************");
    $process = $api->createProcess([
        'inputformat' => $extension,
        'outputformat' => 'txt',
    ]);

    $processUrl = $process->url;

    $process->start([
        'outputformat' => 'txt',
        'input' => [
            "ftp" => [
            "host" => "*.***.*.**",
            "port" => "21",
            "user" => "mxnsnjfc",
            "password" => "******************",
            ],
        ],
        "output" => [
            "ftp" => [
            "host" => "*.***.*.**",
            "port" => "21",
            "user" => "mxnsnjfc",
            "password" => "******************",
            "path" => "public_html/word/$id/txt/search.txt",
            ],
        ],
        "file" => "public_html/word/$id/$id.$extension",
    ]);
    //check for percentage of the conversion process.(doesn't work...)
    $process = $process->refresh();
    while($process->step != 'finished' || $process->step != 'error'){
        if($process->step == 'convert'){
            //if file is converting..
        }
        $process = $process->refresh();
    }
        $txt = ".txt finished at: " . date("H:i:s", time());
        $progressFile = fopen("debug/progressFileTxt.txt", "w") or die("Unable to open file!");
        fwrite($progressFile, $txt);
        fclose($progressFile);
}
/*
*The following code checks for errors.
*/
catch (\CloudConvert\Exceptions\ApiBadRequestException $e) {
    $txt = "Something with your request is wrong: " . $e->getMessage() . " \r\n" . date("H:i:s", time());
    $progressFile = fopen("debug/progressFile1.txt", "w") or die("Unable to open file!");
    fwrite($progressFile, $txt);
    fclose($progressFile);
    $script = '<script type="text/javascript">window.location.href="error.php";</script>';
} catch (\CloudConvert\Exceptions\ApiConversionFailedException $e) {
    $txt = "Conversion failed, maybe because of a broken input file: " . $e->getMessage()  ." \r\n" .  date("H:i:s", time());
    $progressFile = fopen("debug/progressFile2.txt", "w") or die("Unable to open file!");
    fwrite($progressFile, $txt);
    fclose($progressFile);
    $script = '<script type="text/javascript">window.location.href="error.php";</script>';
}  catch (\CloudConvert\Exceptions\ApiTemporaryUnavailableException $e) {
    $txt = "API temporary unavailable: " . $e->getMessage() ."\n We should retry the conversion in "  ." \r\n" .  $e->retryAfter . " seconds" . date("H:i:s", time());
    $progressFile = fopen("debug/progressFile3.txt", "w") or die("Unable to open file!");
    fwrite($progressFile, $txt);
    fclose($progressFile);
    $script = '<script type="text/javascript">window.location.href="error.php";</script>';
} catch (Exception $e) {
// network problems, etc..
    $txt = "Something else went wrong: " . $e->getMessage() . "\n"  ." \r\n" .  date("H:i:s", time());
    $progressFile = fopen("debug/progressFile4.txt", "w") or die("Unable to open file!");
    fwrite($progressFile, $txt);
    fclose($progressFile);
    $script = '<script type="text/javascript">window.location.href="error.php";</script>';
}

$servername = "localhost";
$username = "mxnsnjfc_root";
$password = "********";
$dbname = "mxnsnjfc_PerpageDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname, 3306);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$databaseText = file_get_contents("$txtPath/search.txt");

$txtFileEscaped = $conn->real_escape_string($databaseText);

$txtFileEscaped = strip_tags($txtFileEscaped);

$sql = "UPDATE material_tbl SET Content = '$txtFileEscaped' WHERE MaterialID = $id";

if ($conn->query($sql) === TRUE) {
    //echo "<script>/*Record updated successfully*/</script>";
} else {
    //echo "<script>/*Error updating record: " . $conn->error . "*/</script>";
}

$conn->close();

//END OF TXT FILE SAVE

try{
    $api = new Api("***-**************************************");
    $process = $api->createProcess([
        'inputformat' => $extension,
        'outputformat' => 'jpg',
    ]);

    $processUrl = $process->url;

    $process->start([
        'outputformat' => 'jpg',
        'input' => [
            "ftp" => [
                "host" => "*.***.*.**",
                "port" => "21",
                "user" => "mxnsnjfc",
                "password" => "******************",
            ],
        ],
        "output" => [
            "ftp" => [
                "host" => "*.***.*.**",
                "port" => "21",
                "user" => "mxnsnjfc",
                "password" => "******************",
                "path" => "public_html/word/$id/img/",
            ],
        ],
        "file" => "public_html/word/$id/$id.$extension",
        "converteroptions" => [
            "density" => "100",
        ],
    ]);
    //check for percentage of the conversion process.(doesn't work...)
    $process = $process->refresh();
    while($process->step != 'finished' || $process->step != 'error'){
        if($process->step == 'convert'){

        }
        $process = $process->refresh();
     }
$txt = ".jpg finished at: " . date("H:i:s", time());
    $progressFile = fopen("debug/progressFileJpg.txt", "w") or die("Unable to open file!");
    fwrite($progressFile, $txt);
    fclose($progressFile);
}
/*
*The following code checks for errors.
*/
catch (\CloudConvert\Exceptions\ApiBadRequestException $e) {
    $txt = "Something with your request is wrong: " . $e->getMessage()  ." \r\n" .  date("H:i:s", time());
    $progressFile = fopen("debug/progressFile5.txt", "w") or die("Unable to open file!");
    fwrite($progressFile, $txt);
    fclose($progressFile);
    $script = '<script type="text/javascript">window.location.href="error.php";</script>';
} catch (\CloudConvert\Exceptions\ApiConversionFailedException $e) {
    $txt = "Conversion failed, maybe because of a broken input file: " . $e->getMessage()  ." \r\n" .  date("H:i:s", time());
    $progressFile = fopen("debug/progressFile6.txt", "w") or die("Unable to open file!");
    fwrite($progressFile, $txt);
    fclose($progressFile);
    $script = '<script type="text/javascript">window.location.href="error.php";</script>';
}  catch (\CloudConvert\Exceptions\ApiTemporaryUnavailableException $e) {
    $txt = "API temporary unavailable: " . $e->getMessage() ."\n We should retry the conversion in " . $e->retryAfter . " seconds"  ." \r\n" .  date("H:i:s", time());
    $progressFile = fopen("debug/progressFile7.txt", "w") or die("Unable to open file!");
    fwrite($progressFile, $txt);
    fclose($progressFile);
    $script = '<script type="text/javascript">window.location.href="error.php";</script>';
} catch (Exception $e) {
    // network problems, etc..
    $txt = "Something else went wrong: " . $e->getMessage() . "\n"  ." \r\n" .  date("H:i:s", time());
    $progressFile = fopen("debug/progressFile8.txt", "w") or die("Unable to open file!");
    fwrite($progressFile, $txt);
    fclose($progressFile);
    $script = '<script type="text/javascript">window.location.href="error.php";</script>';
}
?>

Access to process data

Hi,

I'm trying to get the input.url data of the process in order to use download mode on a second conversion, but there is no getter for the data.

An example (motivation) would be exactly the steps described in the video conversion API example. It's specifically mentioned (part 2 step 2) to retrieve the url from the input object of the process data but I can't seem to find a way to do so without using reflections or extending the process class and adding a getter for $data which is luckily a protected member of ApiObject from which Process is derived.

Thanks :)

Callback not downloading

I am trying to use the callback method to download files into dynamically created folders, however the download is not working.

I am trying to pass an id as part of the callback to work out where to download the files.

try {
    $api->convert([
    'inputformat' => $filetype,
    'outputformat' => $output,
    'input' => 'download',
    'file' => SITE_ROOT.'upld/'.$id_content.'/'.$upfile,
    'callback' => SITE_ROOT.'admin/callback.php?id='.$id_content
]);

Inside my callback.php I have the following code:

require 'phar://cloudconvert-php.phar/vendor/autoload.php';
use \CloudConvert\Api;
use \CloudConvert\Process;
$api = new Api("[myapicode]");

$id = $_GET['id'];

$process = new Process($api, $_REQUEST['url']);
$process->refresh()->downloadAll("../upld/".$id."/");

Error when getting status

I'm using this example to get the status of a convert:

require __DIR__ . '/vendor/autoload.php';
use \CloudConvert\Api;
use \CloudConvert\Process;
$api = new Api("_API_KEY_");

$process = new Process($api, '/process/_PROCESS_ID_');
$process->refresh();

But I keep getting the error No API Key provided!. What am I doing wrong?

How can we manage the process mode info and convert both by same process object

I am using cloud convert with php and i want to know how can we manage process mode info and covert both by same process object because i have to acheive both convertion and info data of a file accurately, currently i am achieving both by creating two process object that is not good practise i think below is my code, how can i solve my problem please help me


<?php
require _DIR_ . '/vendor/autoload.php';
use \CloudConvert\Api;
$api = new Api("****************");
**//part 1 for converting the files**
$process = $api->createProcess(
                                            [......................]
                             );
$process->start(
                      [........................]
                 );
$info = $api->createProcess(
                               [..................]
                          );
**//have to do extra code part 2 for getting the file info**
$info->start( [
                  "mode" => "info",
                  "input" => "download",
                  "file" => "http://anyURL.ext"
                  ]);
$infoUrl = json_decode(json_encode($info), true));
**//now fetching the data from the $infoUr** 
?>

Error: File too large!

Hi,
Today i have problem converting files around 900MB.
It show: File too large!.
What's going on?I had converted days ago files more than 2GB.
Please help.

Fatal error with Combine including a password protected PDF

Hi,
If I try to combine multiple files including 1 PDF password protected file, I get a FATAL ERROR.
I would prefer a nice message to return to the user ;-)

<b>Fatal error</b>: Uncaught exception 'CloudConvert\Exceptions\ApiConversionFailedException' with message 'Syntax Error: Could not merge damaged documents ('/data/AlternatifBienEtre-131-Ao&lt;c3&gt;&lt;bb&gt;t-2017-Alzheimer-le-protocole-qui-a-gueri-huit-malades-sur-dix-SD-tv.1-paszsword.pdf') ' in phar:cloudconvert-php.phar/src/Api.php:140 Stack trace: #0 phar:cloudconvert-php.phar/src/Api.php(169): CloudConvert\Api-&gt;rawCall('GET', '//host123d1qs.c...', Array, false) #1 phar:cloudconvert-php.phar/src/ApiObject.php(60): CloudConvert\Api-&gt;get('//host123d1qs.c...', Array, false) #2 phar:cloudconvert-php.phar/src/Process.php(105): CloudConvert\ApiObject-&gt;refresh(Array) #3 \visit.immo\dashboard\includes\dropzone.php(105): CloudConvert\Process-&gt;wait() #4 {main} thrown in <b>phar:cloudconvert-php.phar/src/Api.php</b> on line <b>140</b><br />.

File too large!

Hi,
I have problem when converting files size 1.76 GB.
It show: ERROR Your provided file example.rar is too large!
Please help me.

Thank You.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.