Populate remote forms?

Ask about a PHP problem here.
Post Reply
User avatar
EcazS
Posts: 789
Joined: Fri May 06, 2011 5:29 pm

Populate remote forms?

Post by EcazS »

I know PHP is capable of a lot of different things BUT can you populate remote forms with PHP?

Say I have a form with two input fields on www.domain1.com and a PHP script on www.domain2.com that will populate the form on domain1 and then submit it.

So, almost like a spam thing I guess.
User avatar
jacek
Site Admin
Posts: 3262
Joined: Thu May 05, 2011 1:45 pm
Location: UK
Contact:

Re: Populate remote forms?

Post by jacek »

You can, but not exactly in the way you are asking.

You can't load the page, put values in the boxes and submit it. What you can do is send the same data to the action="" that submitting the form would send.

http://wezfurlong.org/blog/2006/nov/htt ... hout-curl/ is not a bad example, but the code is a bit messy.

I have done this in the past like this (you may recognise it from my channel background)

[syntax=php]class http {

// send http post data to the url.
public static function post($url, $data, $return = true){
$url = parse_url($url);
$boundary = md5(microtime(true));

$post = '';
foreach ($data as $name => $value){
if (file_exists($value)){
$post .= "--{$boundary}\r\n";
$post .= "Content-Disposition: form-data; name=\"{$name}\"; filename=\"" . basename($value) . "\"\r\n";
$post .= 'Content-Type: ' . file::get_mime($value) . ";\r\n\r\n";
$post .= file_get_contents($value) . "\r\n";
}else{
$post .= "--{$boundary}\r\n";
$post .= "Content-Disposition: form-data; name=\"{$name}\"\r\n\r\n";
$post .= $value . "\r\n";
}
}

$post .= "--{$boundary}--\r\n";

if (isset($url['query'])){
$head = "POST {$url['path']}?{$url['query']} HTTP/1.1\r\n";
}else{
$head = "POST {$url['path']} HTTP/1.1\r\n";
}

$head .= "Host: {$url['host']}\r\n";
$head .= "Content-Type: multipart/form-data; boundary=\"{$boundary}\"\r\n";
$head .= 'Content-Length: ' . strlen($post) . "\r\n";
$head .= "Connection: close\r\n\r\n";

$sock = fsockopen($url['host'], ((isset($url['port'])) ? $url['port'] : 80));
fwrite($sock, $head . $post);

if ($return === true){
return stream_get_contents($sock);
}
}

} [/syntax]

Calling

[syntax=php]http::post('http://website.com/login.php', array(
'username' => 'bob',
'password' => 'something',
), false);[/syntax]

would be the same as submitting the form

[syntax=xhtml]<form action="http://website.com/login.php" method="post">
<div>
<input type="text" name="username" value="bob" />
<input type="password" name="password" value="something" />
</div>
<div>
<input type="submit" value="Login" />
</div>
</form>[/syntax]
Image
Post Reply