pass array with list file to curl loop

2019-08-28 06:02发布

i have a doubt about if i can pass an array that content the link of the files to a curl loop to create a single loops and not everytime i need to upload a file content, copy and paste the same curl call with the different file name.

Here are the code i wrote to upload into the server a single file. I copy and paste the same code for every single file and in that way everything works, but i want to understand how to create a single loop giving to the "$data = array('file'=>$fn);" the loop with all the file content and automate all the calls in one function when call the function "file_get_contents($fn)".

//file to upload

$fn = ("fn.rdf");

//curl loop to upload single file
    $data = array('file'=>$fn);
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/rdf+xml'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/index.php?update=true');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($fn));  
    curl_exec($ch);
    $info = curl_getinfo($ch); var_dump($info);
    $result = curl_exec($ch); 
     if ($result === false) {
       die(curl_error());
     }else{
       echo "<br>"."upload ok"."<br>";
     }

thanks!

EDIT: Hi, once again i have a doubt. If i want to use that script as a function to call its method into an another script that read one by one the articles, here i have to put the function updateContent(){} to call into the other script the method updateContent()? As i already said, $fn contain an array with the list of the file. If i want to call the updateContent() created but only for a specific file1.rdf is correct to use that command updateContent($files['0']); to call the method specified only for the element 0 (correspond to file1.rdf of the array mentioned) to update it status?

1条回答
我想做一个坏孩纸
2楼-- · 2019-08-28 06:48

You mean something like that?

$files = array('1.rdf', '2.rdf', '3.rdf', 'x.rdf', 'whatever.xyz');

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/rdf+xml'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/index.php?update=true');
curl_setopt($ch, CURLOPT_POST, true);

foreach ($files as $fn) {
    curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($fn));  
    $result = curl_exec($ch);
    $info = curl_getinfo($ch); 
    var_dump($info);
    if ($result === false) {
       die(curl_error());
    }else{
       echo "<br />".$fn." upload ok"."<br />";
    }
}
查看更多
登录 后发表回答