Send form data curl php

I have the following command, which uses the --form/--F option, which I know to be working:

curl  --form "file=@/home/USERNAME/import.csv" //apiprovider.com/api/v0/imports\?token\=[KEY]

I need to run this command via php, but I'm having trouble, presumably with the form file data. I tried the following, however echoing or var_dumping the result seems to show nothing, just a blank page or a blank string.


How can I get this command working in PHP?

asked Oct 17, 2017 at 15:21

KinsDotNetKinsDotNet

1,4985 gold badges24 silver badges49 bronze badges

3

since no answer got it right thus far [at least not with an approach that would work in php 5.6+], here goes: the equivalent php curl_ code would be:

$ch = curl_init [ '//apiprovider.com/api/v0/imports?token=[KEY]' ];
curl_setopt_array [ $ch, array [
        CURLOPT_POST => 1,
        CURLOPT_POSTFIELDS => array [
                'file' => new CURLFile [ '/home/USERNAME/import.csv' ] 
        ] 
] ];
curl_exec [ $ch ];

[i would also recommend setting CURLOPT_ENCODING to emptystring, especially if you expect the response to be compressible, that would be the equivalent of adding --compressed to the curl command line, and might speed things up]

answered Oct 22, 2017 at 10:04

hanshenrikhanshenrik

18.1k3 gold badges39 silver badges77 bronze badges

try this:


answered Oct 20, 2017 at 9:22

jelle woordjelle woord

1832 silver badges16 bronze badges

0

One way is to use CURLFile instead of @ for PHP version above 5.5

$target_url = '//apiprovider.com/api/v0/imports?token=[KEY]'
$file_name_with_full_path ='/home/USERNAME/import.csv';
// Create a CURLFile object
$cfile = new CURLFile[$file_name_with_full_path,mime_content_type[$file_name_with_full_path],'imported_csv'];    
// Assign POST data
$post = array['imported_csv_file' => $cfile];    
$ch = curl_init[];
curl_setopt[$ch, CURLOPT_URL,$target_url];
curl_setopt[$ch, CURLOPT_POST,1];
curl_setopt[$ch, CURLOPT_POSTFIELDS, $post];
curl_setopt[$ch, CURLOPT_RETURNTRANSFER,1];
curl_setopt[$ch, CURLOPT_VERBOSE,true];
$result=curl_exec [$ch];
curl_close [$ch];
var_dump[$result];

answered Oct 20, 2017 at 14:41

2

Maybe something like this could work:

Chủ Đề