【问题标题】:How to get sessionId and viewstate variables from this code? [duplicate]如何从此代码中获取 sessionId 和 viewstate 变量? [复制]
【发布时间】:2012-11-19 16:39:13
【问题描述】:

可能重复:
Grabbing the href attribute of an A element

如何从这段代码中提取sessionIdviewstate 变量?

代码是这样的:

$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

你能帮帮我吗?

【问题讨论】:

  • 使用 HTML 解析器提取这些值比使用正则表达式更容易。然而,对于正则表达式,这已经被问过并回答过。

标签: php html regex libcurl


【解决方案1】:

没有正则表达式你可以很简单地做到这一点:

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

cookie 也一样:

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

把它们放在一起,你就得到了

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

适用于我的测试设置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-30
    • 1970-01-01
    相关资源
    最近更新 更多