我如何在使用 Curl 发布后获得网址


How I get url after posting with Curl

嗨,我知道这是StackOverFlow上一个非常常见的话题。我已经花了整整一周的时间去搜索它。

我有一个网址:http://bayja.com/forum/index.php

我发布后的这个网址:http://bayja.com/forum/index.php?topic=3454.0

我想得到:http://bayja.com/forum/index.php?topic=3454.0 帖子后获取主题编号"3454.0"

这是我的代码:

function post($subj, $mess, $user, $password, $board, $domain) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_COOKIESESSION, 1);
    curl_setopt($ch, CURLOPT_COOKIEJAR, dirname(__FILE__).'/cookie.txt');
    curl_setopt($ch, CURLOPT_COOKIEFILE, dirname(__FILE__).'/cookie.txt');
    curl_setopt($ch, CURLOPT_USERAGENT, "Automatic SMF poster thing");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "user=".$user."&passwrd=".$password);
    curl_setopt($ch, CURLOPT_URL, "$domain?action=login2");
    curl_exec($ch);
    curl_setopt($ch, CURLOPT_URL, "$domain?action=post;board=".$board.".0");
    $data = curl_exec($ch);
    sleep(3);
    preg_match ( "<input type='"hidden'" name='"sc'" value='"(.*)'">", $data, $sc);
    preg_match ( "<input type='"hidden'" name='"seqnum'" value='"(.*)'">", $data, $seqnum);

    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "subject=".urlencode($subj)."&icon=xx&message=".urlencode($mess)."&notify=0&lock=0&goback=1&sticky=0&move=0&attachment%5B%5D=&attachmentPreview=&post=xxxxx&sc=".$sc[1]."&seqnum=4&seqnum=".$seqnum[1]);
    curl_setopt($ch, CURLOPT_URL, "$domain?action=post2;start=0;board=".$board);
    curl_exec($ch);
    curl_close($ch);
}

请帮助我在帖子后获取网址以获取主题编号。非常感谢。

将curl_getinfo与CURLINFO_EFFECTIVE_URL一起使用以获取与主题匹配的最后一个 URL 和regex,即:

...
curl_exec($ch);
$lastUrl =  curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$topic = preg_replace('/.*topic=(.*?)$/m', '$1', $lastUrl);
echo $topic;  
//3454.0
curl_close($ch);

更新:

你能帮我介绍一下preg_match

preg_match_all('/.*topic=(.*?)$/m', $lastUrl, $topic, PREG_PATTERN_ORDER);
$topic = $topic[1][0];