Eknoes
Eknoes

Reputation: 359

PHP upload file with curl

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.

Upvotes: 0

Views: 14186

Answers (2)

金馆长
金馆长

Reputation: 217

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');

Upvotes: 0

Ibraheem
Ibraheem

Reputation: 160

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

Upvotes: 1

Related Questions