Sending file via CURL using PHP

0

How to translate to PHP the following CURL command?

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

https://api.dominio.com/pictures

I tried in some ways but the ones I found were all sending with some key (eg myfile = > /home/user/picture.jpg) but in case it does not seem to have a key.

    
asked by anonymous 03.02.2017 / 18:26

1 answer

2

In PHP 5.6 and higher you have 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 CURLOPT_POSTFIELDS must be passed array .

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

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

Knowing this is enough to use the PHP CURL:

$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 old versions PHP is not all lost, you can use:

CURLOPT_POSTFIELDS => [          
   'file' => '@/home/user/picture.jpg'
]
    
03.02.2017 / 19:28