Reputation: 18170
I'm trying to send form fields and file to a web service using php curl. The form has already been passed from a browser to a proxy php client web app and I'm trying to forward it to the web service.
When I pass an array to curl_setopt like this:
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $this->fields);
I get a Array to String notice although it is meant to take an array. Here's my array that is passed to $this->fields in the constructor.
$fields = array('title'=>$title,
'content'=>$content,
'category'=>$category,
'attachment'=>$_FILES['attachment']);
If I pass a string using http_build_query
my web serivce complains about not having multipart/form data.
If I then force the multipart/form enctype using curl_setopt
I get an error saying there's no boundary:
org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
Any ideas?
Upvotes: 1
Views: 7796
Reputation: 1711
try this,
$filePath = "abc\\xyz.txt";
$postParams["uploadfile"] = "@" . $filePath;
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, 'https://website_address');
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, $postParams);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
if (curl_errno($ch))
{
echo curl_error($ch);
exit();
}
curl_close($ch);
Upvotes: 0
Reputation: 400932
The array to string notice you have with the following code :
$fields = array(
'title'=>$title,
'content'=>$content,
'category'=>$category,
'attachment'=>$_FILES['attachment']
);
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $fields);
is not because of you're passing an array as 3rd parameter to curl_setopt : it's because you're passing an array for attachment
.
$fields = array(
'title'=>$title,
'content'=>$content,
'category'=>$category,
'attachment'=> '@' . $_FILES['attachment']
);
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $fields);
(This is supposing that $_FILES['attachment']
contains the full path to your file -- up to you to change this code so it's using the right data, if needed)
The full data to post in a HTTP "POST" operation.
To post a file, prepend a filename with @
and use the full path.
This can either be passed as a urlencoded string like 'para1=val1¶2=val2&...'
or as an array with the field name as key and field data as value.
If value is an array, the Content-Type
header will be set to multipart/form-data
.
Upvotes: 3