从php脚本填充表单并发送


populate form from php script and send it

我在网上搜索了一下,一无所获。

在网站上,有一个用于输入电子邮件地址的输入框。我想用电子邮件地址填写此字段并发送表格。我发现了这个代码:

$postdata = http_build_query(
array(
    'email' => 'youremailaddress'
)
); 
$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);

但在我的情况下,操作文件是当前页面本身,url被重写。所以当我把网址放成这样时:

$result = file_get_contents('http://example.com/login.html', false, $context);
var_dump($result);

我收到了页面,但表单没有发送

您可能需要查看Selenium Webdriver&PHPUnit来完成此任务。即使提交URL每次都会更改,您也应该能够轻松填写表格并提交。下面是一个如何工作的例子:

<?php
class phproTest extends PHPUnit_Extensions_Selenium2TestCase
{
        protected function setUp()
        {
                // Which browser to use
                $this->setBrowser('firefox');
                // The base URL
                $this->setBrowserUrl('http://example.com/');
        }
        public function testContactFormExists()
        {
                $this->url( 'http://example.com/login.html' );
                $email = $this->byName( 'sender_email' );
                $submit = $this->byName( 'submit_button' );
                $this->assertEquals( '', $email->value() );
                $this->assertEquals( 'Submit', $submit->value() );
        }
        public function testSubmitToSelf()
        {
                // set the url
                $this->url( 'contact' );
                // create a form object for reuse
                $form = $this->byId( 'contact_form' );
                // get the form action
                $action = $form->attribute( 'action' );
                // check the action value
                $this->assertEquals( 'http://example.com/login.html', $action );
                // fill in the form field values
                $this->byName( 'sender_email' )->value( 'youremailhere' );
                // submit the form
                $form->submit();
        }
}
?>

看起来很多,但一旦你把它分解,就没那么糟糕了。通过使用这种方法,您将使用实际的浏览器(在本例中为firefox)来填写和提交表单。这将加载和处理javascript,根据表单的创建方式,创建唯一的提交URL可能需要javascript。

一个可能适用于您的选项是Fabien Potencier编写的Goutte来提交表单。

包装学家的示例代码:

$crawler = $client->request('GET', 'http://github.com/');
$crawler = $client->click($crawler->selectLink('Sign in')->link());
$form = $crawler->selectButton('Sign in')->form();
$crawler = $client->submit($form, array('login' => 'fabpot', 'password' => 'xxxxxx'));
$crawler->filter('.flash-error')->each(function ($node) {
    print $node->text()."'n";
});

在Packagist上获取:https://packagist.org/packages/fabpot/goutte