php使用3种post/get方式进行后端提交表单(含json数据)

在php后端服务器使用curl进行模拟表单提交,主要可用于服务器php程序在线更新,服务器php爬虫程序,与信任服务器间的api通信等功能(例如使用第三方SDK时会涉及到接口调用,这时候)。

一、使用curl进行post/get表单提交

<?php

/**
 * CURL请求
 * @param $url 请求url地址 ranjuan.cn
 * @param $method 请求方法 get post
 * @param null $postfields post数据数组
 * @param int $usejson 请求usejson信息-----如果usejson=1 则需要加json头
 * @param bool|false $debug  调试开启 默认false
 * @return mixed
 */
// httpRequest($url,$model,$parms,1,true);
function httpRequest($url, $method, $postfields = null, $usejson = 0, $debug = false) {
    $method = strtoupper($method);
    $ci = curl_init();
    if($usejson == 1){//使用json提交方式需要加http头信息
        $headers =array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length: ' . strlen(json_encode($postfields))
        );
    }else{
        $headers =array();
    }

    /* Curl settings */
    curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) curl ranjuan/20200400 Firefox/34.0");
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间,如果设置为0,则无限等待 */
    curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
    switch ($method) {
        case "POST":
            curl_setopt($ci, CURLOPT_POST, true);
            if (!empty($postfields)) {
                $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                if($usejson == 1){
                    curl_setopt($ci, CURLOPT_POSTFIELDS, json_encode($postfields));
                }else{
                curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
                }
            }
            break;
        default:
isset(explode('?',$url)[1])?($url=$url.'&'.http_build_query($postfields)):($url=$url.'?'.http_build_query($postfields));
		
            curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
            break;
    }
    $ssl = preg_match('/^https:\/\//i',$url) ? TRUE : FALSE;
    curl_setopt($ci, CURLOPT_URL, $url);
    if($ssl){
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
    }
    //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
    curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量,这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
    curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ci, CURLINFO_HEADER_OUT, true);
    /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
    $response = curl_exec($ci);
    $requestinfo = curl_getinfo($ci);
    $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
    if ($debug) {
        echo "<br><br>=====".$method." data======".$url."\r\n<br>";
        var_dump($postfields);
        echo "<br><br>=====info===== \r\n<br>";
        print_r($requestinfo);
        echo "<br><br>=====response=====\r\n<br>";
        print_r($response);
    }
    curl_close($ci);
    return $response;
    //return array($http_code, $response,$requestinfo);
}


}

?>

二、使用socket提交(未亲测,有需要的可到官网查看User Contributed Notes

<?php
/**
 * Socket版本
 * 使用方法:
 * $post_string = "username=admin&password=123456";//需拼接为字符串
 * request_by_socket('ranjuan.cn', '/post_socket.php', $post_string);
 */
// 注意socket里面,提交目标地址的不是将完整url直接提交
// fsockopen()函数中写url顶级域名地址及端口号错误码超时配置等信息
//在fwrite($socket, "POST $remote_path HTTP/1.0"); 语句中的$remote_path变量才是域名后的剩余地址/post_socket.php
function request_by_socket($remote_server,$remote_path,$post_string,$port = 80,$timeout = 30) {
  $socket = fsockopen($remote_server, $port, $errno, $errstr, $timeout);
//$socket =  fsockopen("ssl://".$remote_server, $port, $errno, $errstr, $timeout);//指定443端口使用ssl加密时的打开方式
  if (!$socket) die("$errstr($errno)");
  fwrite($socket, "POST $remote_path HTTP/1.0");
  fwrite($socket, "User-Agent: Socket php get");
  fwrite($socket, "HOST: $remote_server");
  fwrite($socket, "Content-type: application/x-www-form-urlencoded");
//fwrite($socket,"Content-Type: application/json; charset=utf-8");
  fwrite($socket, "Content-length: " . (strlen($post_string) + 8) . "");
  fwrite($socket, "Accept:*/*");
  fwrite($socket, "");
  fwrite($socket, "mypost=$post_string");
  fwrite($socket, "");
  $header = "";
  while ($str = trim(fgets($socket, 4096))) {
    $header .= $str;
  }
  $data = "";
  while (!feof($socket)) {
    $data .= fgets($socket, 4096);
  }
  return $data;
}

?>

方法三、使用file_get_contents

/**
 * 发送post请求
 * @param string $url 请求地址
 * @param array $post_data post键值对数据
 * @return string
 */

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' => 15 * 60 // 超时时间(单位:s)
    )
  );
  $context = stream_context_create($options);
  $result = file_get_contents($url, false, $context);
  return $result;
}
//使用方法
$post_data = array(
  'username' => 'admin',
  'password' => '123456'
);
send_post('http://xx.com/post.php', $post_data);

之前写过一篇php直接输出html代码,在前端进行表单提交的文章,有兴趣的可以参考:php直接输出post/get前端表单&json异步提交

基于互联网精神,在注明出处的前提下本站文章可自由转载!

本文链接:https://ranjuan.cn/php-curl-postget-json-form/

赞赏

微信赞赏支付宝赞赏

妥善保密,请勿截图
美国亚马逊直邮中国的地址写法
p20150205