PHP简单MVC架构
由于需要搭建一个简单的框架来进行API接口开发,所以简单的mvc框架当然是首选.最原始,最简洁的mvc框架.下面来介绍下.
app
|-controller 存放控制器文件
|-model 存放模型文件
|-view 存放视图文件
core
|-lib 存放自定义类库
|-config 存放配置文件
|--config.php 系统配置文件
|--conn.php 数据库连接文件
|--db_config.php
数据库配置文件
|-mysql_db.php 数据库类文件
|-runtime 缓存文件
db_caches 数据库缓存文件
logs日志文件
|-index.php 入口文件
| -dispatcher.php
| -loader.php
| -router.php
1.先介绍index.php,附源码:
<?php
include("./core/ini.php");
include("./core/config/config.php");
include("./core/global.fun.php");
include("./core/common.php");
initializer::initialize();//加载将要用到的目录文件,即调用initializer类的一个静态函数initialize,因为我们在ini.php,设置了include_path,以及定义了__autoload,所以程序会自动在core/main目录查找initializer.php.
$router = loader::load("router");//加载URL处理文件,对url进行解析--加载loader函数的静态函数load
dispatcher::dispatch($router);//router.php文件,这个文件的作用就是映射URL,对URL进行解析.根据解析到的URL参数加载相关controller及action
?>
2.初始化项目文件 ./core/ini.php 源码:
<?php
set_include_path(get_include_path() . PATH_SEPARATOR . "core/main");
//set_include_path — Sets the include_path configuration option
function __autoload($object){
require_once("{$object}.php");
}
这个文件首先设置了include_path,也就是我们如果要找包含的文件,告诉系统在这个目录下查找。其实我们定义__autoload()方法,这个方法是在PHP5增加的,就是当我们实例化一个函数的时候,如果本文件没有,就会自动去加载文件
3.加载系统配置文件./core/config.php 源码:
<?php
/*
* 设置页面编码格式
*/
header("content-type:text/html;charset=utf-8");
//禁用错误报告
error_reporting(0);
date_default_timezone_set("PRC");
//定义常量
define("URL_PATH","http://blog.csdn.net/haiqiao_2010");//服务器IP
define("IMG_PATH","http://blog.csdn.net/haiqiao_2010");//服务器图片目录
//判断日志是否开启
defined("APP_LOG") or define("APP_LOG",true);
if (APP_LOG) {
$GLOBALS["log"] = new APIlog();
set_exception_handler(array($GLOBALS["log"],"quit"));
set_error_handler(array($GLOBALS["log"],"error_handle"));
}
define("IS_CGI",substr(PHP_SAPI, 0,3)=="cgi" ? 1 : 0 );
define("IS_WIN",strstr(PHP_OS, "WIN") ? 1 : 0 );
define("IS_CLI",PHP_SAPI=="cli"? 1 : 0);
if(!defined("APP_NAME")) define("APP_NAME", basename(dirname($_SERVER["SCRIPT_FILENAME"])));
if(!IS_CLI) {
// 当前文件名
if(!defined("_PHP_FILE_")) {
if(IS_CGI) {
//CGI/FASTCGI模式下
$_temp = explode(".php",$_SERVER["PHP_SELF"]);
define("_PHP_FILE_", rtrim(str_replace($_SERVER["HTTP_HOST"],"",$_temp[0].".php"),"/"));
}else {
define("_PHP_FILE_", rtrim($_SERVER["SCRIPT_NAME"],"/"));
}
}
if(!defined("__ROOT__")) {
// 网站URL根目录
if( strtoupper(APP_NAME) == strtoupper(basename(dirname(_PHP_FILE_))) ) {
$_root = dirname(dirname(_PHP_FILE_));
}else {
$_root = dirname(_PHP_FILE_);
}
define("__ROOT__", (($_root=="/" || $_root=="\")?"":$_root));
}
//支持的URL模式
define("URL_COMMON", 0); //普通模式
define("URL_PATHINFO", 1); //PATHINFO模式
define("URL_REWRITE", 2); //REWRITE模式
define("URL_COMPAT", 3); // 兼容模式
}
if(!defined("APP_ROOT")) {//项目根路径
// 网站URL根目录
$_root = dirname(_PHP_FILE_);
$_root = (($_root=="/" || $_root=="\")?"":$_root);
$_root = str_replace("/system","",$_root);
define("APP_ROOT", $_root );
}
if(!defined("APP_ROOT_PATH"))//项目绝对路径
define("APP_ROOT_PATH", str_replace("\","/",substr(dirname(__FILE__),0,-11)));
if(!defined("PAGE_SIZE"))//im:页面大小
define("PAGE_SIZE",15);
?>
4.加载通用的方法的文件./core/global_fun.php 源码:
<?php
//header("content-type:text/html;charset=utf-8");
/*
* 过滤sql语句的关键字
*/
function strip_sql($string){
global $search_arr,$replace_arr;
return is_array($string) ? array_map("strip_sql", $string) : preg_replace($search_arr, $replace_arr, $string);
}
function new_htmlspecialchars($string){
return is_array($string) ? array_map("new_htmlspecialchars", $string) : htmlspecialchars($string,ENT_QUOTES);
}
function new_addslashes($string){
if(!is_array($string)) return addslashes($string);
foreach($string as $key => $val) $string[$key] = new_addslashes($val);
return $string;
}
function new_stripslashes($string)
{
if(!is_array($string)) return stripslashes($string);
foreach($string as $key => $val) $string[$key] = new_stripslashes($val);
return $string;
}
function strip_textarea($string){
return nl2br(str_replace(" ", " ", htmlspecialchars($string, ENT_QUOTES)));
}
function strip_js($string, $js = 1){
$string = str_replace(array("
","
","""),array("","","\""),$string);
return $js==1 ? "document.write("".$string."");
" : $string;
}
//邮件格式验证的函数
function check_email($email)
{
if(!preg_match("/^w+((-w+)|(.w+))*@[A-Za-z0-9]+((.|-)[A-Za-z0-9]+)*.[A-Za-z0-9]+$/",$email))
{
return false;
}
else
return true;
}
//验证手机号码
function check_mobile($mobile)
{
$pattern = "/^1d{10}$/";
if (preg_match($pattern,$mobile))
{
Return true;
}
else
{
Return false;
}
}
//获取GMTime
function get_gmtime()
{
return (time() - date("Z"));
}
function to_date($utc_time, $format = "Y-m-d H:i:s") {
if (empty ( $utc_time )) {
return "";
}
$timezone = 8;
$time = $utc_time + $timezone * 3600;
return date ($format, $time );
}
function to_timespan($str, $format = "Y-m-d H:i:s")
{
$timezone = 8;
$time = intval(strtotime($str));
if($time!=0)
$time = $time - $timezone * 3600;
return $time;
}
function get_http()
{
return (isset($_SERVER["HTTPS"]) && (strtolower($_SERVER["HTTPS"]) != "off")) ? "https://" : "http://";
}
function get_domain()
{
/* 协议 */
$protocol = get_http();
/* 域名或IP地址 */
if (isset($_SERVER["HTTP_X_FORWARDED_HOST"]))
{
$host = $_SERVER["HTTP_X_FORWARDED_HOST"];
}
elseif (isset($_SERVER["HTTP_HOST"]))
{
$host = $_SERVER["HTTP_HOST"];
}
else
{
/* 端口 */
if (isset($_SERVER["SERVER_PORT"]))
{
$port = ":" . $_SERVER["SERVER_PORT"];
if ((":80" == $port && "http://" == $protocol) || (":443" == $port && "https://" == $protocol))
{
$port = "";
}
}
else
{
$port = "";
}
if (isset($_SERVER["SERVER_NAME"]))
{
$host = $_SERVER["SERVER_NAME"] . $port;
}
elseif (isset($_SERVER["SERVER_ADDR"]))
{
$host = $_SERVER["SERVER_ADDR"] . $port;
}
}
return $protocol . $host;
}
function get_host()
{
/* 域名或IP地址 */
if (isset($_SERVER["HTTP_X_FORWARDED_HOST"]))
{
$host = $_SERVER["HTTP_X_FORWARDED_HOST"];
}
elseif (isset($_SERVER["HTTP_HOST"]))
{
$host = $_SERVER["HTTP_HOST"];
}
else
{
if (isset($_SERVER["SERVER_NAME"]))
{
$host = $_SERVER["SERVER_NAME"];
}
elseif (isset($_SERVER["SERVER_ADDR"]))
{
$host = $_SERVER["SERVER_ADDR"];
}
}
return $host;
}
/*
* 实现AES加密
* $str : 要加密的字符串
* $keys : 加密密钥
* $iv : 加密向量
* $cipher_alg : 加密方式
*/
function aes_ecryptdString($str,$keys="1034567890666450",$iv="1034567890123450",$cipher_alg=MCRYPT_RIJNDAEL_128){
// $encrypted_string= base64_encode(bin2hex(mcrypt_encrypt($cipher_alg,$keys, $str, MCRYPT_MODE_CBC,$iv)));
$encrypted_string= bin2hex(mcrypt_encrypt($cipher_alg,$keys, $str, MCRYPT_MODE_CBC,$iv));
return $encrypted_string;
}
/*
* 实现AES解密
* $str : 要解密的字符串
* $keys : 加密密钥
* $iv : 加密向量
* $cipher_alg : 加密方式
*/
function aes_decryptString($str,$keys="1034567890666450",$iv="1034567890123450",$cipher_alg=MCRYPT_RIJNDAEL_128){
// $str= base64_decode($str);
$decrypted_string= mcrypt_decrypt($cipher_alg,$keys,pack("H*",$str),MCRYPT_MODE_CBC,$iv);
return $decrypted_string;
}
/**
* 对数组进行转码操作
* @param $array
* @param $in_charset
* @param $out_charset
*/
function iconv_array(&$array,$in_charset,$out_charset)
{
if(UC_CHARSET!="utf-8")
{
foreach($array as $k=>$v)
{
if(is_array($array[$k]))
{
iconv_array($array[$k],$in_charset,$out_charset);
}
else
{
$array[$k] = iconv($in_charset,$out_charset,$array[$k]);
}
}
}
}
/**
* utf8字符转Unicode字符
* @param string $char 要转换的单字符
* @return void
*/
function utf8_to_unicode($char)
{
switch(strlen($char))
{
case 1:
return ord($char);
case 2:
$n = (ord($char[0]) & 0x3f) << 6;
$n += ord($char[1]) & 0x3f;
return $n;
case 3:
$n = (ord($char[0]) & 0x1f) << 12;
$n += (ord($char[1]) & 0x3f) << 6;
$n += ord($char[2]) & 0x3f;
return $n;
case 4:
$n = (ord($char[0]) & 0x0f) << 18;
$n += (ord($char[1]) & 0x3f) << 12;
$n += (ord($char[2]) & 0x3f) << 6;
$n += ord($char[3]) & 0x3f;
return $n;
}
}
/**
* utf8字符串分隔为unicode字符串
* @param string $str 要转换的字符串
* @param string $depart 分隔,默认为空格为单字
* @return string
*/
function str_to_unicode_word($str,$depart=" ")
{
$arr = array();
$str_len = mb_strlen($str,"utf-8");
for($i = 0;$i < $str_len;$i++)
{
$s = mb_substr($str,$i,1,"utf-8");
if($s != " " && $s != " ")
{
$arr[] = "ux".utf8_to_unicode($s);
}
}
return implode($depart,$arr);
}
/**
* utf8字符串分隔为unicode字符串
* @param string $str 要转换的字符串
* @return string
*/
function str_to_unicode_string($str)
{
$string = str_to_unicode_word($str,"");
return $string;
}
//分词
function div_str($str)
{
require_once APP_ROOT_PATH."core/lib/words.php";
$words = words::segment($str);
$words[] = $str;
return $words;
}
/**
* @desc im:十进制数转换成三十六机制数
* @param (int)$num 十进制数
* return 返回:三十六进制数
*/
function get_code_bynum($num) {
$num = intval($num);
if ($num <= 0)
return false;
$codeArr = array("0","1","2","3","4","5","6","7","8","9","A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
$code = "";
do {
$key = ($num - 1) % 36;
$code = $codeArr[$key] . $code;
$num = floor(($num - $key) / 36);
} while ($num > 0);
return $code;
}
/**
* @desc im:三十六进制数转换成十机制数
* @param (string)$str 三十六进制数
* return 返回:十进制数
*/
function get_num_bycode($str){
$array=array("0","1","2","3","4","5","6","7","8","9","A", "B", "C", "D","E", "F", "G", "H", "I", "J", "K", "L","M", "N", "O","P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y","Z");
$len=strlen($str);
for($i=0;$i<$len;$i++){
$index=array_search($str[$i],$array);
$sum+=($index+1)*pow(36,$len-$i-1);
}
return $sum;
}
?>
5.加载公共方法的文件./core/common.php 源码:
<?php
function app_conf($name)
{
return $GLOBALS["db"]->getOne("select value from ".DB_PREFIX."conf where name="".$name.""");
}
/*
* @des:im:验证手机号码
* @param:$phone
*/
function check_phone($phone)
{
if(!empty($phone) && !preg_match("/^1d{10}$/",$phone))
{
return false;
}
else
return true;
}
/**
* @desc get_pwd_strength()im:根据密码字符串判断密码结构
* @param (string)$mobile
* return 返回:$msg
*/
function get_pwd_strength($pwd){
if (strlen(iconv("UTF-8","GBK",$pwd))>30 || strlen(iconv("UTF-8","GBK",$pwd))<6)
{
return "密码是6-30位的字符串,且必须由字母和数字组成.";
}
if(preg_match("/^d+$/",$pwd))
{
return "密码不能为全数字";//全数字
}
if(preg_match("/^[a-z]+$/i",$pwd))
{
return "密码不能为全字母";//全字母
}
if(!preg_match("/^[A-Za-z0-9]+$/",$pwd))
{
return "密码只能包含字母和数字";//有数字有字母 ";
}
return null;
}
/*ajax返回*/
function ajax_return($data)
{
header("Content-Type:text/html; charset=utf-8");
echo(json_encode($data));
// echo(base64_encode(json_encode($data)));
if (APP_LOG) {
$GLOBALS["log"]->quit($data);
}
exit;
}
/**
* 字符串加密函数
* @param string $txt
* @param string $key
* @return string
*/
function passport_encrypt($txt, $key = "IMEMBER_2013") {
srand((double)microtime() * 1000000);
$encrypt_key = md5(rand(0, 32000));
$ctr = 0;
$tmp = "";
for($i = 0;$i < strlen($txt); $i++) {
$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
$tmp .= $encrypt_key[$ctr].($txt[$i] ^ $encrypt_key[$ctr++]);
}
return base64_encode(passport_key($tmp, $key));
}
/**
* 字符串解密函数
* @param string $txt
* @param string $key
* @return string
*/
function passport_decrypt($txt, $key = "IMEMBER_2013") {
$txt = passport_key(base64_decode($txt), $key);
$tmp = "";
for($i = 0;$i < strlen($txt); $i++) {
if (empty($txt[$i+1])) {
return false;
}
$md5 = $txt[$i];
$tmp .= $txt[++$i] ^ $md5;
}
return $tmp;
}
function passport_key($txt, $encrypt_key) {
$encrypt_key = md5($encrypt_key);
$ctr = 0;
$tmp = "";
for($i = 0; $i < strlen($txt); $i++) {
$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
$tmp .= $txt[$i] ^ $encrypt_key[$ctr++];
}
return $tmp;
}
/**
* 传入图片的地址,自动修复图片的相对路径(如 ./public/logo.png)到绝对路径(如http://www.imember.cc/public/logo.png)
* @param unknown $img_path
*/
function imagePathRevise($img_path){
//判断$img_path的路径是否以http://开头
if (preg_match("/^http:///", $img_path)) {
return $img_path;
}else{
return IMG_PATH.preg_replace("/^.//", "", $img_path);
}
}
//utf8 字符串截取
function msubstr($str, $start=0, $length=15, $charset="utf-8", $suffix=true)
{
if(function_exists("mb_substr"))
{
$slice = mb_substr($str, $start, $length, $charset);
if($suffix&$slice!=$str) return $slice."…";
return $slice;
}
elseif(function_exists("iconv_substr")) {
return iconv_substr($str,$start,$length,$charset);
}
$re["utf-8"] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
$re["gb2312"] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
$re["gbk"] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
$re["big5"] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
preg_match_all($re[$charset], $str, $match);
$slice = join("",array_slice($match[0], $start, $length));
if($suffix&&$slice!=$str) return $slice."…";
return $slice;
}
}
?>
6.加载./initializer.php,initializer()用于将所有公用的文件目录在此函数里声明
initializer::initialize();这就话就是调用initializer类的一个静态函数initialize,因为我们在ini.php,设置了include_path,以及定义了__autoload,所以程序会自动在core/main目录查找initializer.php.
定义了一个静态函数,initialize函数,这个函数就是设置include_path,这样,以后如果包含文件,或者__autoload,就会去这些目录下查找。
<?php
class initializer
{
public static function initialize() {
set_include_path(get_include_path().PATH_SEPARATOR . "core/main");
set_include_path(get_include_path().PATH_SEPARATOR . "core/main/cache");
set_include_path(get_include_path().PATH_SEPARATOR . "core/helpers");
set_include_path(get_include_path().PATH_SEPARATOR . "core/libraries");
set_include_path(get_include_path().PATH_SEPARATOR . "core/config");
set_include_path(get_include_path().PATH_SEPARATOR . "app/controllers");
set_include_path(get_include_path().PATH_SEPARATOR."app/models");
set_include_path(get_include_path().PATH_SEPARATOR."app/views");
}
}
?>
7.加载./loader.php文件,源码:
<?php
class loader
{
private static $loaded = array();
public static function load($object){
$valid = array(
"library",
"view",
"model",
"helper",
"router",
"config",
"hook",
"cache",
"db");
if (!in_array($object,$valid)){
// throw new Exception("Not a valid object "{$object}" to load");
ajax_return(array("recode"=>"0003","msg"=>"非法操作","data"=>"Not a valid object "{$object}" to load"));
}
if (empty(self::$loaded[$object])){
self::$loaded[$object]= new $object();
}
return self::$loaded[$object];
}
}
?>
8.加载控制层文件./router.php,源码:
<?php
class router
{
private $route;
private $controller;
private $action;
private $params;
public function __construct()
{
//base64_decode(str)解码
$routeParts=$_GET;
// $routeParts=base64_decode($_GET);
if (!isset($routeParts["c"])){
ajax_return(array("recode"=>"0003","msg"=>"非法操作","data"=>"Controller is null"));
}
$this->route = $routeParts["c"];
$this->controller=$routeParts["c"];
$this->action=isset($routeParts["act"])? $routeParts["act"]:"index";
array_shift($routeParts);
array_shift($routeParts);
$this->params=$routeParts;
}
public function getAction() {
if (empty($this->action)) $this->action="index";
return $this->action;
}
public function getController() {
return $this->controller;
}
public function getParams() {
return $this->params;
}
}
?>
9.加载数据库连接文件./core/conn.php,源码:
<?php
/*
* 数据库连接
*/
//第一种方法:直接写入数据库连接参数
// $dblink=mysql_connect("127.0.0.1:3306","sara","abc123");
// mysql_select_db("ipolarbear",$dblink);
// mysql_query("SET NAMES UTF8");
// if (!$dblink) {
// mysql_query("SET NAMES UTF8");
// die (json_encode(array("recode"=>"0009","msg"=>"连接数据库失败" . mysql_error (),"data"=>"")));
// }
//第二种方法:定义DB类,加载数据库配置,对数据库SQL进行封装
//加载数据库配置
$dbcfg = require APP_ROOT_PATH."core/config/db_config.php";
if(!defined("DB_PREFIX"))//im:数据库表前缀
define("DB_PREFIX", $dbcfg["DB_PREFIX"]);
if(!file_exists(APP_ROOT_PATH."core/runtime/db_caches/"))
mkdir(APP_ROOT_PATH."core/runtime/db_caches/",0777);
$pconnect = false;
$GLOBALS["db"] = new mysql_db($dbcfg["DB_HOST"].":".$dbcfg["DB_PORT"], $dbcfg["DB_USER"],$dbcfg["DB_PWD"],$dbcfg["DB_NAME"],"utf8",$pconnect);
mysql_query("SET NAMES UTF8");//相当于character_set_client(),character_set_connection(),character_set_results()客户端 连接器 返回值三者同时设置编码方式
//检查PHP是否连接上MYSQL
if(mysqli_connect_errno()){
die (json_encode(array("recode"=>"0009","msg"=>"连接数据库失败:" . mysql_error (),"data"=>"")));
}
//end 定义DB
?>
10.加载数据库配置文件./core/db_config.php,源码:
<?php return array( "DB_HOST"=>"localhost", "DB_NAME"=>"ip", "DB_USER"=>"sara", "DB_PWD"=>"abc123", "DB_PORT"=>"3306", "DB_PREFIX"=>"base_", ); ?>
11.加载数据库类文件./core/mysql_db.php,源码:
<?php
class mysql_db
{
var $link_id = NULL;
var $settings = array();
var $queryCount = 0;
var $queryTime = "";
var $queryLog = array();
var $max_cache_time = 60; // 最大的缓存时间,以秒为单位
var $cache_data_dir = "core/runtime/db_caches/";
var $root_path = "";
var $error_message = array();
var $platform = "";
var $version = "";
var $dbhash = "";
var $starttime = 0;
var $timeline = 0;
var $timezone = 0;
var $mysql_config_cache_file_time = 0;
var $mysql_disable_cache_tables = array(); // 不允许被缓存的表,遇到将不会进行缓存
function __construct($dbhost, $dbuser, $dbpw, $dbname = "", $charset = "utf8", $pconnect = 0, $quiet = 0)
{
$this->mysql_db($dbhost, $dbuser, $dbpw, $dbname, $charset, $pconnect, $quiet);
}
function mysql_db($dbhost, $dbuser, $dbpw, $dbname = "", $charset = "utf8", $pconnect = 0, $quiet = 0)
{
if (defined("APP_ROOT_PATH") && !$this->root_path)
{
$this->root_path = APP_ROOT_PATH;
}
if ($quiet)
{
$this->connect($dbhost, $dbuser, $dbpw, $dbname, $charset, $pconnect, $quiet);
}
else
{
$this->settings = array(
"dbhost" => $dbhost,
"dbuser" => $dbuser,
"dbpw" => $dbpw,
"dbname" => $dbname,
"charset" => $charset,
"pconnect" => $pconnect
);
}
}
function connect($dbhost, $dbuser, $dbpw, $dbname = "", $charset = "utf8", $pconnect = 0, $quiet = 0)
{
if ($pconnect)
{
if (!($this->link_id = @mysql_pconnect($dbhost, $dbuser, $dbpw)))
{
if (!$quiet)
{
$this->ErrorMsg("Can"t pConnect MySQL Server($dbhost)!");
}
return false;
}
}
else
{
if (PHP_VERSION >= "4.2")
{
$this->link_id = @mysql_connect($dbhost, $dbuser, $dbpw, true);
}
else
{
$this->link_id = @mysql_connect($dbhost, $dbuser, $dbpw);
mt_srand((double)microtime() * 1000000); // 对 PHP 4.2 以下的版本进行随机数函数的初始化工作
}
if (!$this->link_id)
{
if (!$quiet)
{
$this->ErrorMsg("Can"t Connect MySQL Server($dbhost)!");
}
return false;
}
}
$this->dbhash = md5($this->root_path . $dbhost . $dbuser . $dbpw . $dbname);
$this->version = mysql_get_server_info($this->link_id);
/* 如果mysql 版本是 4.1+ 以上,需要对字符集进行初始化 */
if ($this->version > "4.1")
{
if ($charset != "latin1")
{
mysql_query("SET character_set_connection=$charset, character_set_results=$charset, character_set_client=binary", $this->link_id);
}
if ($this->version > "5.0.1")
{
mysql_query("SET sql_mode=""", $this->link_id);
}
}
$sqlcache_config_file = $this->root_path . $this->cache_data_dir . "sqlcache_config_file_" . $this->dbhash . ".php";
@include($sqlcache_config_file);
$this->starttime = time();
if ($this->max_cache_time && $this->starttime > $this->mysql_config_cache_file_time + $this->max_cache_time)
{
if ($dbhost != ".")
{
$result = mysql_query("SHOW VARIABLES LIKE "basedir"", $this->link_id);
$row = mysql_fetch_assoc($result);
if (!empty($row["Value"]{
1}) && $row["Value"]{
1} == ":" && !empty($row["Value"]{
2}) && $row["Value"]{
2} == "\")
{
$this->platform = "WINDOWS";
}
else
{
$this->platform = "OTHER";
}
}
else
{
$this->platform = "WINDOWS";
}
if ($this->platform == "OTHER" &&
($dbhost != "." && strtolower($dbhost) != "localhost:3306" && $dbhost != "127.0.0.1:3306") ||
(PHP_VERSION >= "5.1" && date_default_timezone_get() == "UTC"))
{
$result = mysql_query("SELECT UNIX_TIMESTAMP() AS timeline, UNIX_TIMESTAMP("" . date("Y-m-d H:i:s", $this->starttime) . "") AS timezone", $this->link_id);
$row = mysql_fetch_assoc($result);
if ($dbhost != "." && strtolower($dbhost) != "localhost:3306" && $dbhost != "127.0.0.1:3306")
{
$this->timeline = $this->starttime - $row["timeline"];
}
if (PHP_VERSION >= "5.1" && date_default_timezone_get() == "UTC")
{
$this->timezone = $this->starttime - $row["timezone"];
}
}
$content = "<" . "?php
" .
"$this->mysql_config_cache_file_time = " . $this->starttime . ";
" .
"$this->timeline = " . $this->timeline . ";
" .
"$this->timezone = " . $this->timezone . ";
" .
"$this->platform = " . """ . $this->platform . "";
?" . ">";
@file_put_contents($sqlcache_config_file, $content);
}
/* 选择数据库 */
if ($dbname)
{
if (mysql_select_db($dbname, $this->link_id) === false )
{
if (!$quiet)
{
$this->ErrorMsg("Can"t select MySQL database($dbname)!");
}
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
function select_database($dbname)
{
return mysql_select_db($dbname, $this->link_id);
}
function set_mysql_charset($charset)
{
/* 如果mysql 版本是 4.1+ 以上,需要对字符集进行初始化 */
if ($this->version > "4.1")
{
if (in_array(strtolower($charset), array("gbk", "big5", "utf-8", "utf8")))
{
$charset = str_replace("-", "", $charset);
}
if ($charset != "latin1")
{
mysql_query("SET character_set_connection=$charset, character_set_results=$charset, character_set_client=binary", $this->link_id);
}
}
}
function fetch_array($query, $result_type = MYSQL_ASSOC)
{
return mysql_fetch_array($query, $result_type);
}
function query($sql, $type = "")
{
if ($this->link_id === NULL)
{
$this->connect($this->settings["dbhost"], $this->settings["dbuser"], $this->settings["dbpw"], $this->settings["dbname"], $this->settings["charset"], $this->settings["pconnect"]);
$this->settings = array();
}
if ($this->queryCount++ <= 99)
{
$this->queryLog[] = $sql;
}
if ($this->queryTime == "")
{
if (PHP_VERSION >= "5.0.0")
{
$this->queryTime = microtime(true);
}
else
{
$this->queryTime = microtime();
}
}
/* 当当前的时间大于类初始化时间的时候,自动执行 ping 这个自动重新连接操作 */
if (PHP_VERSION >= "4.3" && time() > $this->starttime + 1)
{
mysql_ping($this->link_id);
}
if (!($query = mysql_query($sql, $this->link_id)) && $type != "SILENT")
{
$this->error_message[]["message"] = "MySQL Query Error";
$this->error_message[]["sql"] = $sql;
$this->error_message[]["error"] = mysql_error($this->link_id);
$this->error_message[]["errno"] = mysql_errno($this->link_id);
$this->ErrorMsg();
return false;
}
if (defined("DEBUG_MODE") && (DEBUG_MODE & 8) == 8)
{
$logfilename = $this->root_path . DATA_DIR . "/mysql_query_" . $this->dbhash . "_" . date("Y_m_d") . ".log";
$str = $sql . "
";
if (PHP_VERSION >= "5.0")
{
file_put_contents($logfilename, $str, FILE_APPEND);
}
else
{
$fp = @fopen($logfilename, "ab+");
if ($fp)
{
fwrite($fp, $str);
fclose($fp);
}
}
}
//echo $sql."<br/><br/>======================================<br/><br/>";
return $query;
}
function affected_rows()
{
return mysql_affected_rows($this->link_id);
}
function error()
{
return mysql_error($this->link_id);
}
function errno()
{
return mysql_errno($this->link_id);
}
function result($query, $row)
{
return @mysql_result($query, $row);
}
function num_rows($query)
{
return mysql_num_rows($query);
}
function num_fields($query)
{
return mysql_num_fields($query);
}
function free_result($query)
{
return mysql_free_result($query);
}
function insert_id()
{
return mysql_insert_id($this->link_id);
}
function fetchRow($query)
{
return mysql_fetch_assoc($query);
}
function fetch_fields($query)
{
return mysql_fetch_field($query);
}
function version()
{
return $this->version;
}
function ping()
{
if (PHP_VERSION >= "4.3")
{
return mysql_ping($this->link_id);
}
else
{
return false;
}
}
function escape_string($unescaped_string)
{
if (PHP_VERSION >= "4.3")
{
return mysql_real_escape_string($unescaped_string);
}
else
{
return mysql_escape_string($unescaped_string);
}
}
function close()
{
return mysql_close($this->link_id);
}
function ErrorMsg($message = "", $sql = "")
{
if ($message)
{
ajax_return(array("recode"=>"0009","msg"=>"MySQL server error info:".$message,"data"=>""));
}
else
{
ajax_return(array("recode"=>"0010","msg"=>"MySQL server error report:".$this->error_message,"data"=>""));
}
}
/* 仿真 Adodb 函数 */
function selectLimit($sql, $num, $start = 0)
{
if ($start == 0)
{
$sql .= " LIMIT " . $num;
}
else
{
$sql .= " LIMIT " . $start . ", " . $num;
}
return $this->query($sql);
}
function getOne($sql, $limited = false)
{
if ($limited == true)
{
$sql = trim($sql . " LIMIT 1");
}
$res = $this->query($sql);
if ($res !== false)
{
$row = mysql_fetch_row($res);
if ($row !== false)
{
return $row[0];
}
else
{
return "";
}
}
else
{
return false;
}
}
function getOneCached($sql, $cached = "FILEFIRST")
{
$cachefirst = ($cached == "FILEFIRST" || ($cached == "MYSQLFIRST" && $this->platform != "WINDOWS")) && $this->max_cache_time;
if (!$cachefirst)
{
return $this->getOne($sql, true);
}
else
{
$result = $this->getSqlCacheData($sql, $cached);
if (empty($result["storecache"]) == true)
{
return $result["data"];
}
}
$arr = $this->getOne($sql, true);
if ($arr !== false && $cachefirst)
{
$this->setSqlCacheData($result, $arr);
}
return $arr;
}
function getAll($sql)
{
$res = $this->query($sql);
if ($res !== false)
{
$arr = array();
while ($row = mysql_fetch_assoc($res))
{
$arr[] = $row;
}
return $arr;
}
else
{
return false;
}
}
function getAllCached($sql, $cached = "FILEFIRST")
{
$cachefirst = ($cached == "FILEFIRST" || ($cached == "MYSQLFIRST" && $this->platform != "WINDOWS")) && $this->max_cache_time;
if (!$cachefirst)
{
return $this->getAll($sql);
}
else
{
$result = $this->getSqlCacheData($sql, $cached);
if (empty($result["storecache"]) == true)
{
return $result["data"];
}
}
$arr = $this->getAll($sql);
if ($arr !== false && $cachefirst)
{
$this->setSqlCacheData($result, $arr);
}
return $arr;
}
function getRow($sql, $limited = false)
{
if ($limited == true)
{
$sql = trim($sql . " LIMIT 1");
}
$res = $this->query($sql);
if ($res !== false)
{
return mysql_fetch_assoc($res);
}
else
{
return false;
}
}
function getRowCached($sql, $cached = "FILEFIRST")
{
$cachefirst = ($cached == "FILEFIRST" || ($cached == "MYSQLFIRST" && $this->platform != "WINDOWS")) && $this->max_cache_time;
if (!$cachefirst)
{
return $this->getRow($sql, true);
}
else
{
$result = $this->getSqlCacheData($sql, $cached);
if (empty($result["storecache"]) == true)
{
return $result["data"];
}
}
$arr = $this->getRow($sql, true);
if ($arr !== false && $cachefirst)
{
$this->setSqlCacheData($result, $arr);
}
return $arr;
}
function getCol($sql)
{
$res = $this->query($sql);
if ($res !== false)
{
$arr = array();
while ($row = mysql_fetch_row($res))
{
$arr[] = $row[0];
}
return $arr;
}
else
{
return false;
}
}
function getColCached($sql, $cached = "FILEFIRST")
{
$cachefirst = ($cached == "FILEFIRST" || ($cached == "MYSQLFIRST" && $this->platform != "WINDOWS")) && $this->max_cache_time;
if (!$cachefirst)
{
return $this->getCol($sql);
}
else
{
$result = $this->getSqlCacheData($sql, $cached);
if (empty($result["storecache"]) == true)
{
return $result["data"];
}
}
$arr = $this->getCol($sql);
if ($arr !== false && $cachefirst)
{
$this->setSqlCacheData($result, $arr);
}
return $arr;
}
function autoExecute($table, $field_values, $mode = "INSERT", $where = "", $querymode = "")
{
$field_names = $this->getCol("DESC " . $table);
$sql = "";
if ($mode == "INSERT")
{
$fields = $values = array();
foreach ($field_names AS $value)
{
if (@array_key_exists($value, $field_values) == true)
{
$fields[] = $value;
$field_values[$value] = stripslashes($field_values[$value]);
$values[] = """ . addslashes($field_values[$value]) . """;
}
}
if (!empty($fields))
{
$sql = "INSERT INTO " . $table . " (" . implode(", ", $fields) . ") VALUES (" . implode(", ", $values) . ")";
}
}
else
{
$sets = array();
foreach ($field_names AS $value)
{
if (array_key_exists($value, $field_values) == true)
{
$field_values[$value] = stripslashes($field_values[$value]);
$sets[] = $value . " = "" . addslashes($field_values[$value]) . """;
}
}
if (!empty($sets))
{
$sql = "UPDATE " . $table . " SET " . implode(", ", $sets) . " WHERE " . $where;
}
}
if ($sql)
{
return $this->query($sql, $querymode);
}
else
{
return false;
}
}
function autoReplace($table, $field_values, $update_values, $where = "", $querymode = "")
{
$field_descs = $this->getAll("DESC " . $table);
$primary_keys = array();
foreach ($field_descs AS $value)
{
$field_names[] = $value["Field"];
if ($value["Key"] == "PRI")
{
$primary_keys[] = $value["Field"];
}
}
$fields = $values = array();
foreach ($field_names AS $value)
{
if (array_key_exists($value, $field_values) == true)
{
$fields[] = $value;
$values[] = """ . $field_values[$value] . """;
}
}
$sets = array();
foreach ($update_values AS $key => $value)
{
if (array_key_exists($key, $field_values) == true)
{
if (is_int($value) || is_float($value))
{
$sets[] = $key . " = " . $key . " + " . $value;
}
else
{
$sets[] = $key . " = "" . $value . """;
}
}
}
$sql = "";
if (empty($primary_keys))
{
if (!empty($fields))
{
$sql = "INSERT INTO " . $table . " (" . implode(", ", $fields) . ") VALUES (" . implode(", ", $values) . ")";
}
}
else
{
if ($this->version() >= "4.1")
{
if (!empty($fields))
{
$sql = "INSERT INTO " . $table . " (" . implode(", ", $fields) . ") VALUES (" . implode(", ", $values) . ")";
if (!empty($sets))
{
$sql .= "ON DUPLICATE KEY UPDATE " . implode(", ", $sets);
}
}
}
else
{
if (empty($where))
{
$where = array();
foreach ($primary_keys AS $value)
{
if (is_numeric($value))
{
$where[] = $value . " = " . $field_values[$value];
}
else
{
$where[] = $value . " = "" . $field_values[$value] . """;
}
}
$where = implode(" AND ", $where);
}
if ($where && (!empty($sets) || !empty($fields)))
{
if (intval($this->getOne("SELECT COUNT(*) FROM $table WHERE $where")) > 0)
{
if (!empty($sets))
{
$sql = "UPDATE " . $table . " SET " . implode(", ", $sets) . " WHERE " . $where;
}
}
else
{
if (!empty($fields))
{
$sql = "REPLACE INTO " . $table . " (" . implode(", ", $fields) . ") VALUES (" . implode(", ", $values) . ")";
}
}
}
}
}
if ($sql)
{
return $this->query($sql, $querymode);
}
else
{
return false;
}
}
function setMaxCacheTime($second)
{
$this->max_cache_time = $second;
}
function getMaxCacheTime()
{
return $this->max_cache_time;
}
function getSqlCacheData($sql, $cached = "")
{
$sql = trim($sql);
$result = array();
$result["filename"] = $this->root_path . $this->cache_data_dir . "sqlcache_" . abs(crc32($this->dbhash . $sql)) . "_" . md5($this->dbhash . $sql) . ".php";
$result["data"] = $GLOBALS["cache"]->get($result["filename"]);
if($result["data"]===false)
{
$result["storecache"] = true;
}
else
{
$result["storecache"] = false;
}
return $result;
}
function setSqlCacheData($result, $data)
{
if ($result["storecache"] === true && $result["filename"])
{
$GLOBALS["cache"]->set($result["filename"],$data,$this->max_cache_time);
}
}
/* 获取 SQL 语句中最后更新的表的时间,有多个表的情况下,返回最新的表的时间 */
function table_lastupdate($tables)
{
if ($this->link_id === NULL)
{
$this->connect($this->settings["dbhost"], $this->settings["dbuser"], $this->settings["dbpw"], $this->settings["dbname"], $this->settings["charset"], $this->settings["pconnect"]);
$this->settings = array();
}
$lastupdatetime = "0000-00-00 00:00:00";
$tables = str_replace("`", "", $tables);
$this->mysql_disable_cache_tables = str_replace("`", "", $this->mysql_disable_cache_tables);
foreach ($tables AS $table)
{
if (in_array($table, $this->mysql_disable_cache_tables) == true)
{
$lastupdatetime = "2037-12-31 23:59:59";
break;
}
if (strstr($table, ".") != NULL)
{
$tmp = explode(".", $table);
$sql = "SHOW TABLE STATUS FROM `" . trim($tmp[0]) . "` LIKE "" . trim($tmp[1]) . """;
}
else
{
$sql = "SHOW TABLE STATUS LIKE "" . trim($table) . """;
}
$result = mysql_query($sql, $this->link_id);
$row = mysql_fetch_assoc($result);
if ($row["Update_time"] > $lastupdatetime)
{
$lastupdatetime = $row["Update_time"];
}
}
$lastupdatetime = strtotime($lastupdatetime) - $this->timezone + $this->timeline;
return $lastupdatetime;
}
function get_table_name($query_item)
{
$query_item = trim($query_item);
$table_names = array();
/* 判断语句中是不是含有 JOIN */
if (stristr($query_item, " JOIN ") == "")
{
/* 解析一般的 SELECT FROM 语句 */
if (preg_match("/^SELECT.*?FROMs*((?:`?w+`?s*.s*)?`?w+`?(?:(?:s*AS)?s*`?w+`?)?(?:s*,s*(?:`?w+`?s*.s*)?`?w+`?(?:(?:s*AS)?s*`?w+`?)?)*)/is", $query_item, $table_names))
{
$table_names = preg_replace("/((?:`?w+`?s*.s*)?`?w+`?)[^,]*/", "1", $table_names[1]);
return preg_split("/s*,s*/", $table_names);
}
}
else
{
/* 对含有 JOIN 的语句进行解析 */
if (preg_match("/^SELECT.*?FROMs*((?:`?w+`?s*.s*)?`?w+`?)(?:(?:s*AS)?s*`?w+`?)?.*?JOIN.*$/is", $query_item, $table_names))
{
$other_table_names = array();
preg_match_all("/JOINs*((?:`?w+`?s*.s*)?`?w+`?)s*/i", $query_item, $other_table_names);
return array_merge(array($table_names[1]), $other_table_names[1]);
}
}
return $table_names;
}
/* 设置不允许进行缓存的表 */
function set_disable_cache_tables($tables)
{
if (!is_array($tables))
{
$tables = explode(",", $tables);
}
foreach ($tables AS $table)
{
$this->mysql_disable_cache_tables[] = $table;
}
array_unique($this->mysql_disable_cache_tables);
}
}
?>
controller控制层文件./app/controllers/user.php用户类
<?php
/**
* @file: user.php 用户控制层
* @version: 1.0
* @author: Sara
* @create: 2012-12-17 10:15:00
* @update: 2012-12-17 10:15:00
* @access: http://blog.csdn.net/haiqiao_2010
* @copyright: 2012 http://blog.csdn.net/haiqiao_2010 All rights reserved.
**/
header("Content-Type: text/html; charset=utf-8");
@require_once "./core/config/conn.php";
class user
{
/*
* method __construct
* paramemter string $a
* return 提示信息/调用方法
*/
function __construct()
{
$action=@trim(@$_REQUEST["act"]);
if(empty($action)){
$action="index";
}else{
if(!in_array($action,array("index","login","register","userUpdatePwd"))){
ajax_return(array("recode"=>"0003","msg"=>"非法操作","data"=>$action));
}
}
}
/*
* method index 非法调用
* param
* return
*/
public function index()
{
ajax_return(array("recode"=>"0003","msg"=>"非法操作","data"=>@$_REQUEST["act"]));
}
/*
* method login 用户登陆(支持邮箱+密码或者账号+密码)
* param string $user_name,string $user_pwd,string $l_ip,string $city_name,float $l_xpoint,float $l_ypoint
* return 返回成功/失败已经登陆信息
*/
public function login()
{
$data=json_decode(@$_REQUEST["req"]);
$user_name_or_email = trim(new_htmlspecialchars(new_addslashes(@$data->user_name)));
$user_pwd = trim(new_htmlspecialchars(new_addslashes(@$data->user_pwd)));
$log["l_ip"] = trim(new_htmlspecialchars(new_addslashes(@$data->l_ip)));
$log["city_name"] = trim(new_htmlspecialchars(new_addslashes(@$data->city_name)));
$log["l_xpoint"] = trim(new_htmlspecialchars(new_addslashes(@$data->l_xpoint)));
$log["l_ypoint"] = trim(new_htmlspecialchars(new_addslashes(@$data->l_ypoint)));
$log["l_type"] = intval(@$data->l_type);//用户登陆类型:默认为0,网站登陆,1为手机端IOS登陆,2为手机端android
$log["l_version"] = trim(new_htmlspecialchars(new_addslashes(@$data->l_version)));
if(empty($user_name_or_email)|| empty($user_pwd))
{
$r=array("recode"=>"0002","msg"=>"参数错误","data"=>"");
}
else
{
$user_data = $GLOBALS["db"]->getRow("select * from ".DB_PREFIX."user where (user_name="".$user_name_or_email."" or email = "".$user_name_or_email."") and is_delete = 0");
if(!$user_data)
{
$r=array("recode"=>"1014","msg"=>"该用户不存在,请确认操作.","data"=>"");
}
else
{
if($user_data["user_pwd"] != md5($user_pwd.$user_data["code"])&&$user_data["user_pwd"]!=$user_pwd)
{
$r=array("recode"=>"0012","msg"=>"用户密码不对,请确认您的登陆信息.","data"=>"");
}
elseif($user_data["is_effect"] != 1)
{
$r=array("recode"=>"0011","msg"=>"账号未被激活,暂时不能进行如下操作.","data"=>"");
}
elseif($user_data["is_locking"] != 0)
{
$r=array("recode"=>"0014","msg"=>"账号已经被锁定,暂时不能进行如下操作.","data"=>"");
if(app_conf("SHOP_TEL")!="")
$r["msg"].="若有疑问,请致电联系客服: <".app_conf("SHOP_TEL").">";
}
else
{
//im:查看会员分组是否能够升级
$user_current_group = $GLOBALS["db"]->getRow("select * from ".DB_PREFIX."user_group where id = ".intval($user_data["group_id"]));
$user_group = $GLOBALS["db"]->getRow("select * from ".DB_PREFIX."user_group where score <=".intval($user_data["score"])." order by score desc");
if($user_current_group["score"]<$user_group["score"])
{
$user_data["group_id"] = intval($user_group["id"]);
$GLOBALS["db"]->query("update ".DB_PREFIX."user set group_id = ".$user_data["group_id"]." where id = ".$user_data["id"]);
$pm_title = "您已经成为".$user_group["name"]."";
$pm_content = "恭喜您,您已经成为".$user_group["name"]."。";
if($user_group["discount"]<1)
{
$pm_content.="您将享有".($user_group["discount"]*10)."折的购物优惠";
}
send_user_msg($pm_title,$pm_content,0,$user_data["id"],get_gmtime(),0,true,true);
}
//im:查看会员积分是否能够升级
$user_current_level = $GLOBALS["db"]->getRow("select * from ".DB_PREFIX."user_level where id = ".intval($user_data["level_id"]));
$user_level = $GLOBALS["db"]->getRow("select * from ".DB_PREFIX."user_level where point <=".intval($user_data["point"])." order by point desc");
if($user_current_level["point"]<$user_level["point"])
{
$user_data["level_id"] = intval($user_level["id"]);
$GLOBALS["db"]->query("update ".DB_PREFIX."user set level_id = ".$user_data["level_id"]." where id = ".$user_data["id"]);
$pm_title = "您已经成为".$user_level["name"]."";
$pm_content = "恭喜您,您已经成为".$user_level["name"]."。";
send_user_msg($pm_title,$pm_content,0,$user_data["id"],get_gmtime(),0,true,true);
}
if($user_current_level["point"]>$user_level["point"])
{
$user_data["level_id"] = intval($user_level["id"]);
$GLOBALS["db"]->query("update ".DB_PREFIX."user set level_id = ".$user_data["level_id"]." where id = ".$user_data["id"]);
$pm_title = "您已经降为".$user_level["name"]."";
$pm_content = "很报歉,您已经降为".$user_level["name"]."。";
send_user_msg($pm_title,$pm_content,0,$user_data["id"],get_gmtime(),0,true,true);
}
$log["l_time"]=get_gmtime();
$log["user_id"]=$user_data["id"];
//im:更新最后登陆信息
$GLOBALS["db"]->query("update ".DB_PREFIX."user set login_ip = "".$log["l_ip"]."",login_time= ".$log["l_time"].",group_id=".intval($user_data["group_id"])." where id =".$user_data["id"]);
//添加登陆日志
$GLOBALS["db"]->autoExecute("im_user_login_log",$log);
//检查是否为最新系统版本
$log["l_type"] = intval(@$data->l_type);//用户登陆类型:默认为0,网站登陆,1为手机端IOS登陆,2为手机端android
switch ($log["l_type"])//im_m_package:p_type:手机系统版本类型,默认为0 ios系统;为1 android系统
{
case "1":
$package=$GLOBALS["db"]->getRow("select p_version,p_url,is_must from im_m_package where is_effect=1 and p_type=0");
break;
case "2":
$package=$GLOBALS["db"]->getRow("select p_version,p_url,is_must from im_m_package where is_effect=1 and p_type=1");
break;
default:
break;
}
if (@$package && strnatcmp($log["l_version"],$package["p_version"])<0)
{
// $varreg="/^http://[A-Za-z0-9]+.[A-Za-z0-9]+[/=?%-&_~`@[]":+!]*([^<>""])*$/";
$varreg="/^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/?/i";
if(!preg_match($varreg,$package["p_url"]))//im:判断是否为超链接
{
$package["p_url"]=URL_PATH.str_replace("./","",$package["p_url"]);
}
$r=array("recode"=>"0015","msg"=>"用户登陆成功.","data"=>array("user_id"=>$user_data["id"],"user_name"=>$user_data["user_name"],"true_name"=>$user_data["true_name"],"email"=>is_null($user_data["email"])?"":$user_data["email"],"mobile"=>is_null($user_data["mobile"])?"":$user_data["mobile"],"l_time"=>to_date($log["l_time"]),"p_version"=>$package["p_version"],"p_url"=>$package["p_url"],"is_must"=>$package["is_must"]));
}
else
{
$r=array("recode"=>"0015","msg"=>"用户登陆成功.","data"=>array("user_id"=>$user_data["id"],"user_name"=>$user_data["user_name"],"true_name"=>$user_data["true_name"],"email"=>is_null($user_data["email"])?"":$user_data["email"],"mobile"=>is_null($user_data["mobile"])?"":$user_data["mobile"],"l_time"=>to_date($log["l_time"]),"p_version"=>$log["l_version"],"p_url"=>"","is_must"=>""));
}
}
}
}
ajax_return($r);
}
/*
* method register 用户注册
* param int $type,string $user_name,string $user_pwd,string $email ,string mobile
* return 返回成功/失败
*/
public function register()
{
//{"type":0,"user_name":"sara123","user_pwd":"123456","email":"sara123@qq.com","mobile":"13245678900","xpoint":"119.306938","ypoint":"26.069746","city_name":"u5b81u590f","ip":"192.168.1","l_type":"1","l_version":"1.0","verify_code":"123456","msg_id":"12"}
// $data=json_encode(array(
// "type"=>0,
// "user_name"=>"sara123",
// "user_pwd"=>"123456",
// "email"=>"sara123@qq.com",
// "mobile"=>"13245678900",
// "xpoint"=>"119.306938",
// "ypoint"=>"26.069746",
// "city_name"=>"宁夏",
// "ip"=>"192.168.1",
// "l_type"=>"1",
// "l_version"=>"1.0",
// "verify_code"=>"123456",
// "msg_id"=>12
// ));
$data=json_decode(@$_REQUEST["req"]);
$type = intval(@$data->type);//im:注册方式:默认为0:邮箱+账号;1为:手机号+账号
$user_data["user_name"] = strtolower(trim(new_htmlspecialchars(new_addslashes(@$data->user_name))));
$user_data["user_pwd"] = trim(new_htmlspecialchars(new_addslashes(@$data->user_pwd)));
$user_data["email"] = trim(new_htmlspecialchars(new_addslashes(@$data->email)));
$user_data["mobile"] = trim(new_htmlspecialchars(new_addslashes(@$data->mobile)));
$user_data["xpoint"] = doubleval(@$data->xpoint);
$user_data["ypoint"] = doubleval(@$data->ypoint);
$city_name = trim(new_htmlspecialchars(new_addslashes(@$data->city_name)));
$user_data["login_ip"] = trim(new_htmlspecialchars(new_addslashes(@$data->ip)));
$l_type = intval(@$data->l_type);//用户登陆类型:默认为0,网站登陆,1为手机端IOS登陆,2为手机端android
$l_version = trim(new_htmlspecialchars(new_addslashes(@$data->l_version)));
if($user_data["user_name"]==""|| !preg_match("/^[a-zd]{3,20}$/i", $user_data["user_name"]))
{
ajax_return(array("recode"=>"1001","msg"=>"用户名不能为空,且为3-20个由字母和数字组成的字符串.".$data->user_name,"data"=>""));
}
else
{
if($GLOBALS["db"]->getOne("select count(*) from ".DB_PREFIX."user where user_name = "".trim($user_data["user_name"]).""")>0)
{
ajax_return(array("recode"=>"1006","msg"=>"该用户名已经存在,请重新填写","data"=>""));
}
else
{
$msg=get_pwd_strength($user_data["user_pwd"]);
if(!empty($msg))
{
ajax_return(array("recode"=>"1003","msg"=>$msg,"data"=>""));
}
else
{
if($type==0)
{
if(!check_email($user_data["email"]))
{
ajax_return(array("recode"=>"1003","msg"=>"邮箱格式不正确.","data"=>""));
}
else
{
if($GLOBALS["db"]->getOne("select count(*) from ".DB_PREFIX."user where email = "".trim($user_data["email"]).""")>0)
{
ajax_return(array("recode"=>"1004","msg"=>"该邮箱已经被注册过,请填写其他邮箱.","data"=>""));
}
}
}
else
{
if(!check_mobile($user_data["mobile"]))
{
ajax_return(array("recode"=>"1005","msg"=>"手机号码格式错误,手机号码为11位.","data"=>""));
}
else
{
$verify_code = trim(new_htmlspecialchars(new_addslashes(@$data->verify_code)));
$msg_id = intval(@$data->msg_id);
if ($msg_id<=0 || empty($verify_code))
{
ajax_return(array("recode"=>"0002","msg"=>"参数错误","data"=>""));
}
$verify_result=use_sms_code(0,0,$msg_id,0,$user_data["mobile"],$verify_code);
if($verify_result["status"]==0)
{
ajax_return(array("recode"=>$verify_result["recode"],"msg"=>$verify_result["msg"],"data"=>""));
}
}
}
//验证结束开始插入数据
$user_data["create_time"] = get_gmtime();
$user_data["update_time"] = get_gmtime();
//获取默认会员组, 即升级积分最小的会员组
$user_data["group_id"] = $GLOBALS["db"]->getOne("select id from ".DB_PREFIX."user_group order by score asc limit 1");
//获取用户所在城市id
$city = $GLOBALS["db"]->getRow("select * from ".DB_PREFIX."region_conf where name="".$city_name.""");
if ($city)
{
switch ($city["region_level"]) {//im:1:国 2:省 3:市(县) 4:区(镇)
case "2":
$user_data["province_id"]=$city["id"];
break;
case "3":
$user_data["city_id"]=$city["id"];
$user_data["province_id"] = $city["pid"];
break;
default:
break;
}
}
//账号是否激活
// $user_data["is_effect"] = empty($user_data["is_effect"])? app_conf("USER_VERIFY"):$user_data["is_effect"];
$user_data["is_effect"]=1;//手机端注册,默认账号为激活状态
$user_data["code"] = ""; //默认不使用code, 该值用于其他系统导入时的初次认证
$user_data["user_pwd"] = md5($user_data["user_pwd"].$user_data["code"]);
$user_data["register_type"] = 1;//register_type:im:用户注册的方式:默认为0,web端注册,1为手机端注册
if($GLOBALS["db"]->autoExecute(DB_PREFIX."user",$user_data,"INSERT"))
{
$user_id = $GLOBALS["db"]->insert_id();
$register_money = app_conf("USER_REGISTER_MONEY");
$register_score = app_conf("USER_REGISTER_SCORE");
$register_point = app_conf("USER_REGISTER_POINT");
if($register_money>0||$register_score>0)
{
$user_get["score"] = $register_score;
$user_get["money"] = $register_money;
$user_get["point"] = $register_point;
@require_once "./app/modules/userModule.php";
modify_account($user_get,intval($user_id),"在".to_date(get_gmtime())."注册成功");
}
//im:添加登陆日志
$GLOBALS["db"]->autoExecute("im_user_login_log",array("user_id"=>$user_id,"l_type"=>1,"l_ip"=>$user_data["login_ip"],"l_time"=>get_gmtime(),"city_name"=>$city_name,"l_xpoint"=>$user_data["xpoint"],"l_ypoint"=>$user_data["ypoint"],"l_type"=>$l_type,"l_version"=>$l_version));
ajax_return(array("recode"=>"1009","msg"=>"用户注册成功","data"=>array("user_id"=>$user_id,"user_name"=>$user_data["user_name"],"email"=>is_null($user_data["email"])?"":$user_data["email"],"mobile"=>is_null($user_data["mobile"])?"":$user_data["mobile"],"create_time"=>to_date($user_data["create_time"]))));
}
else
{
ajax_return(array("recode"=>"1008","msg"=>"用户注册失败","data"=>""));
}
}
}
}
}
/*
* method userUpdatePwd 修改密码接口
* parameter int $user_id
* parameter string $old_pwd
* parameter string $new_pwd
* return 返回成功/失败
*/
function userUpdatePwd()
{
//{"user_id":0,"old_pwd":"111@qq.com","new_pwd":"13245678900"}
// $data=json_encode(array(
// "user_id"=>0,
// "old_pwd"=>"sara123@qq.com",
// "new_pwd"=>"13245678900"
// ));
$data=json_decode(@$_REQUEST["req"]);
$user_id = intval(@$data->user_id);
$user_pwd = trim(new_htmlspecialchars(new_addslashes(@$data->old_pwd)));
$new_pwd = trim(new_htmlspecialchars(new_addslashes(@$data->new_pwd)));
if ($user_id<=0)
{
$r=array("recode"=>"0002","msg"=>"参数错误.","data"=>"");
}
else
{
$msg=get_pwd_strength($new_pwd);
if(!empty($msg))
{
$r=array("recode"=>"1002","msg"=>$msg,"data"=>"");
ajax_return($r);
}
else
{
$user_data = $GLOBALS["db"]->getRow("select * from ".DB_PREFIX."user where id="".$user_id.""");
if(!$user_data)
{
$r=array("recode"=>"1014","msg"=>"该用户不存在,请确认操作.","data"=>"");
}
else
{
if($user_data["user_pwd"] != md5($user_pwd.$user_data["code"])&&$user_data["user_pwd"]!=$user_pwd)
{
$r=array("recode"=>"0012","msg"=>"用户密码不对,请确认您的登陆信息.","data"=>"");
}
elseif($user_data["is_effect"] != 1)
{
$r=array("recode"=>"0011","msg"=>"账号未被激活,暂时不能进行如下操作.","data"=>"");
}
else if ($user_data["is_delete"]==1)
{
$r=array("recode"=>"1012","msg"=>"该用户已被删除,请重新注册.","data"=>"");
}
else
{
$user_data["user_pwd"] = $new_pwd;
$new_pwd = md5($new_pwd.$user_data["code"]);
if($GLOBALS["db"]->query("update ".DB_PREFIX."user set user_pwd = "".$new_pwd."",password_verify="" where id = ".$user_data["id"] ))
{
$GLOBALS["db"]->query("update ".DB_PREFIX."supplier_account set account_password = "".$new_pwd."" where user_id = ".$user_data["id"] );
$r=array("recode"=>"0000","msg"=>"操作成功.","data"=>"");
}
else
{
$r=array("recode"=>"0001","msg"=>"操作失败.","data"=>"");
}
}
}
}
}
ajax_return($r);
}
}
?>
声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。
- 上一篇: Yii框架zii.widgets.grid自定义按钮,ajax触发事件并提示
- 下一篇:没有了
