2014-02-21 112 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