【问题标题】:Simultaneous users running php script同时用户运行 php 脚本
【发布时间】:2014-02-21 17:56:32
【问题描述】:

我有一个简单的 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 jar 文件?
  • 您在此行中缺少引用:$url = httpPost("http://www.mysite.com/, $params);

标签: php curl session-cookies simultaneous simultaneous-calls


【解决方案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);

【讨论】:

  • 你我的朋友值得奖励。我不得不稍微调整一下,所以它可以基于 Windows 和 Linux 测试工作。除此之外,它就像一个魅力。非常感谢! @TajMorton
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-05
  • 2017-06-23
相关资源
最近更新 更多