当php进程存在时,我可以作为登录用户保存会话并浏览网站。没关系。
这是我的工作代码:
$options = array(
CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; rv:38.0) Gecko/20100101 Firefox/38.0',
CURLOPT_URL => $url,
CURLOPT_HEADER => true,
CURLOPT_VERBOSE => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_REFERER => 'http://website.com/',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => http_build_query($post),
CURLOPT_COOKIESESSION => true,
CURLOPT_COOKIEJAR => __DIR__ . '/cookie-name',
CURLOPT_COOKIEFILE => '',
CURLOPT_HTTPHEADER => array(
'Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"',
'Accept-Language: "en-US,en;q=0.5"',
'Connection: "keep-alive"',
'Cache-Control: "max-age=0"'
)
);
$ch = curl_init();
curl_setopt_array( $ch, $options );
try {
$raw_response = curl_exec( $ch );
if(curl_errno($ch))
throw new Exception(curl_error($ch), 500);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($status_code != 200)
throw new Exception("Response with Status Code [" . $status_code . "].", 500);
} catch(Exception $ex) {
if ($ch != null) curl_close($ch);
throw new Exception($ex);
}
现在我们有了$ch
资源,可以将其用于其他请求。但它仍然在一个php会话中使用curl对象。如果我需要在不同的php进程中使用这个会话,该怎么办?有可能吗?
否。PHP基本上是一个无状态的应用程序。可以通过数据库或memcache在其他php进程中重用初始化的数据,但每次启动新进程时都必须重新初始化资源会话。
如果出于某种原因,您能够使用同一会话是至关重要的,那么您可以考虑编写一个持续运行的守护进程,在后台处理来自apache服务器的排队请求,在单个循环中接受和响应来自服务器的请求。
我弄清楚了它是如何工作的)如果您想保留会话,只需将set-cookie
选项从标头响应复制到某个文件即可。之后,您可以使用此cookie进行下一次连接。您不必再次进行授权。