PHP post请求与curl和隐藏值


PHP post request with curl and hidden values

我目前正试图通过curl发送POST数据到URL。数据被发送到的URL就是表单所在的URL。换句话说,形式"action"就是它本身。

问题是,在表单页面上,一个随机隐藏的输入值在每次刷新时设置,我需要获得这些值,并将它们与我要发布的其他数据一起使用。下面是我当前的代码:

<?php
function httpPost($url,$params) {
    $postData = '';
    $proxy = "127.0.0.1";
    $port = "9150";
    // Create name value pairs seperated by &
    foreach($params as $k => $v) { 
        $postData .= $k . '='.urlencode($v).'&'; 
    }
    rtrim($postData, '&');
    $ch = curl_init();  
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_HEADER, false); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POST, count($postData));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);    
    curl_setopt ($ch, CURLOPT_PROXYTYPE, 7 );
    curl_setopt ($ch, CURLOPT_PROXY, $proxy.':'.$port );
    $output=curl_exec($ch);
    curl_close($ch);
    return $output;
}
$content = file_get_contents('https://secured.example.com/directory/create'); 
$params = array(
    "name" => "Name",
    "pass" => "password",
    "email" => "email@email.com"
);
echo httpPost("https://secured.example.com/directory/create",$params);
?>

例如,在https://secured.example.com/directory/create上有一个隐藏的输入字段,看起来像这样:

<input type="hidden" name="anon_token" value="ZHvR0DtwB-15Os0qwdVE3IN_ygSHHhllDAkOUwVPtZE" />

但是,该值是每次(刷新)随机设置的。

获取内容后,需要获取anon_token的值

这基本上使用HTML页面的内容作为新的DOMDocument。然后获取所有输入标记,以找到包含"anon_token"的一个输入标记。您希望从这个标记获得值(即令牌)。该令牌需要插入到POST数据数组中。

旁注:一个简单的preg_match也可以工作。但是,无论如何,为了安全起见,我们还是使用Dom-functions。

$content = file_get_contents('https://secured.example.com/directory/create');
$doc = new DOMDocument();
$doc->loadHTML($content);
$tags = $doc->getElementsByTagName('input');
foreach ($tags as $tag) {
    if($tag->getAttribute('name') === 'anon_token') {
         $token = $tag->getAttribute('value');
    }
}
$params = array(
    "name" => "Name",
    "pass" => "password",
    "email" => "email@email.com",
    "anon_token" => $token
);

与preg_match () . .

preg_match('/name="anon_token"'svalue="(.*)"/', $content, $matches)
$token = $matches[0];

希望这行得通:

$content = file_get_contents("https://secured.example.com/directory/create");
$pattern  = "/hidden.*name=['s|'|'"]anon_token.*value=.*['"']/";
preg_match( $pattern , $content  , $matches);
$pattern_value  = "/hidden.*name=['s|'|'"]anon_token.*value=/";
foreach($matches as $match){
echo preg_replace(array($pattern_value, "/'/" , '/"/')  , array( "", "" , "") , $match);
}