0

I'm trying to upload a file to an API with PHP. Additionally to the file i need to provide other parameters. My current code looks like this:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);

curl_setopt($ch, CURLOPT_PUT, 1);
$post = array(
    'file'        => '@' . realpath('filename'),
    'other_parameter'  => ''
);

curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array('Content-Type: multipart/form-data');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERPWD, $user . ":" . $pass);
$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close ($ch);

Server header response: HTTP/1.1 422 status code 422 Cache-Control: no-cache Content-Type: application/json; charset=utf-8 Status: 422 Unprocessable Entity Vary: Origin X-Content-Type-Options: nosniff X-Xss-Protection: 1; mode=block Content-Length: 106 Connection: keep-alive

Also i get the message that the file field cannot be empty.

Eknoes
  • 349
  • 4
  • 6
  • 17
  • 1
    Please add additional information: What have you tried so far? Are there any errors? What is the server's response (including the headers! [see here for help](http://stackoverflow.com/questions/9183178/php-curl-retrieving-response-headers-and-body-in-a-single-request))? – 0xJoKe Feb 20 '17 at 21:28
  • The code contains what i've tried. I've also tried it with application/x-www-form-urlencoded instead of multipart/form-data as content type, but had also no success – Eknoes Feb 21 '17 at 13:40

2 Answers2

1

Here is the answer to your question (as it's repeated question!):

how to upload file using curl with php

And also take a look at the link here: http://php.net/manual/en/function.curl-file-create.php

Community
  • 1
  • 1
Ibraheem
  • 160
  • 1
  • 11
  • Thanks. Set CURLOPT_POSTFIELDS before CURLOPT_POST. That combined with curl_file_create solved it – Eknoes Feb 22 '17 at 10:42
0
function ftp_upload($localfile,$ftpHost,$ftpUsername,$ftpPassword){
    $ch=curl_init();
    $fp=fopen($localfile,'r');
    curl_setopt($ch,CURLOPT_URL,"ftp://".$ftpUsername.':'.$ftpPassword.'@'.$ftpHost.'/htdocs/'.$localfile);
    curl_setopt($ch,CURLOPT_UPLOAD,1);
    curl_setopt($ch,CURLOPT_INFILE,$fp);
    curl_setopt($ch,CURLOPT_INFILESIZE,filesize($localfile));
    curl_exec ($ch);
    $error_no=curl_errno($ch);
    curl_close ($ch);
    if($error_no==0){
        $message='File uploaded successfully.';
    }
    else{
        $message='File upload error: $error_no';
    }
    return $message;
}
echo ftp_upload('test.zip','ftp.hello.net','user','123456');
clemens
  • 16,716
  • 11
  • 50
  • 65
金馆长
  • 217
  • 2
  • 7