PHP接收POST数据的方法总结

 更新时间:2016年11月25日 15:35  点击:1270
POST数据我们常用的接受方式就是$_POST了,其实除了这种方法 之外还有很多的函数变更可以来接受的哦,具体我们来看看下文。


通常情况下用户使用浏览器网页表单向服务器post提交数据,我们使用PHP接收用户POST到服务器的数据,并进行适当的处理。但有些情况下,如用户使用客户端软件向服务端php程序发送post数据,而不能用$_POST来识别,那又该如何处理呢?


$_POST方式接收数据

$_POST方式是通过 HTTP POST 方法传递的变量组成的数组,是自动全局变量。如使用$_POST['name']就可以接收到网页表单以及网页异步方式post过来的数据,即$_POST只能接收文档类型为Content-Type: application/x-www-form-urlencoded提交的数据。

$GLOBALS['HTTP_RAW_POST_DATA']方式接收数据
如果用过post过来的数据不是PHP能够识别的文档类型,比如 text/xml 或者 soap 等等,我们可以用$GLOBALS['HTTP_RAW_POST_DATA']来接收。$HTTP_RAW_POST_DATA 变量包含有原始的POST数据。此变量仅在碰到未识别MIME 类型的数据时产生。$HTTP_RAW_POST_DATA 对于enctype="multipart/form-data" 表单数据不可用。也就是说使用$HTTP_RAW_POST_DATA无法接收网页表单post过来的数据。
php://input方式接收数据
如果访问原始 POST 数据的更好方法是 php://input。php://input 允许读取 POST 的原始数据。和 $HTTP_RAW_POST_DATA 比起来,它给内存带来的压力较小,并且不需要任何特殊的php.ini设置,而php://input不能用于 enctype="multipart/form-data"。
例如,用户使用某个客户端应用程序post给服务器一个文件,文件的内容我们不管它,但是我们要把这个文件完整的保存在服务器上,我们可以使用如下代码:
 
$input = file_get_contents('php://input');
file_put_contents($original, $input); //$original为服务器上的文件

以上代码使用file_get_contents('php://input')接收post数据,然后将数据写入$original文件中,其实可以理解为从客户端上传了一个文件到服务器上,此类应用非常多,尤其是我们PHP开发要与C,C++等应用程序开发进行产品联合开发时会用到,例如本站有文章:拍照上传就是结合flash利用此原理来上传照片的。
以下是一个小示例,演示了$_POST,$GLOBALS['HTTP_RAW_POST_DATA']和php://input三种不同方式的接收POST数据处理:

a.html
 
<form name="demo_form" action="post.php" method="post">
    <p><label>Name: </label><input type="text" class="input" name="name"></p>
    <p><label>Address: </label><input type="text" class="input" name="address"></p>
    <p><input type="submit" name="submit" class="btn" value="Submit"></p>
</form>
post.php
 
header("Content-type:text/html;charset=utf-8");
 
echo '$_POST接收:<br/>';
print_r($_POST);
echo '<hr/>';
 
echo '$GLOBALS[\'HTTP_RAW_POST_DATA\']接收:<br/>';
print_r($GLOBALS['HTTP_RAW_POST_DATA']);
echo '<hr/>';
 
echo 'php://input接收:<br/>';
$data = file_get_contents('php://input');
print_r(urldecode($data));

本文我们来分享一下php利用PHPOffice/PHPExcel类实现数据导入导出的方法实例,后面带数据导入导出的全步骤详细解析。

/**
 * PHPExcel数据导入方法
 * Document:https://github.com/PHPOffice/PHPExcel/blob/develop/Documentation/markdown/Overview/07-Accessing-Cells.md
 * @param string $file 文件名
 * @return msg  SUCCESS:1, FALSE:$msg
 * @author farwish.com
 */
include './PHPExcel.php';
include './PHPExcel/IOFactory.php';
function excelReader($file) {
  if(@fopen($file, 'r')) {
      $objReader = PHPExcel_IOFactory::createReader('Excel2007');
      
      if( ! $objReader->canRead($file)) {
        $objReader = PHPExcel_IOFactory::createReader('Excel5');
        if( ! $objReader->canRead($file)) {
          die('仅支持 .xls 类型的文件 !');
        }
      }
     
      $objReader->setReadDataOnly(true);

      $objPHPExcel = $objReader->load($file);

      $objWorksheet = $objPHPExcel->getActiveSheet();

      $highestRow = $objWorksheet->getHighestRow(); //10

      $highestColumn = $objWorksheet->getHighestColumn(); //C

      $betten = 'A2:'.$highestColumn.$highestRow;

      $dataArray = $objWorksheet->rangeToArray(
          $betten,
          '',
          TRUE,
          TRUE
        );
            
      if($dataArray && is_array($dataArray)) {
          foreach($dataArray as $v) {
              if(intval($v[0]) == 0) {
                  die('数据的格式不正确 !');
              }

              //Your code here...
        $msg = 1;
          }
      } else {
          $msg = '文件没有数据';
      }
  } else {
        $msg = '文件不存在 !';
  }
 
 return $msg; 
}


用phpExcel实现Excel数据的导入导出(全步骤详细解析)

很多文章都有提到关于使用phpExcel实现Excel数据的导入导出,大部分文章都差不多,或者就是转载的,都会出现一些问题,下面是本人研究phpExcel的使用例程总结出来的使用方法,接下来直接进入正题。

首先先说一下,本人的这段例程是使用在Thinkphp的开发框架上,要是使用在其他框架也是同样的方法,很多人可能不能正确的实现Excel的导入导出,问题基本上都是phpExcel的核心类引用路径出错,如果有问题大家务必要对路劲是否引用正确进行测试。

(一)导入Excel

第一,在前台html页面进行上传文件:如:
复制代码 代码如下:

<form method="post" action="php文件" enctype="multipart/form-data">
         <h3>导入Excel表:</h3><input  type="file" name="file_stu" />

           <input type="submit"  value="导入" />
</form>

第二,在对应的php文件进行文件的处理

 if (! empty ( $_FILES ['file_stu'] ['name'] ))

 {
    $tmp_file = $_FILES ['file_stu'] ['tmp_name'];
    $file_types = explode ( ".", $_FILES ['file_stu'] ['name'] );
    $file_type = $file_types [count ( $file_types ) - 1];

     /*判别是不是.xls文件,判别是不是excel文件*/
     if (strtolower ( $file_type ) != "xls")             
    {
          $this->error ( '不是Excel文件,重新上传' );
     }

    /*设置上传路径*/
     $savePath = SITE_PATH . '/public/upfile/Excel/';

    /*以时间来命名上传的文件*/
     $str = date ( 'Ymdhis' );
     $file_name = $str . "." . $file_type;

     /*是否上传成功*/
     if (! copy ( $tmp_file, $savePath . $file_name ))
      {
          $this->error ( '上传失败' );
      }

    /*

       *对上传的Excel数据进行处理生成编程数据,这个函数会在下面第三步的ExcelToArray类中

      注意:这里调用执行了第三步类里面的read函数,把Excel转化为数组并返回给$res,再进行数据库写入

    */
  $res = Service ( 'ExcelToArray' )->read ( $savePath . $file_name );

   /*

        重要代码 解决Thinkphp M、D方法不能调用的问题  

        如果在thinkphp中遇到M 、D方法失效时就加入下面一句代码

    */
   //spl_autoload_register ( array ('Think', 'autoload' ) );

   /*对生成的数组进行数据库的写入*/
   foreach ( $res as $k => $v )
   {
       if ($k != 0)
      {
           $data ['uid'] = $v [0];
           $data ['password'] = sha1 ( '111111' );
           $data ['email'] = $v [1];

           $data ['uname'] = $v [3];

          $data ['institute'] = $v [4];
         $result = M ( 'user' )->add ( $data );
         if (! $result)
         {
              $this->error ( '导入数据库失败' );
          }
      }
   }

}

第三:ExcelToArrary类,用来引用phpExcel并处理Excel数据的

class ExcelToArrary extends Service{

 public function __construct() {

     /*导入phpExcel核心类    注意 :你的路径跟我不一样就不能直接复制*/
     include_once('./Excel/PHPExcel.php');
 }

/**

* 读取excel $filename 路径文件名 $encode 返回数据的编码 默认为utf8

*以下基本都不要修改

*/

public function read($filename,$encode='utf-8'){

          $objReader = PHPExcel_IOFactory::createReader('Excel5');

          $objReader->setReadDataOnly(true);

          $objPHPExcel = $objReader->load($filename);

          $objWorksheet = $objPHPExcel->getActiveSheet();

    $highestRow = $objWorksheet->getHighestRow();
    $highestColumn = $objWorksheet->getHighestColumn();
      $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
      $excelData = array();
    for ($row = 1; $row <= $highestRow; $row++) {
        for ($col = 0; $col < $highestColumnIndex; $col++) {
                 $excelData[$row][] =(string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
           }
         }
        return $excelData;

    }    

 }

第四,以上就是导入的全部内容,phpExcel包附在最后。

(二)Excel的导出(相对于导入简单多了)

第一,先查出数据库里面要生成Excel的数据,如:

$data= M('User')->findAll();   //查出数据
$name='Excelfile';    //生成的Excel文件文件名
$res=service('ExcelToArrary')->push($data,$name);

第二,ExcelToArrary类,用来引用phpExcel并处理数据的   

class ExcelToArrary extends Service{

       public function __construct() {

              /*导入phpExcel核心类    注意 :你的路径跟我不一样就不能直接复制*/
               include_once('./Excel/PHPExcel.php');
       }

     /* 导出excel函数*/
    public function push($data,$name='Excel'){

          error_reporting(E_ALL);
          date_default_timezone_set('Europe/London');
         $objPHPExcel = new PHPExcel();

        /*以下是一些设置 ,什么作者  标题啊之类的*/
         $objPHPExcel->getProperties()->setCreator("转弯的阳光")
                               ->setLastModifiedBy("转弯的阳光")
                               ->setTitle("数据EXCEL导出")
                               ->setSubject("数据EXCEL导出")
                               ->setDescription("备份数据")
                               ->setKeywords("excel")
                              ->setCategory("result file");
         /*以下就是对处理Excel里的数据, 横着取数据,主要是这一步,其他基本都不要改*/
        foreach($data as $k => $v){

             $num=$k+1;
             $objPHPExcel->setActiveSheetIndex(0)

                         //Excel的第A列,uid是你查出数组的键值,下面以此类推
                          ->setCellValue('A'.$num, $v['uid'])   
                          ->setCellValue('B'.$num, $v['email'])
                          ->setCellValue('C'.$num, $v['password'])
            }

            $objPHPExcel->getActiveSheet()->setTitle('User');
            $objPHPExcel->setActiveSheetIndex(0);
             header('Content-Type: application/vnd.ms-excel');
             header('Content-Disposition: attachment;filename="'.$name.'.xls"');
             header('Cache-Control: max-age=0');
             $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
             $objWriter->save('php://output');
             exit;
      }


Ecshop手机网页版本支持在网上找了很多需要花钱购买了,在这里小编整理了一个Ecshop 支付宝手机网页支付免费版供大家参考。

Ecshop 支付宝手机网页支付,针对ecshop wap手机版

ecshop-alipay-wap


<?php
 
/**
* ECSHOP 支付宝手机网页插件
*/
 
if (!defined('IN_ECS'))
{
die('Hacking attempt');
}
 
$payment_lang = ROOT_PATH . 'languages/' .$GLOBALS['_CFG']['lang']. '/payment/alipay_wap.php';
 
if (file_exists($payment_lang))
{
global $_LANG;
 
include_once($payment_lang);
}
 
/* 模块的基本信息 */
if (isset($set_modules) && $set_modules == TRUE)
{
$i = isset($modules) ? count($modules) : 0;
 
/* 代码 */
$modules[$i]['code'] = basename(__FILE__, '.php');
 
/* 描述对应的语言项 */
$modules[$i]['desc'] = 'alipay_wap_desc';
 
/* 是否支持货到付款 */
$modules[$i]['is_cod'] = '0';
 
/* 是否支持在线支付 */
$modules[$i]['is_online'] = '1';
 
/* 作者 */
$modules[$i]['author'] = 'ECSHOP TEAM';
 
/* 网址 */
$modules[$i]['website'] = 'http://www.alipay.com';
 
/* 版本号 */
$modules[$i]['version'] = '1.0.2';
 
/* 配置信息 共用?? */
$modules[$i]['config'] = array(
array('name' => 'alipay_account', 'type' => 'text', 'value' => ''),
array('name' => 'alipay_key', 'type' => 'text', 'value' => ''),
array('name' => 'alipay_partner', 'type' => 'text', 'value' => ''),
array('name' => 'alipay_pay_method', 'type' => 'select', 'value' => '')
);
 
return;
}
 
/**
* 类
*/
class alipay_wap
{
 
/**
* 构造函数
*
* @access public
* @param
*
* @return void
*/
function alipay()
{
}
 
function __construct()
{
$this->alipay();
}
 
/**
* 生成支付代码
* @param array $order 订单信息
* @param array $payment 支付方式信息
*/
function get_code($order, $payment)
{
 
if (!defined('EC_CHARSET'))
{
$charset = 'utf-8';
}
else
{
$charset = EC_CHARSET;
}
 
//合作身份者id,以2088开头的16位纯数字
$alipay_config['partner'] = $payment['alipay_partner'];
 
//签名方式 不需修改
$alipay_config['sign_type'] = '0001';
 
//安全检验码,以数字和字母组成的32位字符
//如果签名方式设置为“MD5”时,请设置该参数
//$alipay_config['key'] = $payment['alipay_key'];
 
//商户的私钥(后缀是.pen)文件相对路径
//如果签名方式设置为“0001”时,请设置该参数
$alipay_config['private_key_path'] = dirname(__FILE__)."/alipay_wap/key/rsa_private_key.pem";
 
//支付宝公钥(后缀是.pen)文件相对路径
//如果签名方式设置为“0001”时,请设置该参数
$alipay_config['ali_public_key_path']= dirname(__FILE__)."/alipay_wap/key/alipay_public_key.pem";
//↑↑↑↑↑↑↑↑↑↑请在这里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
 
//字符编码格式 目前支持 gbk 或 utf-8
$alipay_config['input_charset']= 'utf-8';
 
//ca证书路径地址,用于curl中ssl校验
//请保证cacert.pem文件在当前文件夹目录中
$alipay_config['cacert'] = dirname(__FILE__)."/alipay_wap/cacert.pem";
 
//访问模式,根据自己的服务器是否支持ssl访问,若支持请选择https;若不支持请选择http
$alipay_config['transport'] = 'http';
 
require_once(dirname(__FILE__)."/alipay_wap/lib/alipay_submit.class.php");
 
//返回格式
$format = "xml";
//必填,不需要修改
 
//返回格式
$v = "2.0";
//必填,不需要修改
 
//请求号
$req_id = date('Ymdhis');
//必填,须保证每次请求都是唯一
 
//**req_data详细信息**
 
//服务器异步通知页面路径
$notify_url = return_url(basename(__FILE__, '.php'));
//需http://格式的完整路径,不允许加?id=123这类自定义参数
 
//页面跳转同步通知页面路径
$call_back_url = return_url(basename(__FILE__, '.php'));
//需http://格式的完整路径,不允许加?id=123这类自定义参数
 
//操作中断返回地址
$merchant_url = $GLOBALS['ecs']->url();
//用户付款中途退出返回商户的地址。需http://格式的完整路径,不允许加?id=123这类自定义参数
 
//卖家支付宝帐户
$seller_email = $payment['alipay_account'];
//必填
 
//商户订单号
$out_trade_no = $order['order_sn'] . $order['log_id'];
//商户网站订单系统中唯一订单号,必填
 
//订单名称
$subject = $order['order_sn'];
//必填
 
//付款金额
$total_fee = $order['order_amount'];
//必填
 
//请求业务参数详细
$req_data = '<direct_trade_create_req><notify_url>' . $notify_url . '</notify_url><call_back_url>' . $call_back_url . '</call_back_url><seller_account_name>' . $seller_email . '</seller_account_name><out_trade_no>' . $out_trade_no . '</out_trade_no><subject>' . $subject . '</subject><total_fee>' . $total_fee . '</total_fee><merchant_url>' . $merchant_url . '</merchant_url></direct_trade_create_req>';
//必填
 
/************************************************************/
 
//构造要请求的参数数组,无需改动
$para_token = array(
"service" => "alipay.wap.trade.create.direct",
"partner" => trim($alipay_config['partner']),
"sec_id" => trim($alipay_config['sign_type']),
"format" => $format,
"v" => $v,
"req_id" => $req_id,
"req_data" => $req_data,
"_input_charset" => trim(strtolower($alipay_config['input_charset']))
);
 
//建立请求
$alipaySubmit = new AlipaySubmit($alipay_config);
$html_text = $alipaySubmit->buildRequestHttp($para_token);
 
//URLDECODE返回的信息
$html_text = urldecode($html_text);
 
//解析远程模拟提交后返回的信息
$para_html_text = $alipaySubmit->parseResponse($html_text);
 
//获取request_token
$request_token = $para_html_text['request_token'];
 
/**************************根据授权码token调用交易接口alipay.wap.auth.authAndExecute**************************/
 
//业务详细
$req_data = '<auth_and_execute_req><request_token>' . $request_token . '</request_token></auth_and_execute_req>';
//必填
 
//构造要请求的参数数组,无需改动
$parameter = array(
"service" => "alipay.wap.auth.authAndExecute",
"partner" => trim($alipay_config['partner']),
"sec_id" => trim($alipay_config['sign_type']),
"format" => $format,
"v" => $v,
"req_id" => $req_id,
"req_data" => $req_data,
"_input_charset" => trim(strtolower($alipay_config['input_charset']))
);
 
//建立请求
$alipaySubmit = new AlipaySubmit($alipay_config);
$html_text = $alipaySubmit->buildRequestForm($parameter, 'get', '进行付款');
return $html_text;
}
 
/**
* 响应操作
*/
function respond()
{
if (!empty($_POST))
{
foreach($_POST as $key => $data)
{
$_GET[$key] = $data;
}
}
 
log_write($_GET, 'alipay_wap');
$payment = get_payment($_GET['code']);
$seller_email = rawurldecode($_GET['seller_email']);
$order_sn = str_replace($_GET['subject'], '', $_GET['out_trade_no']);
$order_sn = trim($order_sn);
 
/* 检查数字签名是否正确 */
ksort($_GET);
reset($_GET);
 
//合作身份者id,以2088开头的16位纯数字
$alipay_config['partner'] = $payment['alipay_partner'];
 
//签名方式 不需修改
$alipay_config['sign_type'] = '0001';
 
//安全检验码,以数字和字母组成的32位字符
//如果签名方式设置为“MD5”时,请设置该参数
//$alipay_config['key'] = $payment['alipay_key'];
 
//商户的私钥(后缀是.pen)文件相对路径
//如果签名方式设置为“0001”时,请设置该参数
$alipay_config['private_key_path'] = dirname(__FILE__)."/alipay_wap/key/rsa_private_key.pem";
 
//支付宝公钥(后缀是.pen)文件相对路径
//如果签名方式设置为“0001”时,请设置该参数
$alipay_config['ali_public_key_path']= dirname(__FILE__)."/alipay_wap/key/alipay_public_key.pem";
//↑↑↑↑↑↑↑↑↑↑请在这里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
 
//字符编码格式 目前支持 gbk 或 utf-8
$alipay_config['input_charset']= 'utf-8';
 
//ca证书路径地址,用于curl中ssl校验
//请保证cacert.pem文件在当前文件夹目录中
$alipay_config['cacert'] = dirname(__FILE__)."/alipay_wap/cacert.pem";
 
//访问模式,根据自己的服务器是否支持ssl访问,若支持请选择https;若不支持请选择http
$alipay_config['transport'] = 'http';
 
require_once(dirname(__FILE__)."/alipay_wap/lib/alipay_notify.class.php");
 
//计算得出通知验证结果
$alipayNotify = new AlipayNotify($alipay_config);
$verify_result = $alipayNotify->verifyNotify();
 
if(!$verify_result) {//验证不成功
return false;
}
 
$notify_data = $alipayNotify->decrypt($_GET['notify_data']);
 
$doc = new DOMDocument();
$doc->loadXML($notify_data);
 
if( ! empty($doc->getElementsByTagName( "notify" )->item(0)->nodeValue) ) {
//商户订单号
$out_trade_no = $doc->getElementsByTagName( "out_trade_no" )->item(0)->nodeValue;
$out_trade_no = str_replace($_GET['subject'], '', $out_trade_no);
$out_trade_no = trim($out_trade_no);
//支付宝交易号
$trade_no = $doc->getElementsByTagName( "trade_no" )->item(0)->nodeValue;
//交易状态
$trade_status = $doc->getElementsByTagName( "trade_status" )->item(0)->nodeValue;
 
/* 检查支付的金额是否相符 */
if (!check_money($out_trade_no, $_GET['total_fee']))
{
return false;
}
 
if($_GET['trade_status'] == 'TRADE_FINISHED') {
/* 改变订单状态 */
order_paid($out_trade_no);
return true;
}else if ($_GET['trade_status'] == 'TRADE_SUCCESS') {
/* 改变订单状态 */
order_paid($out_trade_no, 2);
 
return true;
}else{
return false;
}
}
 
}
}
 
?>

微信扫码网站自动登录的原是还是比较简单的,只要各位知道相互的原理就可以实现了,下面我们来看两个例子,我相信各位看了这两个例子肯定知道怎么来做了。

magento 微信扫码网站自动登录

案例仿照了微信联合登陆的做法,微信联合登陆介绍:

https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&lang=zh_CN

查看授权后接口调用(UnionID),不难发现填写回调地址,用户确认登陆pc端即可跳转

获取UnionID方法

public function wcallbackAction(){
 
$code = $_GET['code'];
$state = $_GET['state'];
$setting = include CONFIG_PATH . 'setting.php';
$appid=$setting['weixin']['appid'];
$appsecret=$setting['weixin']['appsecret'];
 
if (empty($code)) $this->showMessage('授权失败');
try{
 
$token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
 
$token = json_decode($this->https_request($token_url));
 
}catch(Exception $e)
{
print_r($e);
}
 
if (isset($token->errcode)) {
echo '<h1>错误:</h1>'.$token->errcode;
echo '<br/><h2>错误信息:</h2>'.$token->errmsg;
exit;
}
 
$access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$token->refresh_token;
//转成对象
$access_token = json_decode($this->https_request($access_token_url));
if (isset($access_token->errcode)) {
echo '<h1>错误:</h1>'.$access_token->errcode;
echo '<br/><h2>错误信息:</h2>'.$access_token->errmsg;
exit;
}
$user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token->access_token.'&openid='.$access_token->openid.'&lang=zh_CN';
//转成对象
$user_info = json_decode($this->https_request($user_info_url));
if (isset($user_info->errcode)) {
echo '<h1>错误:</h1>'.$user_info->errcode;
echo '<br/><h2>错误信息:</h2>'.$user_info->errmsg;
exit;
}
//打印用户信息
// echo '<pre>';
// print_r($user_info);
// echo '</pre>';
 
//获取unionid
 
$uid=$user_info->unionid;
 
}
 
//用户操作处理 分为再次登录和第一次登陆
 
$sql="select h_user_id from dtb_user_binded as t1 left join dtb_user_weixin as t2 on t1.u_id=t2.id where t1.u_type='".
User::$arrUtype['weixin_num_t']."' and t2.openid='$user_info->unionid'";
$h_user_id = Core_Db::getOne($sql);
if(!empty($h_user_id)){//该weixin号再次登录
 
}{//该weixin号第一次登录
 
}

php 微信扫码 pc端自动登陆注册


用的接口scope 是snsapi_userinfo,微信登陆一个是网页授权登陆,另一个是微信联合登陆

网页授权登陆:http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html

微信联合登陆:https://open.weixin.qq.com/cgi-bin/frame?t=home/web_tmpl&lang=zh_CN

一:首先把微信链接带个标识生成二维码

比如链接为 https://open.weixin.qq.com/connect/oauth2/authorize?appid=’.$appid.’&redirect_uri=’.$url.’&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect’  我们可以在state上做文章,因为state你传入什么微信那边返回什么

可以作为服务器与微信段的一个标识


public function creatqrAction(){

if($_GET['app']){
$wtoken=$_COOKIE['wtoken'];
$postdata=$_SESSION['w_state'];
if($wtoken){
$postdata=$wtoken;
}
<span style="color: #3366ff;">include CONFIG_PATH . 'phpqrcode/'.'phpqrcode.php';</span>
$sh=$this-&gt;shar1();
$value="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx138697ef383a9167&amp;redirect_uri=http://www.xxx.net/login/wcallback&amp;response_type=code&amp;scope=snsapi_userinfo&amp;state=".$postdata."&amp;connect_redirect=1#wechat_redirect";

$errorCorrectionLevel = "L";

$matrixPointSize = "5";

QRcode::png($value, false, $errorCorrectionLevel, $matrixPointSize);
}

}

此时生成了二维码 state是标识,phpqrcode可以在文章末尾下载,这样我们设置了回调地址http://www.xxx.net/login/wcallback

就可以在wcallback方法里面处理数据 插入用户 生成session,跳转登陆,pc端可以设置几秒钟ajax请求服务器,一旦获取到了

state,即实现调整,微信浏览器里处理完后可以关闭窗口,微信js可实现


document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() {
WeixinJSBridge.call('closeWindow');

}, false);

也可以授权登陆成功后跳转到微信服务号关注页面


header("Location: weixin://profile/gh_a5e1959f9a4e");

wcallback方法做处理登陆


$code = $_GET['code'];
$state = $_GET['state'];
$setting = include CONFIG_PATH . 'setting.php';
$appid=$setting['weixin']['appid'];
$appsecret=$setting['weixin']['appsecret'];

if (empty($code)) $this->showMessage('授权失败');
try{

$token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';

$token = json_decode($this->https_request($token_url));

}catch(Exception $e)
{
print_r($e);
}

if (isset($token->errcode)) {
echo '<h1>错误:</h1>'.$token->errcode;
echo '<br/><h2>错误信息:</h2>'.$token->errmsg;
exit;
}

$access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$token->refresh_token;
//转成对象
$access_token = json_decode($this->https_request($access_token_url));
if (isset($access_token->errcode)) {
echo '<h1>错误:</h1>'.$access_token->errcode;
echo '<br/><h2>错误信息:</h2>'.$access_token->errmsg;
exit;
}
$user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token->access_token.'&openid='.$access_token->openid.'&lang=zh_CN';
//转成对象
$user_info = json_decode($this->https_request($user_info_url));
if (isset($user_info->errcode)) {
echo '<h1>错误:</h1>'.$user_info->errcode;
echo '<br/><h2>错误信息:</h2>'.$user_info->errmsg;
exit;
}
//打印用户信息
// echo '<pre>';
// print_r($user_info);
// echo '</pre>';

GD库是php中一个默认的强大的图片处理库了,我们可以利用它来对图片进行一些操作或生成图片的操作,下面我们来看文字图片水印缩略图在php中的实例。

一:添加文字水印 使用方法

require 'image.class.php'
$src="001.jpg";
$content="hello";
$font_url="my.ttf";
$size=20;
$image=new Image($src);
$color=array(
0=>255,
1=>255,
2=>255,
2=>20
);
$local=array(
'x'=>20,
'y'=>30
);
$angle=10;
$image->fontMark($content,$font_url,$size,$color,$local,$angle);
$image->show();


二:图片缩略图 使用方法:


require 'image.class.php'
$src="001.jpg";
$image=new Image($src);
$image->thumb(300,200);
$image->show();


三:image.class.php

class image{
private $info;
private $image;
public function __contruct($src){
$info= getimagesize($src);
$this->info=array(
'width'=> $info[0],
'height'=>$info[1],
'type'=>image_type_to_extension($info[2],false),
'mime'=>$info['mime'],
 
);
$fun="imagecreatefrom{$this->info['type']}";
 
$this->image= $fun($src);
 
}
 
//缩略图
public function thumd($width,$height){
$image_thumb= imagecreatetruecolor($width,$height);
imagecopyresampled($image_thumb,$this->image,0,0,0,0,$width,$height,$this->info['width'],$this->info['height']);
imagedestroy($this->image);
$this->image=$image_thumb;
 
}
//文字水印
public function fontMark($content,$font_url,$size,$color,$local,$angle){
 
$col=imagecolorallocatealpha($this->image,$color[0],$color[1],$color[2],$color[3]);
$text=imagettftext($this->image,$size,$angle,$local['x'],$local['y'],$col,$font_url,$content);
}
//输出图片
public function show()
{
header("Content-type:",$this->info['mime']);
 
$func="image{$this->info['type']}";
$func($this->image);
 
}
public function save($nwename){
$func="image{$this->info['type']}";
//从内存中取出图片显示
$func($this->image);
//保存图片
$func($this->image,$nwename.$this->info['type']);
 
}
public function _destruct(){
 
imagedestroy($this->image);
}
 
}

[!--infotagslink--]

相关文章

  • C#连接SQL数据库和查询数据功能的操作技巧

    本文给大家分享C#连接SQL数据库和查询数据功能的操作技巧,本文通过图文并茂的形式给大家介绍的非常详细,需要的朋友参考下吧...2021-05-17
  • php 中file_get_contents超时问题的解决方法

    file_get_contents超时我知道最多的原因就是你机器访问远程机器过慢,导致php脚本超时了,但也有其它很多原因,下面我来总结file_get_contents超时问题的解决方法总结。...2016-11-25
  • php抓取网站图片并保存的实现方法

    php如何实现抓取网页图片,相较于手动的粘贴复制,使用小程序要方便快捷多了,喜欢编程的人总会喜欢制作一些简单有用的小软件,最近就参考了网上一个php抓取图片代码,封装了一个php远程抓取图片的类,测试了一下,效果还不错分享...2015-10-30
  • php简单数据操作的实例

    最基础的对数据的增加删除修改操作实例,菜鸟们收了吧...2013-09-26
  • 解决Mybatis 大数据量的批量insert问题

    这篇文章主要介绍了解决Mybatis 大数据量的批量insert问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-01-09
  • HTTP 408错误是什么 HTTP 408错误解决方法

    相信很多站长都遇到过这样一个问题,访问页面时出现408错误,下面一聚教程网将为大家介绍408错误出现的原因以及408错误的解决办法。 HTTP 408错误出现原因: HTT...2017-01-22
  • Antd-vue Table组件添加Click事件,实现点击某行数据教程

    这篇文章主要介绍了Antd-vue Table组件添加Click事件,实现点击某行数据教程,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-11-17
  • Android子控件超出父控件的范围显示出来方法

    下面我们来看一篇关于Android子控件超出父控件的范围显示出来方法,希望这篇文章能够帮助到各位朋友,有碰到此问题的朋友可以进来看看哦。 <RelativeLayout xmlns:an...2016-10-02
  • 详解如何清理redis集群的所有数据

    这篇文章主要介绍了详解如何清理redis集群的所有数据,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-18
  • gin 获取post请求的json body操作

    这篇文章主要介绍了gin 获取post请求的json body操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-15
  • ps把文字背景变透明的操作方法

    ps软件是现在非常受大家喜欢的一款软件,有着非常不错的使用功能。这次文章就给大家介绍下ps把文字背景变透明的操作方法,喜欢的一起来看看。 1、使用Photoshop软件...2017-07-06
  • vue 获取到数据但却渲染不到页面上的解决方法

    这篇文章主要介绍了vue 获取到数据但却渲染不到页面上的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-11-19
  • intellij idea快速查看当前类中的所有方法(推荐)

    这篇文章主要介绍了intellij idea快速查看当前类中的所有方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-09-02
  • C#使用Http Post方式传递Json数据字符串调用Web Service

    这篇文章主要为大家详细介绍了C#使用Http Post方式传递Json数据字符串调用Web Service,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2020-06-25
  • Mysql select语句设置默认值的方法

    1.在没有设置默认值的情况下: 复制代码 代码如下:SELECT userinfo.id, user_name, role, adm_regionid, region_name , create_timeFROM userinfoLEFT JOIN region ON userinfo.adm_regionid = region.id 结果:...2014-05-31
  • js导出table数据到excel即导出为EXCEL文档的方法

    复制代码 代码如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta ht...2013-10-13
  • mysql 批量更新与批量更新多条记录的不同值实现方法

    批量更新mysql更新语句很简单,更新一条数据的某个字段,一般这样写:复制代码 代码如下:UPDATE mytable SET myfield = 'value' WHERE other_field = 'other_value';如果更新同一字段为同一个值,mysql也很简单,修改下where即...2013-10-04
  • php把读取xml 文档并转换成json数据代码

    在php中解析xml文档用专门的函数domdocument来处理,把json在php中也有相关的处理函数,我们要把数据xml 数据存到一个数据再用json_encode直接换成json数据就OK了。...2016-11-25
  • ps怎么制作倒影 ps设计倒影的方法

    ps软件是一款非常不错的图片处理软件,有着非常不错的使用效果。这次文章要给大家介绍的是ps怎么制作倒影,一起来看看设计倒影的方法。 用ps怎么做倒影最终效果&#819...2017-07-06
  • mybatis-plus 处理大数据插入太慢的解决

    这篇文章主要介绍了mybatis-plus 处理大数据插入太慢的解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-12-18