简体   繁体   中英

How to keep curl session alive between two php processes?

I can save session and surf the website as logged user while php process exists. That is ok.

Here is my working code:

$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);
    }

Now we have $ch resource to use it for other requests. But it still use curl object in one php session. What if I need to use this session in the different php processes? Is it possible?

No. PHP is basically a stateless application. It's possible to reuse initialized data in other php processes by way of a database or memcache, but resource sessions will have to be re-initialized every time you start a new process.

If it is vitally important, for some reason, that you be able to use the same session, then you might consider writing a continuously running daemon that handles queued requests from the apache server in the background, accepting and responding to requests from the server in a single loop.

I figured out how it works) If you want to keep session just copy set-cookie option from header response to some file. After that you can use this cookies for next connection. You have not to do authorization again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM