栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > PHP

通过curl模拟post和get方式提交的表单类

PHP 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

通过curl模拟post和get方式提交的表单类

最近做项目,后台已经做好了但是前台的模版还没下来,所以测试比较麻烦。于是写了个简单的脚本通过curl的方式模拟表单提交。可以通过数组和字符串两种方式提交数据。

复制代码 代码如下:


class SimulantForm {
   
    protected $_url;

   
    protected $_ch;

   
    public function __construct($_url) {
  $this->_ch = curl_init();
  $this->setUrl($_url);
  curl_setopt($this->_ch, CURLOPT_RETURNTRANSFER, 1);
 }

   
    public function get($_data = '') { 
  $this->_url .= $this->_setGetData($_data);
  $this->setUrl($this->_url);
  $result = curl_exec($this->_ch);
        curl_close($this->_ch);
        return $result;
 }

   
    public function post($_data) {
  curl_setopt($this->ch, CURLOPT_POST, 1);
  $this->_setPostData($_data);
  $result = curl_exec($this->_ch);
        curl_close($this->_ch);
        return $result;
 }

   
    public function getLastError() {
  return array(curl_errno($this->_ch), curl_error($this->_ch));
 }

 
 public function setcookieFile($_cookieFile) {
  curl_setopt($this->_ch, CURLOPT_cookieFILE, $_cookieFile);
 }

 
    public function setcookieJar($_cookieFile) {
        curl_setopt($this->_ch, CURLOPT_cookieJAR, $_cookieFile);
    }

 
    protected function setUrl($_url) {
  $this->_url = $_url;
  curl_setopt($this->_ch, CURLOPT_URL, $_url);
 }

   
    protected function _setGetData($_get_data) {
        if(is_array($_get_data)) {
           return $this->_getDataToString($_get_data);
        } elseif(is_string($_get_data)) {
           return $_get_data;
        }
    }

   
    protected function _setPostData ($_post_data) {
        curl_setopt($this->_ch, CURLOPT_POSTFIELDS, $_post_data);
    }

   
    protected function _getDataToString(array $_get_data) {
  $result_string = '?';
  array_walk($_get_data, function ($value, $key) use (&$result_string) {
   if(is_array($value)) {
    foreach($value as $sec_value) {
     $result_string .= $key . '[]=' . $sec_value . '&';
    }
   } else {
    $result_string .= $key . '=' . $value . '&';
   }
  });
  return substr($result_string, 0, strlen($result_string) - 1);
 }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/48346.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号