微信开发session问题

代码-君 2016-02-04 07:34:34
服务器3个文件 index.php 微信入口文件 menu.php菜单文件 user.php用户信息显示页面
在index.php中 把用户的openid存入到session中 在user.php中不能获取到session的值 按照网上找的方法 自定义了一个session_id 还是没用 求 解决办法

代码太长贴不完 后面贴上代码




回复的时候 请贴上代码 新手 不太明白 说的太抽象 谢谢各位
...全文
1198 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
Drone_xjw 2017-01-11
  • 打赏
  • 举报
回复
请教大神,请问楼主,在公众号中如何保存用户输入的信息 望回复
代码-君 2016-02-04
  • 打赏
  • 举报
回复
index.php 代码 <?php /** * wechat php test */ //define your token header("Content-type: text/html; charset=utf-8"); define("TOKEN", "weixin"); $wechatObj = new wechatCallbackapiTest(); $wechatObj->responseMsg(); class wechatCallbackapiTest { public function valid() { $echoStr = $_GET["echostr"]; //valid signature , option if($this->checkSignature()){ echo $echoStr; exit; } } //连接数据库 public function conn(){ $con = mysql_connect("localhost","zjwdb_443064","Kf159357"); if (!$con) { file_put_contents("log.txt","连接数据库失败".mysql_error(),FILE_APPEND ); } mysql_query("set names 'utf8'"); mysql_select_db("zjwdb_443064",$con); //打开数据库 } public function responseMsg() { //get post data, May be due to the different environments $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //file_put_contents("log.txt",$postStr,FILE_APPEND ); //extract post data if (!empty($postStr)){ /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection, the best way is to check the validity of xml by yourself */ //libxml_disable_entity_loader(true); //这句是默认有的 但是如果不注释掉 不反回信息 $now_time = time(); //当前时间 $this->file_get_weixin_token($now_time); //调用获取token 并且处理永久性方法 $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); // XML 字符串载入对象中 $fromUsername = $postObj->FromUserName; session_id($postObj->fromUsername); session_start(); $toUsername = $postObj->ToUserName; $keyword = trim($postObj->Content); //输入的关键词 $type = $postObj->MsgType; //获取MsgType类型 $x = $postObj->Location_X; //获取x维度 $y = $postObj->Location_Y; //获取y维度 $label = $postObj->Label; //位置信息 $time = time(); $textTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <Content><![CDATA[%s]]></Content> <FuncFlag>0</FuncFlag> </xml>"; session_id($fromUsername); session_start(); /* $ev = $postObj->Event; //获取event参数 具体看事件文档 if($ev == "subscribe"){ //当用户关注的时候 } */ //回复文本信息 if(!empty( $keyword )) //当被动回复 { $info = array(); $arr = $this->_get_xml("token.xml"); //获取xml中的access_token值 $this->conn(); //连接数据库 $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$arr['recipename']}&openid={$fromUsername}"; $result = $this->https_request($url,$data = null); //微信接口数据传输函数 $strjson = json_decode($result); //转为json格式 $name = $strjson->nickname; //昵称 $sex = $strjson->sex; //性别 if($sex==1){ $newsex = "男"; }else{ $newsex = "女"; } $country = $strjson->country; //国籍 $province = $strjson->province; //省份 $city = $strjson->city; //城市 $address = $country.",".$province.",".$city; //拼接地址 $headimgurl = $strjson->headimgurl; //头像 $query = "select * from weixin_user where name='".$name."' and openid = '".$fromUsername."'"; $result = mysql_query($query); $info = mysql_fetch_array($result); $_SESSION['openid'] = $fromUsername; //将openid 存入session //file_put_contents("log.txt","$fromUsername",FILE_APPEND ); if($info == ""){ //如果没有这个数据 //插入新数据 $query = "INSERT INTO weixin_user (name,openid,sex,address,pictuer) VALUES ('".$name."','".$fromUsername."','".$sex."','".$address."','".$headimgurl."')"; mysql_query($query); } /* $msgType="text"; $contentStr = "这是测试回复"; */ //格式化其中的变量 /* $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType,$contentStr); echo $resultStr; */ }else{ echo "Input something..."; } }else { echo ""; exit; } } //获取access_token 并写入xml文件 函数关键逻辑 2小时写入一次xml public function curl_get_weixin_token(){ //获取access_token 并写入xml文件 $appid = "wxdb38002e9fd2466b"; $appsecret = "7b0ab8639408f275d087a8b788a28b3a"; $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); curl_close($ch); $jsoninfo = json_decode($output, true); //print_r($jsoninfo); $access_token = $jsoninfo["access_token"]; //获取acess_token $_clean = array("recipename"=>$access_token,"preptime"=>time()); //参数 access_token值 获取时候的time()时间 $this->_set_xml("token.xml",$_clean); //写入xml文件 return $access_token; } //判断比较方法 public function file_get_weixin_token($now_time){ $arr = $this->_get_xml("token.xml"); //从本地获取xml文件 //如果xml中的文件都没有 或者 当前调用函数的时间-本地时间 > 2小时 if(!$arr || (($now_time - $arr['preptime']) > 7200)){ $access_token = $this->curl_get_weixin_token(); //从远程获取access_token 并写入xml }else{ $access_token = $arr['recipename']; //从本地获取access_token } return $access_token; //返回access_token } /*** * access_token 写入xml文件 * @param unknown $_xmlfile xml 文件 * @param unknown $_clean 参数数组 */ public function _set_xml($_xmlfile,$_clean){ $_fp = @fopen($_xmlfile,'w'); //写入方式打开,将文件指针指向文件头并将文件大小截为零。如果文件不存在则尝试创建之。 if(!$_fp){ exit('系统错误,文件不存在!'); } flock($_fp,LOCK_EX); //要取得独占锁定(写入的程序) $_string = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\t"; //fwrite fwrite(file,string,length) 函数写入文件 /*语法 file 必需。规定要写入的打开文件。 string 必需。规定要写入文件的字符串。 length 可选。规定要写入的最大字节数。 */ fwrite($_fp, $_string,strlen($_string)); // strlen() 函数返回字符串的长度。 $_string = "<recipe>\r\t"; fwrite($_fp, $_string,strlen($_string)); $_string = "\t<recipename>{$_clean['recipename']}</recipename>\r\t"; fwrite($_fp, $_string,strlen($_string)); $_string = "\t<preptime>{$_clean['preptime']}</preptime>\r\t"; fwrite($_fp, $_string,strlen($_string)); $_string = "</recipe>"; fwrite($_fp, $_string,strlen($_string)); flock($_fp,LOCK_UN); //要释放锁定(无论共享或独占) fclose($_fp); //关闭文件 } /* * _get_xml 获取的XML文件 * @access public 表示函数对外公开 * @param $_xmlfile xml文件 * $_html 从XML中取出的数据数组 * */ public function _get_xml($_xmlfile){ $_html = array(); if(file_exists($_xmlfile)){ $xml = ""; $data = ""; $f = @fopen($_xmlfile,'r'); //只读方式打开,将文件指针指向文件头 while($data = fread($f,4096)) { //从文件中读取4096个字节 $xml .= $data; //赋值给变量 } fclose($f); //关闭文件 preg_match_all('/\<recipe>(.*)\<\/recipe\>/s',$xml,$_dom); //正则表达式匹配 foreach($_dom[1] as $_value){ preg_match_all('/\<recipename>(.*)\<\/recipename\>/', $_value,$recipename); preg_match_all('/\<preptime>(.*)\<\/preptime\>/', $_value,$_username); $_html['recipename'] = $recipename[1][0]; $_html['preptime'] = $_username[1][0]; } }else{ die("文件不存在"); } return $_html; } //给微信服务器发送请求 获取用户信息可以使用 public function https_request($url,$data = null){ $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); if (!empty($data)){ curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); } curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($curl); curl_close($curl); return $output; } private function checkSignature() { // you must define TOKEN by yourself if (!defined("TOKEN")) { throw new Exception('TOKEN is not defined!'); } $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"]; $token = TOKEN; $tmpArr = array($token, $timestamp, $nonce); // use SORT_STRING rule sort($tmpArr, SORT_STRING); $tmpStr = implode( $tmpArr ); $tmpStr = sha1( $tmpStr ); if( $tmpStr == $signature ){ return true; }else{ return false; } } } /** * 将xml对象数组 转为普通数组 */ function xmlToArr($xml, $root = true) { if(!$xml->children()) { return (string)$xml; } $array = array(); foreach($xml->children() as $element => $node) { $totalElement = count($xml->{$element}); if(!isset($array[$element])) { $array[$element] = ""; } // Has attributes if($attributes = $node->attributes()) { $data = array(); foreach($attributes as $attr => $value) { $data[$attr] = (string)$value; } if($totalElement > 1) { $data2 = xmlToArr($node, false); $array[$element][] = array_merge($data,$data2); } else { $data2[‘value‘] = (count($node) > 0) ? xmlToArr($node, false) : (string)$node; $array[$element] = array_merge($data,$data2); } } else { if($totalElement > 1) { $array[$element][] = xmlToArr($node, false); } else { $array[$element] = xmlToArr($node, false); } } } if($root) { return array($xml->getName() => $array); } else { return $array; } } $array = array(); ?>
代码-君 2016-02-04
  • 打赏
  • 举报
回复
user.php 代码 <?php session_start(); if(!$_SESSION['openid']){ die("请先关注平台"); } echo $_SESSION['openid']; ?> <!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 http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta content="width=device-width, minimum-scale=1,initial-scale=1, maximum-scale=1, user-scalable=1;" id="viewport" name="viewport" /> <title>微信用户信息</title> </head> <?php $query = "select * from weixin_user where openid='".$_SESSION['openid']."'"; $result = mysql_query($query); while ($arr = mysql_fetch_array($result,MYSQL_ASSOC)){ ?> <p>昵称:<span><?php echo $arr['name'];?></span>   <img src="<?php echo $arr['pictuer'];?>" alt="头像" /></p> <p>性别:<span><?php echo $arr['sex'];?></span></p> <p>地址:<span><?php echo $arr['address'];?></span></p> <?php } ?> <body> </body> </html>
代码-君 2016-02-04
  • 打赏
  • 举报
回复
menu.php 代码 <?php session_start(); $jsonmenu = '{ "button": [ { "name": "个人信息", "sub_button": [ { "type": "view", "name": "信息", "url": "http://www.kfweixin.win/user.php" } ] }, ] }'; /* * _get_xml 获取的XML文件 * @access public 表示函数对外公开 * @param $_xmlfile xml文件 * $_html 从XML中取出的数据数组 * */ function _get_xml($_xmlfile){ $_html = array(); if(file_exists($_xmlfile)){ $xml = ""; $data = ""; $f = @fopen($_xmlfile,'r'); //只读方式打开,将文件指针指向文件头 while($data = fread($f,4096)) { //从文件中读取4096个字节 $xml .= $data; //赋值给变量 } fclose($f); //关闭文件 preg_match_all('/\<recipe>(.*)\<\/recipe\>/s',$xml,$_dom); //正则表达式匹配 foreach($_dom[1] as $_value){ preg_match_all('/\<recipename>(.*)\<\/recipename\>/', $_value,$recipename); preg_match_all('/\<preptime>(.*)\<\/preptime\>/', $_value,$_username); $_html['recipename'] = $recipename[1][0]; $_html['preptime'] = $_username[1][0]; } }else{ die("文件不存在"); } return $_html; } $arr = _get_xml("token.xml"); $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$arr['recipename']}"; $result = https_request($url, $jsonmenu); function https_request($url,$data = null){ $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); if (!empty($data)){ curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); } curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($curl); curl_close($curl); return $output; } ?>

3,143

社区成员

发帖
与我相关
我的任务
社区描述
微信开发即微信公众平台开发,将企业信息、服务、活动等内容通过微信网页的方式进行表现,通过二次开发可以将公众账号由一个媒体型营销工具转化成提供服务的产品。
社区管理员
  • 微信开发
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧