从 HTTP 发布到另一台服务器的 PHP 字符串


PHP string from HTTP post to another server

我将在这个网站上进一步使用 PHP,否则有兴趣学习更多的 python 来实现这些结果。

我从一个搜索表单开始,该表单允许用户输入需要转换为 url 的"findme"值。(例如,我将使用 findme = 12345678)

<form name="search" method="post" action="search.php" target="_blank" novalidate>
<input type="text" name="findme" />
<input type="submit" name="submit" value="submit" />
</form>

然后,我想从第二个服务器检索 HTTP 帖子响应页面中的字符串,并将 url 存储为 PHP 字符串。

首先,我需要将表单提交到另一台服务器,这是我的搜索尝试.php

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://another.server.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
$data = array(
    'surname' => 'surname',
    'name' => 'name',
    'findme' => 'findme'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
?>

另一个服务器通过提供新页面(即 https://another.server.com/response.html)来响应,然后我想找到包含 findme 字符串的行,下面是 findme 值 12345678 将出现在响应页面的一行中的格式。我想将 ABCDE 保存为字符串。

<tr class="special"><td><a href="/ABCDE">12345678</a>......

希望我能实现

<?php
file_put_contents("response.html", file_get_contents("https://another.server.com/response.html"));
$content = file_get_contents('response.html');
preg_match('~^(.*'.$findme.'.'</a>'.*)$~',$content,$line);
echo $line[1];
$findme_url = substr("abcdef", -37, 5);
echo $findme_url
?>
使用 cURL

和preg_match可能的解决方案进行了更新,但是文件放置内容需要从 cURL 读取响应页面

是的,这是使用 curl 的最佳时机。

$request = curl_init( 'https://another.server.com' );
curl_setopt( $request, CURLOPT_POST, true ); // use POST
$response = curl_exec( $request );
// catch errors
if( $response === false ) {
    throw new Exception( curl_error($response) );
}
curl_close( $request );
// parse response...