Sebastian Rüttger
Sebastian Rüttger

Reputation: 775

php - use cUrl to upload a file to a form

I need to send a file to a form using cUrl. The Site im sending this to, provided a cUrl command to upload the file, which works from the commandline but i cant get it to work with php curl.

Here is the cUrl command:

curl -x [<proxy_url>:<proxy_port>] -k -v --key key-<id>_nopw.pem --cacert ./ca_Zertifikat-<id>.pem --cert client_Zertifikat-<id>.pem -F upload=@C:\pathto\file.XML https://url.com/upload.php

And here is my php Code:

$ch = curl_init($url);  curl_setopt($ch, CURLOPT_SSLKEY, $keyFile);
curl_setopt($ch, CURLOPT_CAINFO, $caFile);
curl_setopt($ch, CURLOPT_SSLCERT, $certFile);
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$postdata = array();
$postdata['upload'] = realpath($filename);

curl_setopt($ch, CURLOPT_POST, sizeof($postdata));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);

The response i'm getting from the Server amounts to:

"Error in transmission, no file has been uploaded"

I checked the message by manually trying the form and it means that no file has been chosen in the file dialog. What am i missing?

EDIT: This works, but i've been told this won't work on servers, since the probably block this:

exec('curl -k -v --key '.$keyFile.' --cacert '.$caFile.' --cert  '.$certFile.' -F upload=@'.realpath($filename).' https://url.com/upload.php', $result);

Upvotes: 0

Views: 283

Answers (1)

Sebastian R&#252;ttger
Sebastian R&#252;ttger

Reputation: 775

I found the solution. I had to change this:

$postdata['upload'] = realpath($filename);

to this line:

$postdata['upload'] = new CURLFile(realpath($filename), 'text/xml');

this changes from the old way to upload to the new. I had tried this approach before but i set the wrong MIME type, which ended up not working.

Upvotes: 1

Related Questions