1. /**
    2. *
    3. */
    4. class MyCurl {
    5. private static $url = ''; // 访问的url
    6. private static $oriUrl = ''; // referer url
    7. private static $data = array(); // 可能发出的数据 post,put
    8. private static $method; // 访问方式,默认是GET请求
    9. public static function send($url, $data = array(), $method = 'get') {
    10. if (!$url) exit('url can not be null');
    11. self::$url = $url;
    12. self::$method = $method;
    13. $urlArr = parse_url($url);
    14. self::$oriUrl = $urlArr['scheme'] .'://'. $urlArr['host'];
    15. self::$data = $data;
    16. if ( !in_array(
    17. self::$method,
    18. array('get', 'post', 'put', 'delete')
    19. )
    20. ) {
    21. exit('error request method type!');
    22. }
    23. $func = self::$method . 'Request';
    24. return self::$func(self::$url);
    25. }
    26. /**
    27. * 基础发起curl请求函数
    28. * @param int $is_post 是否是post请求
    29. */
    30. private function doRequest($is_post = 0) {
    31. $ch = curl_init();//初始化curl
    32. curl_setopt($ch, CURLOPT_URL, self::$url);//抓取指定网页
    33. curl_setopt($ch, CURLOPT_AUTOREFERER, true);
    34. // 来源一定要设置成来自本站
    35. curl_setopt($ch, CURLOPT_REFERER, self::$oriUrl);
    36. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    37. if($is_post == 1) curl_setopt($ch, CURLOPT_POST, $is_post);//post提交方式
    38. if (!empty(self::$data)) {
    39. self::$data = self::dealPostData(self::$data);
    40. curl_setopt($ch, CURLOPT_POSTFIELDS, self::$data);
    41. }
    42. $data = curl_exec($ch);//运行curl
    43. curl_close($ch);
    44. return $data;
    45. }
    46. /**
    47. * 发起get请求
    48. */
    49. public function getRequest() {
    50. return self::doRequest(0);
    51. }
    52. /**
    53. * 发起post请求
    54. */
    55. public function postRequest() {
    56. return self::doRequest(1);
    57. }
    58. /**
    59. * 处理发起非get请求的传输数据
    60. *
    61. * @param array $postData
    62. */
    63. public function dealPostData($postData) {
    64. if (!is_array($postData)) exit('post data should be array');
    65. foreach ($postData as $k => $v) {
    66. $o .= "$k=" . urlencode($v) . "&";
    67. }
    68. $postData = substr($o, 0, -1);
    69. return $postData;
    70. }
    71. /**
    72. * 发起put请求
    73. */
    74. public function putRequest($param) {
    75. return self::doRequest(2);
    76. }
    77. /**
    78. * 发起delete请求
    79. */
    80. public function deleteRequest($param) {
    81. return self::doRequest(3);
    82. }
    83. }
    84. $res = MyCurl::send('http://www.ipip.net/ip.html',array('ip' => '61.142.206.145'),'post');
    85. var_dump($res);die();