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.

2
  • 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)? Commented Feb 20, 2017 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 Commented Feb 21, 2017 at 13:40

2 Answers 2

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

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

1 Comment

Thanks. Set CURLOPT_POSTFIELDS before CURLOPT_POST. That combined with curl_file_create solved it
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');

Comments

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.