Mark D
Mark D

Reputation: 326

Uploading multiple files using PHP via curl

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?

Upvotes: 3

Views: 2900

Answers (1)

Ranty
Ranty

Reputation: 3362

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

Upvotes: 1

Related Questions