1

I'm trying to upload files to Redmine using the following PHP code.

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $url)
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/octet-stream',
    'X-Redmine-API-Key: ' . $apiKey));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, TRUE);

$data = array('file' => '@' . $filePath);

curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_POST, 1);

$token = curl_exec($curl);

This request returns a valid upload token but the file is corrupted during upload. Trying to upload, for example, an empty .txt file results in an uploaded overwritten .txt file now containing the following lines.

------------------------------dde946a683ac

Content-Disposition: form-data; name="file"; filename="/var/www/wp-content/uploads/redmine_uploads/emptyTextFile.txt" Content-Type: application/octet-stream

------------------------------dde946a683ac--

Any ideas why this is happening?

2 Answers 2

5

Figured it out. Modifying my code to

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $url)
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/octet-stream',
    'X-Redmine-API-Key: ' . $apiKey));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

$file = fopen($filePath, 'r');
$size = filesize($filePath);
$filedata = fread($file,$size);

curl_setopt($curl, CURLOPT_POSTFIELDS, $filedata);
curl_setopt($curl, CURLOPT_INFILE, $file);
curl_setopt($curl, CURLOPT_INFILESIZE, $size);

curl_setopt($curl, CURLOPT_POST, 1);

$token = curl_exec($curl);

yields the desired file upload.

Sign up to request clarification or add additional context in comments.

Comments

0

Try adding a name value in your CURLOPT_POSTFIELDS array.

$data = array('name' => 'SomeName', 'file' => '@' . realpath($filePath));

As an aside, you no longer need CURLOPT_BINARYTRANSFER.

1 Comment

Excluding CURLOPT_BINARYTRANSFER and editing $data = array('name' => 'emptyTextFile', 'file' => '@' . $filePath); still leads to a corrupted file now containing the lines ------------------------------a943ac000d23 Content-Disposition: form-data; name="name" emptyTextFile ------------------------------a943ac000d23 Content-Disposition: form-data; name="file"; filename="/var/www/wp-content/uploads/redmine_uploads/emptyTextFile.txt" Content-Type: application/octet-stream ------------------------------a943ac000d23--

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.