2

Possible Duplicate:
Grabbing the href attribute of an A element

How can I extract the sessionId and viewstate variables from this code?

The code is this:

$url = "http://www.atb.bergamo.it/ITA/Default.aspx?SEZ=2&PAG=38&MOD=LINTRV";

$ckfile = tempnam ("/tmp", "CURLCOOKIE");
$ch = curl_init ($url);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile); 
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$html = curl_exec ($ch);
curl_close($ch);

preg_match('~<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="(.*?)" />~',$html,$viewstate);

var_dump(file_get_contents($ckfile)); //<--- There's the sessionId variable in it
var_dump($viewstate[1]);              //<--- View State

Can you help me please?

Community
  • 1
  • 1
nhDeveloper
  • 53
  • 1
  • 5
  • It's easier to use a HTML parser to extract such values than a regex. For the regex however, this has been asked and answered before. – hakre Dec 02 '12 at 13:07

1 Answers1

4

You can do this very simple without regex:

$viewstate = explode('id="__VIEWSTATE" value="', $html);
$viewstate = explode('"', $viewstate[1]);
$viewstate = $viewstate[0];

Same for the cookie:

$sesid = explode('SessionId', file_get_contents($ckfile));
$sesid = explode('\n', $sesid[1]);
$sesid = trim($sesid[0]);

Put it all together and you get

   $url = "http://www.atb.bergamo.it/ITA/Default.aspx?SEZ=2&PAG=38&MOD=LINTRV";    
   $ckfile = tempnam ("/tmp", "CURLCOOKIE");
   $ch = curl_init ($url);
   curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile); 
   curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true);
   curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
   $html = curl_exec ($ch);
   curl_close($ch);

    $viewstate = explode('id="__VIEWSTATE" value="', $html);
    $viewstate = explode('"', $viewstate[1]);
    $viewstate = $viewstate[0];    

    $sesid = explode('_SessionId', file_get_contents($ckfile));
    $sesid = explode("\n", $sesid[1]);    
    $sesid = trim($sesid[0]);

    echo $viewstate."<br/>";
    echo $sesid;

Works on my test setup.

Green Black
  • 5,037
  • 1
  • 17
  • 29