2014-02-21 110 views
0

我有一个简单的php脚本,它发出一个curl HTTP POST请求,然后通过重定向向用户显示数据。我遇到的问题是,如果不止一个人同时运行脚本,它将为一个人执行并成功完成,但对另一个人却失败。我认为它可能与会话或cookie相关,但我没有使用session_start(),并且在重定向之前cookie被清除。运行php脚本的同时用户

为什么会发生这种情况,我可以调整脚本以支持同时用户吗?

<?php 
     $params = "username=" . $username . "&password=" . $password . "&rememberusername=1"; 
     $url = httpPost("http://www.mysite.com/", $params); 
     removeAC(); 
     header(sprintf('Location: %s', $url)); 
     exit; 


     function removeAC() 
     { 
      foreach ($_COOKIE as $name => $value) 
      { 
      setcookie($name, '', 1); 
      } 
     } 

    function httpPost($url, $params) 
    { 
     try { 
      //open connection 
      $ch = curl_init($url); 

      //set the url, number of POST vars, POST data 
      // curl_setopt($ch, CURLOPT_COOKIEJAR, "cookieFileName"); 
      curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)"); 
      curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt'); 
      curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt'); 
      curl_setopt($ch, CURLOPT_HEADER, true); 
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); 
      curl_setopt($ch, CURLOPT_POST, 1); 
      curl_setopt($ch, CURLOPT_POSTFIELDS, $params); 
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 

      //execute post 
      $response = curl_exec($ch); 

      //print_r(get_headers($url)); 

      //print_r(get_headers($url, 0)); 

      //close connection 
      curl_close($ch); 
      return $response; 
      if (FALSE === $ch) 
       throw new Exception(curl_error($ch), curl_errno($ch)); 

      // ...process $ch now 
     } 
     catch(Exception $e) { 

      trigger_error(sprintf(
       'Curl failed with error #%d: %s', 
       $e->getCode(), $e->getMessage()), 
       E_USER_ERROR); 

     } 
    } 


?> 
+3

为每个请求创建一个独特的Cookie jar文件? –

+0

你错过了这一行的报价:'$ url = httpPost(“http://www.mysite.com/,$ params);' –

回答

1

如果我的理解正确,那么您访问的网站使用会话/ cookie,对吗?要解决此问题,请尝试为每个请求创建一个独特的Cookie jar:

// at the beginning of your script or function... (possibly in httpPost()) 
$cookie_jar = tempnam(sys_get_temp_dir()); 

// ... 
// when setting your cURL options: 
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_jar); 
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_jar); 

// at the end of your script or function (when you don't need to make any more requests using that session): 
unlink($cookie_jar); 
+0

你我的朋友应该得到奖励,我必须稍微调整一下,所以它可以在Windows和Linux测试的基础上运行,除此之外它的魅力非常非常好,谢谢!@TajMorton – snapplex