簡體   English   中英

同時運行php腳本的用戶

[英]Simultaneous users running php script

我有一個簡單的PHP腳本,該腳本發出curl HTTP POST請求,然后通過重定向將數據顯示給用戶。 我遇到的問題是,如果一個以上的人同時運行腳本,它將對一個人成功執行並成功完成,但對另一個人卻失敗。 我認為可能與會話或cookie有關,但我沒有使用session_start(),並且在重定向cookie之前將其清除。

為什么會發生這種情況,我可以調整腳本以支持同時用戶嗎?

<?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);

       }
   }


?>

如果我理解正確,那么您訪問的站點使用會話/ cookie,對嗎? 要解決此問題,請嘗試為每個請求創建一個唯一的Cookie罐:

 // 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM