Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uploading multiple files using PHP via curl

Tags:

php

curl

upload

ftp

I am trying to transfer two files via PHP using cURL. I know the methodology via the command line would be

curl -T "{file1,file2,..filex}" ftp://ftp.example.com/ -u username:password

And within php you can upload 1 file via the following code

$ch = curl_init();
$localfile = "somefile";
$username = "[email protected]";
$password = "somerandomhash";
$fp = fopen($localfile, 'r');
curl_setopt($ch, CURLOPT_URL, "ftp://ftp.domain.com/");
curl_setopt($ch, CURLOPT_USERPWD, "$user:$pass");
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);

But how would I do multiple files using the above methodology?

like image 909
Mark D Avatar asked Aug 15 '26 20:08

Mark D


1 Answers

If you can use the same credentials to connect to FTP in parallel, you could try to do that with minimum changes via curl_multi_* with the code like this:

$chs = array();
$cmh = curl_multi_init();
for ($i = 0; $i < $filesCount; $i++)
{
    $chs[$i] = curl_init();
    // set curl properties
    curl_multi_add_handle($cmh, $chs[$i]);
}

$running=null;
do {
    curl_multi_exec($cmh, $running);
} while ($running > 0);

for ($i = 0; $i < $filesCount; $i++)
{
    $content = curl_multi_getcontent($chs[$t]);
    // parse reply
    curl_multi_remove_handle($cmh, $chs[$t]);
    curl_close($chs[$t]);
}
curl_multi_close($cmh);
like image 90
Ranty Avatar answered Aug 18 '26 11:08

Ranty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!