开发者

PHP & cUrl - POST problems in while loop

I have a while loop, with cUrl inside. (I can't use curl_multi for various reasons.) The problem is that cUrl seems to save the data it POSTS after each loop traversal. For instance, if parameter X is One the first loop through, and if it's Two the second loop through, cUrl posts: "One,Two". It should just POST "Two".(This is despite closing and unsetting the curl handle.)

Here's a simplified version of the code (with unecessary info stripped out):

<?php   
  while(true){

           // code to form the $url. this code is local to the loop. 
          // so the variables should be "erased" and made new for each 
         // loop through.

    $ch = curl_init();
    $userAgent = 'Googlebot/2.1 (http://www.googlebot.com/bot.html)';
    curl_setopt($ch,CURLOPT_USERAGENT, $userAgent);
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_POST,count($fields));
    curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
    curl_开发者_JS百科setopt($ch, CURLOPT_FAILONERROR, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $html = curl_exec($ch);
    curl_close($ch);
    unset($ch);

    $dom = new DOMDocument();
    @$dom->loadHTML($html);
    $xpath = new DOMXPath($dom);
    $resultTable = $xpath->evaluate("/html/body//table");

           // $resultTable is 20 the first time through the loop,
           // and 0 everytime thereafter because the POSTing doesn't work right 
           //with the "saved" parameters. 

What am I doing wrong here?


EDIT

Michael was right. I needed to unset $fields/$fields_string. The new data was concatenated onto the old data.

I don't understand why this happens, though. $fields is a local variable in the loop. Shouldn't it be removed from the stack once the loop ends, and then it'd be created a new?


Have you tried printing the $fields_string and $fields to see their values at each loop iteration? Perhaps one of them isn't getting cleared. Since you're using curl_init/curl_close each time, the problem is likely not in curl itself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜