Fill out a form automatically using curl and php

我的未来我决定 提交于 2020-01-06 02:49:09

问题


I am trying to write a script that fills out forms automatically and then automatically presses the submit button.

I have read that you can use curl to post HTTP requests, but what do you do when the form handles the post request with JavaScript, like the code below?

<form name="myform" action="javascript:void(0)" method="POST" onsubmit="return fancy_function(this)">

回答1:


Based off your answer to the comments above, what you want to do is not "fill out the form" with curl, but rather post the completed form to the same page the form would normally send to.

This is also called cross-site posting, and many developers specifically test for and don't allow it to improve security. This will also be much much harder if the form has a captcha.

Assuming that it still makes sense to do (I've used this technique before for a newsletter signup form), here's what you want to do:

To get the form's action url, you'll need to look through the Javascript code for the site and find where funcy_function() is defined. Then in the body of the function, you'll likely see the destination url. You'll also need to note the specific names of the form variables in the html. You'll need to setup your variables with the exact same names. Then your curl setup will look like this:

$url = 'http://www.targeturl.com';
$myvars = 'myvar1=' . $myvar1 . '&myvar2=' . $myvar2;

$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec( $ch );

This will send the post variables to the specified url, imitating what would normally happen from the form. The html that the page returns will be in $response if you want to parse or use it.



来源:https://stackoverflow.com/questions/3081376/fill-out-a-form-automatically-using-curl-and-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!