PHP发送post请求的两种方式

第一种方式:curl

    /* 
     * curl发送post请求	
     * url:访问路径  
     * array:要传递的数组  
     * */  
    protected function curl_post($url,$array){  
		$curl = curl_init();  
		//设置提交的url
		curl_setopt($curl, CURLOPT_URL, $url);  
		//设置头文件的信息作为数据流输出  
		curl_setopt($curl, CURLOPT_HEADER, 0);  
		//设置获取的信息以文件流的形式返回,而不是直接输出  
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);  
		//设置post方式提交  
		curl_setopt($curl, CURLOPT_POST, 1);
		// 最大执行时间超时时间(单位:s)
		curl_setopt($curl, CURLOPT_TIMEOUT, 120);			
		//设置post数据
		curl_setopt($curl, CURLOPT_POSTFIELDS, $array);  
		//执行命令
		$data = curl_exec($curl);
		//获得数据并返回
		return $data;
		//关闭URL请求
		curl_close($curl);
    }

第二种方式:file_get_contents

    /**
	 * 发送post请求
	 * @param string $url 请求地址
	 * @param array $post_data post键值对数据
	 * @return string
	 */
	protected function send_post($url, $post_data) {
		$postdata = http_build_query($post_data);
		$options = array(
		'http' => array(
			'method' => 'POST',
			'header' => 'Content-type:application/x-www-form-urlencoded',
			'content' => $postdata,
			'timeout' => 120 // 超时时间(单位:s)
		)
	  );
		$context = stream_context_create($options);
		$result = file_get_contents($url, false, $context);
		return $result;
	}	

 

你可能感兴趣的:(#,PHP基础)