Search code examples
phpcurlcookiesgenexus

PHP cUrl and cookie GX_SESSION_ID


I am stuck with this matter.

I am trying to automatize a query in a website form and handle the return response with PHP. My code actually works BUT ONLY when i add the following header:

$headers = [
    'Cookie: GX_SESSION_ID=zWfdnmlQgtodK0ax97epfsbma9J0tvVI%2B%2BelShsOIZo%3D; JSESSIONID=E1378A4864FFF03AF4B8BAA0CBB88D89;',
];
curl_setopt($cURLConnection, CURLOPT_HTTPHEADER, $headers);

The JSESSIONID var is not a problem, the script runs well without it. But if i dont declare the GX_SESSION_ID var with a valid gx session id (which i take from google chrome browsing the website) the script dont works.

When i browse the website with Google Chrome, as soon as i enter the website. The cookie is sent in the Request Headers.

I dont understand how this var is being created.

Can you help me recreate this into my cURL PHP code? Create a calid GX_SESSION_ID without needing to get it manually from a browser?

Thank you all


Solution

  • Use the curl to get cookie variables as array:

    $ch = curl_init('http://www.google.com/');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // get headers too with this line
    curl_setopt($ch, CURLOPT_HEADER, 1);
    $result = curl_exec($ch);
    // get cookie
    // multi-cookie variant contributed by @Combuster in comments
    preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $matches);
    $cookies = array();
    foreach($matches[1] as $item) {
        parse_str($item, $cookie);
        $cookies = array_merge($cookies, $cookie);
    }
    var_dump($cookies);