stack
stack

Reputation: 10228

How to open a page and pass a POST parameter to it by PHP?

I can open a page by PHP like this:

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

But it will be redirected to https://hammihan.com/users.php. Because name input is empty. Now I need to open that URL and pass a POST parameter to it. Something like this:

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

Anyway, how can I do that by PHP ?


EDIT:

I've tested CURL approach but it returns nothing. Here is my code:

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

The output of function above is empty. Noted that when I paste following code into a .html page, it works:

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

What's wrong? Why I cannot get the result by PHP?

Upvotes: 0

Views: 101

Answers (2)

Niranjan N Raju
Niranjan N Raju

Reputation: 11987

You can use curl for this

$url = "https://hammihan.com/search.php";
$data['name'] = "a";
$data['email'] = "[email protected]";
// 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);

Now in search.php, you can access post variables like this

echo $_POST['name'];// will echo a
echo $_POST['email'];// will echo [email protected]

Upvotes: 1

Joshua Jones
Joshua Jones

Reputation: 1396

You can do this by making an HTTP POST request to that URL using cURL or a library like Guzzle. You will need to set the request content type as application/x-www-form-urlencoded and format your payload thusly.

Upvotes: 0

Related Questions