PHP使用CURL模拟POST/GET/PUT/DELETE方式提交数据
$content = file_get_contents("http://www.doucube.com"); // or $lines = file("http://www.doucube.com"); // or readfile(http://www.doucube.com); 不过,这种做法缺乏灵活性和有效的错误处理。而且,你也不能用它完成一些高难度任务——比如处理coockies、验证、表单提交、文件上传等等。所以选择curl库。 示例代码: <?php $url = 'https://www.google.com'; $method = 'POST'; //headers and data (this is API dependent, some uses XML): //即在接口调用时才用headers 和$data $headers = array( 'Accept: application/json', 'Content-Type: application/json', ); $data = json_encode(array( 'firstName'=> 'John', 'lastName'=> 'Doe' )); // 启动一个CURL会话 $handle = curl_init(); curl_setopt($handle, CURLOPT_URL, $url); // 要访问的地址 curl_setopt($handle,CURLOPT_HEADER,1); // 是否显示返回的Header区域内容 curl_setopt($handle, CURLOPT_HTTPHEADER, $headers); //设置请求头 curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回 curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在 curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查 switch($method) { case 'GET': break; case 'POST': curl_setopt($handle, CURLOPT_POST, true); curl_setopt($handle, CURLOPT_POSTFIELDS, $data); //设置请求体,提交数据包 break; case 'PUT': curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($handle, CURLOPT_POSTFIELDS, $data); //设置请求体,提交数据包 break; case 'DELETE': curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'DELETE'); break; } $response = curl_exec($handle); // 执行操作 $code = curl_getinfo($handle, CURLINFO_HTTP_CODE); // 获取返回的状态码 curl_close ($handle); // 关闭CURL会话 if('200'==$code){ echo "ok"; } 下面还有一个示例,有兴趣可以看看: 用curl上传文件的话很方便,什么header,post串都不用生成了,用fsockopen要写一堆 curl: ============== PHP code $file = array("upimg"=>"@E:/png.png");//文件路径,前面要加@,表明是文件上传. $curl = curl_init("http://localhost/a.php"); curl_setopt($curl,CURLOPT_POST,true); curl_setopt($curl,CURLOPT_POSTFIELDS,$file); curl_exec($curl); fsockopen: =============== PHP code $uploadFile = file_get_contents("E:/png.png"); $boundary = md5(time()); $postStr .="--".$boundary."\r\n";//边界开始,注意默认比header定义的boundary多两个'-' $postStr .="Content-Disposition: form-data; name=\"upimg\"; filename=\"E:/png.png\"\r\n"; $postStr .="Content-Type: image/png\r\n\r\n"; $postStr .=$uploadFile."\r\n"; $postStr .="--".$boundary."\r\n";//边界结束 write($fp,"POST /a.php HTTP/1.0\r\n"); fwrite($fp,"Content-Type: multipart/form-data; boundary=".$boundary."\r\n"); fwrite($fp,"Content-length:".strlen($postStr)."\r\n\r\n"); fwrite($fp,$postStr); while (!feof($fp)) { echo fgets($fp, 128); } fclose($fp); a.php ============== PHP code print_r($_FILES);