How to automatically submit a (POST) form from remote server?

cybergeek654 picture cybergeek654 · Jun 2, 2015 · Viewed 11k times · Source

I am trying to automatically fill in a field and submit a form at another server. I do not have any control on the target page and server.

I tried writing running php code with Snoopy class to do the job, but it did not work (description here)

The page that I am trying to fill in and submit automatically is: http://example.com/?page=a and the source of the page is as follows:

<form action="" method="post" class="horizontal-form" role="form" >
<input type="hidden" name="submit_form" value="true" />
<input type="text" name="field_name" class="form-control" value="" >
<button type="submit" class="btn"><i class="icon-ok"></i> Send</button>
</form>

Any idea how I can fill in the "field_name" automatically using a script/php code from my own site and automatically submit this form? I guess I can use CURL to do it as well, but I am novice and don't know how. :(

Thank you for your help.

Answer

Gerard picture Gerard · Jun 2, 2015

You can't fill the form with php since php is a server-side language. You could fill in the form with javascript. There are some frameworks to do that (phantomjs, casperjs).

You can try to post the form data directly using curl in PHP.

<?php

$data = array(
    'submit_form' => 1,
    'field_name' => 'your value here',
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/post-url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

$output = curl_exec($ch);
$info = curl_getinfo($ch);

curl_close($ch);

You can find the url by looking in the console of your browser:

form post

Your request might be blocked because it's coming from another server but you can give it a try. If you want to 'mimic' a normal visitor you can start with setting the user agent string, maybe modify the HTTP_REFERER as well.

curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36');
curl_setopt($ch, CURLOPT_REFERER, 'http://www.example.com/the-url-of-the-form');