Using Perl and LWP::UserAgent to POST to a HTML/PHP form.

Here is the original HTML form that you would see if you were navigating to the page to fill out the form:

<form name="input" action="form_rec.php" method="post">
Ye giveth:<input type="text" name="in">
<input type="submit" value="Go">
</form>

Notice that we’re posting to the file form_rec.php, not the file that actually contains this form code.  If you try posting to the file that actually contains the form code, query for the content, you’ll always get the code for that page.  It is a problem that I see all the time online.

Here is the content of the form_rec.php file:

<?php
$var = $_POST['in'];
echo "Ye taketh: ".$var;
?>

Anyway, here is the perl code that I could use to post to this file:

<code>#!/usr/bin/perl
use strict;
use LWP::UserAgent;
 
my $user = LWP::UserAgent->new();
my $response = $user->
   post('http://website.com/form_rec.php', [in => 'apples']);
 
if ($response->is_success) {
  my $content = $response->content; 
  print $content;
} else {
  print "lol";
}

Getting this to work, the first time, was really frustrating. From looking around at other forums/blogs I found this Firefox plugin to be extremely useful to see exactly what information is being passed to/from the browser to the actual server. The plugin is named Live HTTP Headers and is described here: Live HTTP Headers .

This entry was posted in Programming, Webhosting and tagged , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.