Use file_get_contents to simulate form submissions or POST requests

Testing your website, written in PHP, for GET request is a very easy task. All you have to do, is to manipulate your browser’s URL bar. And what about testing POST requests? Impossible?

Well… This Stack Overflow answer shows, that it is not only possible, but also fairly easy.

You just need to write a short piece of code and call file_get_contents in the end:

$postdata = http_build_query(
    array(
        'var1' => 'some content',
        'var2' => 'doh'
    )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context  = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);

That’s all. Consult mentioned Stack Overflow answer for details, comments etc.

Leave a Reply