doutuobao9736 2013-06-20 01:41
浏览 29

如何在php中对网页中的表单发出HTTP请求

What I am trying to achieve is:

I have a web site to which I have full source code access. The pages in this web site has been created using velocity templates and I have a page with the following form.

<h3>form data</h3>
<form action="$portalPath/test" method="post">
    <input type="text" name="text" value="$!self.getTextFromFormData()" />
    <input type="submit" />
</form>

Now from another application written in php, I want to make an http request to this page and get a file downloaded. (Which is an html file). To do that, I wrote following code from the other web application :

$url = 'http://localhost/portal/default/test';
$data = array('filename.html');

$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded
",
        'method'  => 'POST',
        'content' => http_build_query($data),
    ),
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

var_dump($result);

But the result shows the html source of the template I access(i.e. test) and not the html file I want to download. What I want to do is to make an http request to auto enter the file name to the form and make the form auto submit the request and process it and get the required html file downloaded as the result. I don't know if this is possible or if possible whether this is the correct way. If this can be done using curl, that's better. Any idea will be highly appreciated.

  • 写回答

1条回答 默认 最新

  • dqxsuig64994 2013-06-20 01:46
    关注

    See: how can I post an external form using PHP?

    So, from the referenced URL:

    <?php
      $url = 'http://localhost/portal/default/test';
      $fields = array(
        'text'=>urlencode($value_for_field_text),
      );
    
      //url-ify the data for the POST
      foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
      rtrim($fields_string,'&');
    
      // Initialize curl
      $ch = curl_init();
    
      //set the url, number of POST vars, POST data
      curl_setopt($ch,CURLOPT_URL,$url);
      curl_setopt($ch,CURLOPT_POST,count($fields));
      curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
    
      //execute post
      $result = curl_exec($ch);
    
      // Results of post in $result
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100