Automatic HTML form submission using WWW::Mechanize

Here is a short tip on how to automatically submit a HTML form using a Linux command line and perl script. For this example we would need a WWW::Mechanize perl module and some basic PHP website. Let’s start with simple PHP website. The website will consist of two files:

form.php:

<form action="submit.php" method="post">
First Name: <input name="fname" type="text" />
Last Name: <input name="lname" type="text" />
<input type="submit" />
</form>

submit.php

<html>
<body>
First Name: <?php echo $_POST["fname"]; ?><br />
Last Name: <?php echo $_POST["lname"]; ?>
</body>
</html>

Upload those two files to your webserver’s directory and change their permissions:

chmod 755 form.php submit.php

If you have not done so yet, install WWW::Mechanize. On Debian or Ubuntu it would be something like this:

# apt-get install libwww-mechanize-perl

and create a script called mechanize.pl with a following content:

#!/usr/bin/perl

use WWW::Mechanize;
my $mech = WWW::Mechanize->new();

$url = 'http://localhost/form.php';
$mech->get( $url );

  $mech->submit_form(
        form_number => 1,
        fields      => {
            fname    => 'www',
            lname    => 'mechanize',
        }
    );

print $mech->content();

Note the URL in the above script. Edit this URL to fit your settings. Make the script executable:

$ chmod +x mechanize.pl

Now execute this script and redirect all output to index.html

./mechanize.pl > index.html

If everything was OK open up index.html using your browser and you should see:


First Name: www
Last Name: mechanize