3

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 = "Someusername@someserver.com";
$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?

SchmitzIT
  • 9,227
  • 9
  • 65
  • 92
Mark D
  • 327
  • 1
  • 9
  • 15

1 Answers1

1

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);
Ranty
  • 3,333
  • 3
  • 22
  • 24
  • That would be great but unfortunately I need to upload the two files in sequence using the same connection. So File1, then File2, however files 3 and 4 can be uploaded using a different connection, which in fact is what I'm trying to achieve. So to summarize file 1 then file2, while concurrently file3 then file 4, ad infinium. – Mark D Dec 06 '12 at 13:50
  • You can still use the code I provided, simply running it twice without the lines: `curl_multi_remove_handle($cmh, $chs[$t]);`, `curl_close($chs[$t]);` and `curl_multi_close($cmh);` – Ranty Dec 06 '12 at 13:55
  • Isn't this more targeted towards downloading files as opposed to uploading files? I need to be able to upload multiple files. – Mark D Dec 12 '12 at 03:59
  • It's just a tool, it's up to you how you use it. You might need to do less threads while uploading, but that's simply due to the fact that more resources are required for it. – Ranty Dec 12 '12 at 06:03
  • hi @Ranty i am trying above code but not work for multiple files it upload only single file to remote server – faizanbeg Apr 07 '18 at 09:49