In a recent project, the backend has been completed but the frontend template has not yet been downloaded, so testing is more troublesome. So I wrote a simple script to simulate form submission through curl. Data can be submitted in two ways: array and string.
- /**
- * Class SimulantForm simulation form
- */
- class SimulantForm {
- /**
- * @var The page url to be submitted
- */
- protected $_url;
- /**
- *@var resource The curl handle returned by curl_init()
- */
- protected $_ch ;
- /**
- * Initialize a form
- * @param $_url url
- */
- public function __construct($_url) {
- $this->_ch = curl_init();
- $this->setUrl($_url);
- curl_setopt($this- >_ch, CURLOPT_RETURNTRANSFER, 1);
- }
-
- /**
- *Submit via get method
- * @param array|string form data
- * @return mixed
- */
- public function get($_data = '') {
- $this->_url .= $this->_setGetData($ _data);
- $this->setUrl($this->_url);
- $result = curl_exec($this->_ch);
- curl_close($this->_ch);
- return $result;
- }
-
- /**
- * Submit via post
- * @param array|string form data
- * @return mixed
- */
- 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;
- }
-
- /**
- * Return error message
- * @return array array[0]: error number, array[1]: error message
- */
- public function getLastError() {
- return array( curl_errno($this->_ch), curl_error($this->_ch));
- }
-
- /**
- * Set SETOPT_COOKIEFILE
- * @param string $_cookieFile file real path
- */
- public function setCookieFile($_cookieFile) {
- curl_setopt($this-> _ch, CURLOPT_COOKIEFILE, $_cookieFile);
- }
-
- /**
- * Set SETOPT_COOKIEJAR
- * @param string $_cookieFile file real path
- */
- public function setCookieJar($_cookieFile) {
- curl_setopt($this->_ch, CURLOPT_COOKIEJAR, $_cookieFile);
- }
-
- / **
- * Set url
- * @param $_url
- */
- protected function setUrl($_url) {
- $this->_url = $_url;
- curl_setopt($this->_ch, CURLOPT_URL, $_url);
- }
-
- /**
- * Set the data when submitting in get mode
- * @param $_get_data string or array
- * @return mixed
- */
- protected function _setGetData($_get_data) {
- if(is_array($_get_data)) {
- return $this->_getDataToString($_get_data);
- } elseif(is_string($_get_data)) {
- return $_get_data;
- }
- }
-
- /**
- * Set the data when submitting in post mode
- * @param array|string $_post_data
- */
- protected function _setPostData ($_post_data) {
- curl_setopt($this->_ch, CURLOPT_POSTFIELDS, $_post_data);
- }
-
- /**
- * Parse the submitted information in array form into a string for submission via get method
- * @param array $_get_data
- * @return string
- */
- protected function _getDataToString(array $_get_data) {
- return '?' . http_build_query($_get_data); //Refer to the first floor, replaced by the http_build_query function, and the editing function of oschina is really terrible!
- }
- }
Copy code
|