如何通过PHP打开页面并将POST参数传递给它?

时间:2017-06-28 07:23:12

标签: php html

我可以像这样用PHP打开一个页面:

$html = file_get_contents('https://hammihan.com/search.php');

但它会被重定向到https://hammihan.com/users.php。因为name输入为空。现在我需要打开该URL并将POST参数传递给它。像这样:

$_POST['name'] = 'myname';

无论如何,我怎么能用PHP做到这一点?

编辑:

我已经测试了CURL方法,但它什么也没有返回。这是我的代码:

public function hammihan($request)
{
    $val = 'ali'; // urlencode($request->name);

    $url = "https://hammihan.com/search.php";
    $data['name'] = $val;
    $data['family'] = "";
    $data['marriage'] = 1;

    $handle = curl_init($url);
    curl_setopt($handle, CURLOPT_POST, true);
    curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
    curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($handle, CURLOPT_URL, $url);
    $res = curl_exec($handle);

    return $res;
}

上述功能的输出为空。注意到当我将以下代码粘贴到.html页面时,它可以工作:

<form class="loginform" action="https://hammihan.com/search.php" method="POST">
    <input type="hidden" name="searcher" value="searcher">
    <input name="name" value="" type="text" placeholder="???">
    <input name="family" value="" type="text" placeholder="??? ????????">
    <select name="marriage">
        <option>?????</option>
        <option value="1">???</option>
        <option value="2">??</option>
    </select>
    <input type="submit" value="?????">
    <div class="marginbottom"></div>
</form>

出了什么问题?为什么我不能通过PHP获得结果?

2 个答案:

答案 0 :(得分:1)

您可以将curl用于此

$url = "https://hammihan.com/search.php";
$data['name'] = "a";
$data['email'] = "a@gmail.com";
// you can add more values to $data array.


$handle = curl_init($url);
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);// here we are passing $data
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_URL, $url);
$res = curl_exec($handle);

现在在search.php,你可以访问像这样的帖子变量

echo $_POST['name'];// will echo a
echo $_POST['email'];// will echo a@gmail.com

答案 1 :(得分:0)

您可以通过使用cURL或Guzzle等库向该URL发出HTTP POST请求来执行此操作。您需要将请求内容类型设置为application/x-www-form-urlencoded并格式化您的有效负载。