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 = "[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?

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

5 Comments

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.
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);
Isn't this more targeted towards downloading files as opposed to uploading files? I need to be able to upload multiple files.
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.
hi @Ranty i am trying above code but not work for multiple files it upload only single file to remote server

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.