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:

[code language=”php”]
$postdata = http_build_query(
‘var1’ => ‘some content’,
‘var2’ => ‘doh’

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

$context = stream_context_create($opts);

$result = file_get_contents(‘’, false, $context);

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

Leave a Reply