php - 填写表单字段

标签 php curl

我想填写一个表单字段并使用 CURL 提交它。该网页有许多已填写的表单字段,因此我不想触摸这些字段。

那么是否可以使用curl并填充必填字段并将其与已填充的所有其他字段一起提交?

最佳答案

完整演练(给定提供的 HTML 抓取文本)

要进行自定义,您只需将字段名称添加到 $fields_i_want 数组中,以指定您想要从下载的源文本中提取的所有文本字段值,并更改检索和提交位置的 URL。

此外,file_get_contents() 的更好替代方法是curl。您可以使用 this SO post 上的说明了解如何通过curl 检索远程文本。

// First, retrieve the remote source using file_get_contents()
$str = file_get_contents('http://www.example.com/');    

$my_field_val  = 'my_field_value';
$fields_i_want = array('audien', 'unifor');
$field_vals    = array();
$field_string  = '';


// Use DOM to parse the values you want from the form
$dom = new DOMDocument;
$dom->loadHTML($str);

// Get all the input field nodes
$inputs = $dom->getElementsByTagName('input');

// Iterate over the input fields and save the values we want to an array
foreach ($inputs as $input) {
  $name = $input->getAttribute('name');
  if (in_array($name, $fields_i_want)) {
    $val = $input->getAttribute('value');
    $field_vals[$name] = $val;
  }
}

// append the field value we set ourselves to the list
$field_vals['my_field'] = $my_field_val;

foreach ($field_vals as $key => $val) {
  $field_vals[$key] = urlencode($val)
}

// url-ify the data for the POST
foreach($fields as $key=>$value) {
  $fields_string .= $key.'='.$value.'&';
}
rtrim($fields_string, '&');

// open connection
$ch = curl_init();

// POST the data to the form submission url
$submit_url = 'http://www.submitform.com';

// set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $submit_url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);

// execute post (returns TRUE on success or FALSE on failure)
$result = curl_exec($ch);

// close connection
curl_close($ch);

关于php - 填写表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8419997/

相关文章:

php - 设计具有三种不同访问级别的 php mysql 用户登录系统的最佳方法是什么?

php - PayPal cURL Cert 错误设置证书验证位置

curl - 为什么 Elasticsearch _update with "script"using "params"不删除文档?

php - 如果站点是主页,则显示菜单(wordpress)

php - Symfony2 : what Symfony git repository can I use to start a project?

php - 为什么在yii框架中使用Chtml

curl - 使用 Curl 创建具有成员资格的 Asana 任务

php - 如何使用 curl 获取 JSON 响应

php - 获取 google play 开发者控制台页面中列出的所有应用程序

php - Laravel 4.2 在 BelongsToMany 结果上返回软删除