最近做项目,后台已经做好了但是前台的模版还没下来,所以测试比较麻烦。于是写了个简单的脚本通过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);
}
}



