faqts : Computers : Programming : Languages : PHP : Common Problems : Forms and User Input

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

73 of 82 people (89%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

Can I simulate a form submission using a php script?

Mar 23rd, 2001 15:36
Ben Udall, lukas novak,


Yes, here's an example script submits a search for 'php' to Google 
(http://www.google.com) and returns the second page of results.
<?
// The url to submit the form to
$form_url    = "http://www.google.com/search";
$form_method = "GET";
// The form data to pass 
$form_data['q']     = 'php'; 
$form_data['start'] = '10'; 
// Build the request data string
$request_data = "";
foreach ($form_data as $name => $value)
{
   if (strlen($request_data) > 0)
      $request_data .= '&';
   $request_data .= $name.'='.urlencode($value);
} 
// Build the request
$url         = parse_url($form_url);
$form_method = strtoupper($form_method);
$request     = $form_method." ";
switch ($form_method)
{
   case 'GET': 
      $request .= $url['path']."?".$request_data." HTTP/1.1\r\n".
                  "Host: ".$url['host']."\r\n\r\n";
      break;
   case 'POST': 
      $request .= $url['path']." HTTP/1.1\r\n".
                  "Host: ".$url['host']."\r\n".
                  "Content-type: application/x-www-form-urlencoded\r\n".
                  "Content-length: ".strlen($request_data)."\r\n\r\n".
                  $request_data;
      break;
   default:
      die("Invalid method: ".$form_method);
}
// Open the connection 
$fp = fsockopen($url['host'], 80, $err_num, $err_msg, 30); 
if ($fp) 
{
   // Submit form
   fputs($fp, $request);
   // Get the response 
   while (!feof($fp)) 
      $response .= fgets($fp, 1024);
   fclose($fp);
   echo $response;
}
else
{
   echo 'Could not connect to: '.htmlentities($url['host']).'<br />';
   echo 'Error #'.$err_num.': '.$err_msg;
   exit;
}
?>