Sending a file via CURL using PHP

Asked

Viewed 2,336 times

0

How to translate the following CURL command to PHP?

curl -F file=@/home/user/picture.jpg

https://api.dominio.com/pictures

I tried a few ways but the ones I found were all sent with some key (e.g., Myfile => /home/user/picture.jpg) but in the case there seems to be no key.

1 answer

3


In PHP 5.6 and above you have the curl_file_create, you can use it.

curl -F file=@/home/user/picture.jpg https://api.dominio.com/pictures

This indicates exactly:

  • -F indicates that it is a multipart/form-data and therefore the CURLOPT_POSTFIELDS must be passed through array.

  • The "file" indicates the parameter name, or is the "key".

  • The "/home/user/picture.jpg" indicates the file path, the @ before it indicates that it is to be read the path file (and not shipped /home/user/picture.jpg as text).

Knowing this just use CURL PHP:

$ch = curl_init('https://api.dominio.com/pictures');

curl_setopt_array($ch, [    
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => [          
      'file' => curl_file_create('/home/user/picture.jpg')
    ]
]);

$resposta = curl_exec($ch);
curl_close($ch);

If you are in older versions PHP is not all lost, you can use:

CURLOPT_POSTFIELDS => [          
   'file' => '@/home/user/picture.jpg'
]
  • Worked perfectly :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.