开发者

Filling out and submitting html forms with php without user input

开发者 https://www.devze.com 2023-03-24 06:06 出处:网络
I have the following form in a file called \"foobar.html\": <!-- other stuff --> <form method=\"post\" action=\"foo.php?cat=1\">

I have the following form in a file called "foobar.html":

<!-- other stuff -->

<form method="post" action="foo.php?cat=1">
  <input type="text" name="bar" />
  <input type="submit" value="foobar" name="foobar" />
</form>

<!-- other stuff -->

And I open this file in a php script with fopen, how do I fill out and submit this for开发者_StackOverflow中文版m without any input from the user? Thanks


Parse out the action attribute with a HTML parser, and use curl to perform a POST to the appropriate target URL.


Read the entire fire into a variable. Rather than using fopen you might want to consider file_get_contents for that, it's a bit cleaner.

You'll then want to parse that string as HTML. You could use PHP's DOMDocument for that. Get the action and method of the form by traversing the DOM tree to the form tag and reading out those attributes. Next get the names of any inputs within the form tags. Use those names to generate a query string with your key=value pairs. If the method of the form is GET, then append that query string to the form action, otherwise save it in another variable.

Finally, use CURL to "submit" the form. That is, use the form action as the URL for a CURL request. If the form method was GET, you should have already appended the data to the URL, if the method was POST, you'll want to set the data for the CURL request to the data query string you generated from the form names.

If your question extend to how to know what data to fill into what form fields, that is pretty much impossible to solve. Certainly there are some input names you could look for and guess the required data but a universal solution is an impossible problem to solve.


Are you trying to have the user submit the form on their browser, without user interaction? If that's the case, you'll need to resort to javascript, something like:

<body onLoad="document.getElementById('autoSubmit').submit();">
    <form id="autoSubmit">
    (insert form here) 
    </form>
</body>

This will automatically submit the form. Some notes: not everyone has JavaScript enabled, so you might want to change the inputs to type="hidden", as well as add a nice big submit button that says Click Here.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号