14 php验证码

<?php
//session_start();
//
//$captchas	=	new captcha();
//$word		=	$captchas->generate_word(8);
//$image		=	$captchas->generate_image();
//if($image==false){
//	echo 'false';
//}
//其中存储的SESSION值使用base64_encode加密
class captcha
{
    /**
     * 背景图片所在目录
     *
     * @var string  $folder
     */
    var $folder     = "data/captcha/";
 
    /**
     * 图片的文件类型
     *
     * @var string  $img_type
     */
    var $img_type   = 'png';
 
    /*------------------------------------------------------ */
    //-- 存在session中的名称
    /*------------------------------------------------------ */
    var $session_word = 'captcha_word';
 
    /**
     * 背景图片以及背景颜色
     *
     * 0 => 背景图片的文件名
     * 1 => Red, 2 => Green, 3 => Blue
     * @var array   $themes
     */
    var $themes_jpg = array(
        1 => array('captcha_bg1.jpg', 255, 255, 255),
        2 => array('captcha_bg2.jpg', 0, 0, 0),
        3 => array('captcha_bg3.jpg', 0, 0, 0),
        4 => array('captcha_bg4.jpg', 255, 255, 255),
        5 => array('captcha_bg5.jpg', 255, 255, 255),
    );
 
    var $themes_gif = array(
        1 => array('captcha_bg1.gif', 255, 255, 255),
        2 => array('captcha_bg2.gif', 0, 0, 0),
        3 => array('captcha_bg3.gif', 0, 0, 0),
        4 => array('captcha_bg4.gif', 255, 255, 255),
        5 => array('captcha_bg5.gif', 255, 255, 255),
    );
 
    /**
     * 图片的宽度
     *
     * @var integer $width
     */
    var $width      = 130;
 
    /**
     * 图片的高度
     *
     * @var integer $height
     */
    var $height     = 20;
 
    /**
     * 构造函数
     *
     * @access  public
     * @param   string  $folder     背景图片所在目录
     * @param   integer $width      图片宽度
     * @param   integer $height     图片高度
     * @return  bool
     */
    function captcha($folder = '', $width = 145, $height = 20)
    {
        if (!empty($folder))
        {
            $this->folder = $folder;
        }
 
        $this->width    = $width;
        $this->height   = $height;
 
        /* 检查是否支持 GD */
        if (PHP_VERSION >= '4.3')
        {
 
            return (function_exists('imagecreatetruecolor') || function_exists('imagecreate'));
        }
        else
        {
 
            return (((imagetypes() & IMG_GIF) > 0) || ((imagetypes() & IMG_JPG)) > 0 );
        }
    }
 
    /**
     * 构造函数
     *
     * @access  public
     * @param
     *
     * @return void
     */
    function __construct($folder = '', $width = 145, $height = 20)
    {
        $this->captcha($folder, $width, $height);
    }
 
 
    /**
     * 检查给出的验证码是否和session中的一致
     *
     * @access  public
     * @param   string  $word   验证码
     * @return  bool
     */
    function check_word($word)
    {
        $recorded = isset($_SESSION[$this->session_word]) ? base64_decode($_SESSION[$this->session_word]) : '';
        $given    = $this->encrypts_word(strtoupper($word));
 
        return (preg_match("/$given/", $recorded));
    }
 
    /**
     * 生成图片并输出到浏览器
     *
     * @access  public
     * @param   string  $word   验证码
     * @return  mix
     */
    function generate_image($word = false)
    {
        if (!$word)
        {
            $word = $this->generate_word();
        }
 
        /* 记录验证码到session */
        $this->record_word($word);
 
        /* 验证码长度 */
        $letters = strlen($word);
 
        /* 选择一个随机的方案 */
        mt_srand((double) microtime() * 1000000);
 
        if (function_exists('imagecreatefromjpeg') && ((imagetypes() & IMG_JPG) > 0))
        {
            $theme  = $this->themes_jpg[mt_rand(1, count($this->themes_jpg))];
        }
        else
        {
            $theme  = $this->themes_gif[mt_rand(1, count($this->themes_gif))];
        }
		//print_r($theme);
        if (!file_exists($this->folder . $theme[0]))
        {
            return false;
        }
        else
        {
            $img_bg    = (function_exists('imagecreatefromjpeg') && ((imagetypes() & IMG_JPG) > 0)) ?
                            imagecreatefromjpeg($this->folder . $theme[0]) : imagecreatefromgif($this->folder . $theme[0]);
            $bg_width  = imagesx($img_bg);
            $bg_height = imagesy($img_bg);
 
            $img_org   = ((function_exists('imagecreatetruecolor')) && PHP_VERSION >= '4.3') ?
                          imagecreatetruecolor($this->width, $this->height) : imagecreate($this->width, $this->height);
 
            /* 将背景图象复制原始图象并调整大小 */
            if (function_exists('imagecopyresampled') && PHP_VERSION >= '4.3') // GD 2.x
            {
                imagecopyresampled($img_org, $img_bg, 0, 0, 0, 0, $this->width, $this->height, $bg_width, $bg_height);
            }
            else // GD 1.x
            {
                imagecopyresized($img_org, $img_bg, 0, 0, 0, 0, $this->width, $this->height, $bg_width, $bg_height);
            }
            imagedestroy($img_bg);
 
            $clr = imagecolorallocate($img_org, $theme[1], $theme[2], $theme[3]);
 
            /* 绘制边框 */
            //imagerectangle($img_org, 0, 0, $this->width - 1, $this->height - 1, $clr);
 
            /* 获得验证码的高度和宽度 */
            $x = ($this->width - (imagefontwidth(5) * $letters)) / 2;
            $y = ($this->height - imagefontheight(5)) / 2;
            imagestring($img_org, 5, $x, $y, $word, $clr);
 
            header('Expires: Thu, 01 Jan 1970 00:00:00 GMT');
 
            // HTTP/1.1
            header('Cache-Control: private, no-store, no-cache, must-revalidate');
            header('Cache-Control: post-check=0, pre-check=0, max-age=0', false);
 
            // HTTP/1.0
            header('Pragma: no-cache');
            if ($this->img_type == 'jpeg' && function_exists('imagecreatefromjpeg'))
            {
                header('Content-type: image/jpeg');
                imageinterlace($img_org, 1);
                imagejpeg($img_org, false, 95);
            }
            else
            {
                header('Content-type: image/png');
                imagepng($img_org);
            }
 
            imagedestroy($img_org);
 
            return true;
        }
    }
 
    /*------------------------------------------------------ */
    //-- PRIVATE METHODs
    /*------------------------------------------------------ */
 
    /**
     * 对需要记录的串进行加密
     *
     * @access  private
     * @param   string  $word   原始字符串
     * @return  string
     */
    function encrypts_word($word)
    {
        return substr(md5($word), 1, 10);
    }
 
    /**
     * 将验证码保存到session
     *
     * @access  private
     * @param   string  $word   原始字符串
     * @return  void
     */
    function record_word($word)
    {
        $_SESSION[$this->session_word] = base64_encode($this->encrypts_word($word));
    }
 
    /**
     * 生成随机的验证码
     *
     * @access  private
     * @param   integer $length     验证码长度
     * @return  string
     */
    function generate_word($length = 4)
    {
        $chars = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
 
        for ($i = 0, $count = strlen($chars); $i < $count; $i++)
        {
            $arr[$i] = $chars[$i];
        }
 
        mt_srand((double) microtime() * 1000000);
        shuffle($arr);
 
        return substr(implode('', $arr), 5, $length);
    }
}
 
?>

13 php mysql数据库类

在顶部写了几个实例,类是从ecshop上面弄下来的,有缓存功能,还是很好用的,有待更新。

<?php
/*
 * mysql类
 */
 
define('EC_CHARSET', 'utf8');
define('ROOT_PATH', 'D:/wamp/www/');
$DB		=	new cls_mysql('localhost', 'root', '', 'guestbook');
$sql	=	"SELECT * FROM  `messageclass`";
 
$re		=	$DB->getOne($sql);
print_r($re);
$DB->max_cache_time	=	2;
$re		=	$DB->getOneCached($sql);
print_r($re);
$re		=	$DB->getAll($sql);
print_r($re);
$re		=	$DB->getAllCached($sql);
print_r($re);
$re		=	$DB->getCol($sql);
print_r($re);
$re		=	$DB->getColCached($sql);
print_r($re);
$re		=	$DB->getRow($sql);
print_r($re);
$re		=	$DB->getRowCached($sql);
print_r($re);
 
$re		=	$DB->autoExecute('message', array('title'=>'1','content'=>'1'));
$re		=	$DB->get_table_name($sql);
var_dump($re);
//$re		=	$DB->autoReplace($table, $field_values, $update_values, $where = '', $querymode = '');
 
 
 
 
class cls_mysql
{
    var $link_id    = NULL;
    var $settings   = array();
    var $queryCount = 0;
    var $queryTime  = '';
    var $queryLog   = array();
    var $max_cache_time = 300; // 最大的缓存时间,以秒为单位
    var $cache_data_dir = 'temp/query_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->cls_mysql($dbhost, $dbuser, $dbpw, $dbname, $charset, $pconnect, $quiet);
    }
 
    function cls_mysql($dbhost, $dbuser, $dbpw, $dbname = '', $charset = 'utf8', $pconnect = 0, $quiet = 0)
    {
        if (defined('EC_CHARSET'))
        {
            $charset = strtolower(str_replace('-', '', EC_CHARSET));
        }
 
        if (defined('ROOT_PATH') && !$this->root_path)
        {
            $this->root_path = 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\r\n" .
                       '$this->mysql_config_cache_file_time = ' . $this->starttime . ";\r\n" .
                       '$this->timeline = ' . $this->timeline . ";\r\n" .
                       '$this->timezone = ' . $this->timezone . ";\r\n" .
                       '$this->platform = ' . "'" . $this->platform . "';\r\n?" . '>';
 
            @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 . "\n\n";
 
            if (PHP_VERSION >= '5.0')
            {
                file_put_contents($logfilename, $str, FILE_APPEND);
            }
            else
            {
                $fp = @fopen($logfilename, 'ab+');
                if ($fp)
                {
                    fwrite($fp, $str);
                    fclose($fp);
                }
            }
        }
 
        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)
        {
            echo "<b>Info</b>: $message\n\n<br /><br />";
          }
        else
        {
            echo "<b>MySQL server error report:";
            print_r($this->error_message);
         }
 
        exit;
    }
 
/* 仿真 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)
    {
 
        $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;
                    $values[] = "'" . $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)
                {
                    $sets[] = $value . " = '" . $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';
 
        $data = @file_get_contents($result['filename']);
        if (isset($data{23}))
        {
            $filetime = substr($data, 13, 10);
            $data     = substr($data, 23);
 
            if (($cached == 'FILEFIRST' && time() > $filetime + $this->max_cache_time) || ($cached == 'MYSQLFIRST' && $this->table_lastupdate($this->get_table_name($sql)) > $filetime))
            {
                $result['storecache'] = true;
            }
            else
            {
                $result['data'] = @unserialize($data);
                if ($result['data'] === false)
                {
                    $result['storecache'] = true;
                }
                else
                {
                    $result['storecache'] = false;
                }
            }
        }
        else
        {
            $result['storecache'] = true;
        }
 
        return $result;
    }
 
    function setSqlCacheData($result, $data)
    {
        if ($result['storecache'] === true && $result['filename'])
        {
            @file_put_contents($result['filename'], '<?php exit;?>' . time() . serialize($data));
            clearstatcache();
        }
    }
 
    /* 获取 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.*?FROM\s*((?:`?\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.*?FROM\s*((?:`?\w+`?\s*\.\s*)?`?\w+`?)(?:(?:\s*AS)?\s*`?\w+`?)?.*?JOIN.*$/is', $query_item, $table_names))
            {
                $other_table_names = array();
                preg_match_all('/JOIN\s*((?:`?\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);
    }
}
 
?>

other from ucenter

<?php
 
/*
	[Discuz!] (C)2001-2009 Comsenz Inc.
	This is NOT a freeware, use is subject to license terms
 
	$Id: db.class.php 976 2009-12-03 03:02:44Z zhaoxiongfei $
*/
 
if(!defined('IN_COMSENZ')) {
	exit('Access Denied');
}
 
class dbstuff {
	var $querynum = 0;
	var $link;
	var $histories;
	var $time;
	var $tablepre;
 
	function connect($dbhost, $dbuser, $dbpw, $dbname = '', $dbcharset, $pconnect = 0, $tablepre='', $time = 0) {
		$this->time = $time;
		$this->tablepre = $tablepre;
		if($pconnect) {
			if(!$this->link = mysql_pconnect($dbhost, $dbuser, $dbpw)) {
				$this->halt('Can not connect to MySQL server');
			}
		} else {
			if(!$this->link = mysql_connect($dbhost, $dbuser, $dbpw, 1)) {
				$this->halt('Can not connect to MySQL server');
			}
		}
 
		if($this->version() > '4.1') {
			if($dbcharset) {
				mysql_query("SET character_set_connection=".$dbcharset.", character_set_results=".$dbcharset.", character_set_client=binary", $this->link);
			}
 
			if($this->version() > '5.0.1') {
				mysql_query("SET sql_mode=''", $this->link);
			}
		}
 
		if($dbname) {
			mysql_select_db($dbname, $this->link);
		}
 
	}
 
	function fetch_array($query, $result_type = MYSQL_ASSOC) {
		return mysql_fetch_array($query, $result_type);
	}
 
	function result_first($sql, &$data) {
		$query = $this->query($sql);
		$data = $this->result($query, 0);
	}
 
	function fetch_first($sql, &$arr) {
		$query = $this->query($sql);
		$arr = $this->fetch_array($query);
	}
 
	function fetch_all($sql, &$arr) {
		$query = $this->query($sql);
		while($data = $this->fetch_array($query)) {
			$arr[] = $data;
		}
	}
 
	function cache_gc() {
		$this->query("DELETE FROM {$this->tablepre}sqlcaches WHERE expiry<$this->time");
	}
 
	function query($sql, $type = '', $cachetime = FALSE) {
		$func = $type == 'UNBUFFERED' && @function_exists('mysql_unbuffered_query') ? 'mysql_unbuffered_query' : 'mysql_query';
		if(!($query = $func($sql, $this->link)) && $type != 'SILENT') {
			$this->halt('MySQL Query Error', $sql);
		}
		$this->querynum++;
		$this->histories[] = $sql;
		return $query;
	}
 
	function affected_rows() {
		return mysql_affected_rows($this->link);
	}
 
	function error() {
		return (($this->link) ? mysql_error($this->link) : mysql_error());
	}
 
	function errno() {
		return intval(($this->link) ? mysql_errno($this->link) : mysql_errno());
	}
 
	function result($query, $row) {
		$query = @mysql_result($query, $row);
		return $query;
	}
 
	function num_rows($query) {
		$query = mysql_num_rows($query);
		return $query;
	}
 
	function num_fields($query) {
		return mysql_num_fields($query);
	}
 
	function free_result($query) {
		return mysql_free_result($query);
	}
 
	function insert_id() {
		return ($id = mysql_insert_id($this->link)) >= 0 ? $id : $this->result($this->query("SELECT last_insert_id()"), 0);
	}
 
	function fetch_row($query) {
		$query = mysql_fetch_row($query);
		return $query;
	}
 
	function fetch_fields($query) {
		return mysql_fetch_field($query);
	}
 
	function version() {
		return mysql_get_server_info($this->link);
	}
 
	function close() {
		return mysql_close($this->link);
	}
 
	function halt($message = '', $sql = '') {
		show_error('run_sql_error', $message.'<br /><br />'.$sql.'<br /> '.mysql_error(), 0);
	}
}
 
?>

10 php目录文件操作类

<?php
/*
 * 从网上找的目录文件操作类
 * 在最底下写了实例,可以一个一个单独的测试
 */
	class file_dir
	{
		function check_exist($filename)		//检查目录或文件是否存在
		{
			if(file_exists($filename))
			{
				return true;
			}
			else	return false;
		}
 
		function create_dir($dirname,$mode=0777)	// 一次只能创建一级目录
		{
			if(is_null($dirname) || $dirname=="")	return false;
			if(!is_dir($dirname))
			{
				return mkdir($dirname,$mode);
			}
		}
 
		function createDir($aimUrl)		//可同时创建多级目录
		{
        	$aimUrl = str_replace('\\', '/', $aimUrl);
        	$aimDir = '';
        	$arr = explode('/', $aimUrl);
        	foreach ($arr as $str)
        	{
            	$aimDir .= $str . '/';
            	if (!file_exists($aimDir))
            	{
                	mkdir($aimDir);
            	}
        	}
    	}
 
		function delete_dir($dirname)		//删除目录
		{
			if($this->check_exist($dirname) and is_dir($dirname))
			{
				if(!$dirhandle=opendir($dirname)) return false;
				while(($file=readdir($dirhandle))!==false)
				{
					if($file=="." or $file=="..")	continue;
					$file=$dirname.DIRECTORY_SEPARATOR.$file;  //表示$file是$dir的子目录
					if(is_dir($file))
					{
						$this->delete_dir($file);
					}
					else
					{
						unlink($file);
					}
				}
				closedir($dirhandle);
				return rmdir($dirname);
			}
			else	return false;
		}
 
		function copy_dir($dirfrom,$dirto)		//复制目录
		{
			if(!is_dir($dirfrom))	return false;
			if(!is_dir($dirto))		mkdir($dirto);
			$dirhandle=opendir($dirfrom);
			if($dirhandle)
			{
				while(false!==($file=readdir($dirhandle)))
				{
					if($file=="." or $file=="..")	continue;
					$filefrom=$dirfrom.DIRECTORY_SEPARATOR.$file;  //表示$file是$dir的子目录
					$fileto=$dirto.DIRECTORY_SEPARATOR.$file;
					if(is_dir($filefrom))
					{
						$this->copy_dir($filefrom,$fileto);
					}
					else
					{	if(!file_exists($fileto))
						copy($filefrom,$fileto);
					}
				}
			}
			closedir($dirhandle);
		}
 
		function getdir_size($dirname)		//获取目录大小
		{
			if(!file_exists($dirname) or !is_dir($dirname))	 return false;
			if(!$handle=opendir($dirname)) 	return false;
			$size=0;
			while(false!==($file=readdir($handle)))
			{
				if($file=="." or $file=="..")	continue;
				$file=$dirname."/".$file;
				if(is_dir($file))
				{
					$size+=$this->getdir_size($file);
				}
				else
				{
					$size+=filesize($file);
				}
 
			}
			closedir($handle);
			return $size;
		}
 
		function getReal_size($size)	   // 单位自动转换函数
		{
			$kb=1024;
			$mb=$kb*1024;
			$gb=$mb*1024;
			$tb=$gb*1024;
			if($size<$kb)	return $size."B";
			if($size>=$kb and $size<$mb)	return round($size/$kb,2)."KB";
			if($size>=$mb and $size<$gb)	return round($size/$mb,2)."MB";
			if($size>=$gb and $size<$tb)	return round($size/$gb,2)."GB";
			if($size>=$tb)	return round($size/$tb,2)."TB";
		}
 
		function copy_file($srcfile,$dstfile)
		{
			if(is_file($srcfile))
			{
				if(!file_exists($dstfile))
				return copy($srcfile,$dstfile);
			}
			else	return false;
		}
 
   	 	function unlink_file($filename)		//删除文件
   	 	{
   	 		if($this->check_exist($filename) and is_file($filename))
   	 		{
   	 			return unlink($filename);
   	 		}
   	 		else	return false;
   	 	}
 
   	 	function getsuffix($filename)			//获取文件名后缀
   	 	{
   	 		if(file_exists($filename) and is_file($filename))
   	 		{
   	 			return end(explode(".",$filename));
   	 		}
   	 	}
 
   	 	function input_content($filename,$str)		//将字符串写入文件
   	 	{
   	 		if(function_exists('file_put_contents'))
   	 		{
   	 			file_put_contents($filename,$str);
   	 		}
   	 		else
   	 		{
   	 			$fp=fopen($filename,"wb");
   	 			fwrite($fp,$str);
   	 			fclose($fp);
   	 		}
   	 	}
 
   	 	function output_content($filename)			//将整个文件内容读出到一个字符串中
   	 	{
   	 		if(function_exists('file_get_contents'))
   	 		{
   	 			return file_get_contents($filename);
   	 		}
   	 		else
   	 		{
   	 			$fp=fopen($filename,"rb");
   	 			$str=fread($fp,filesize($filename));
   	 			fclose($fp);
   	 			return $str;
   	 		}
   	 	}
 
   	 	function output_to_array($filename)		//将文件内容读出到一个数组中
   	 	{
   	 		$file=file($filename);
   	 		$arr=array();
   	 		foreach($file as $value)
   	 		{
   	 			$arr[]=trim($value);
   	 		}
   	 		return $arr;
   	 	}
 
 
	}
$dir=new file_dir;
 
$para	=	'<br />----------------------------------------------------------------------<br />';
 
echo $dir->check_exist("D:/wamp/www/test2/");echo $para;
echo $dir->create_dir("D:/wamp/www/test2/");echo $para;
echo $dir->createDir("D:/wamp/www/test2/test/");echo $para;
echo $dir->delete_dir("D:/wamp/www/test2/test/");echo $para;
echo $dir->copy_dir("D:/wamp/www/test/","D:/wamp/www/test3/");echo $para;
echo $size	=	$dir->getdir_size("D:/wamp/www/test3/");echo $para;
echo $dir->getReal_size($size);echo $para;
 
echo $dir->copy_file("D:/wamp/www/test3/fenlei.php","D:/wamp/www/test3/fenlei2.php");echo $para;
echo $dir->unlink_file("D:/wamp/www/test3/fenlei.php");echo $para;
echo $dir->getsuffix("D:/wamp/www/test3/fenlei2.php");echo $para;
echo $dir->input_content("D:/wamp/www/test3/fenlei5.php",'test');echo $para;
echo $dir->output_content("D:/wamp/www/test3/fenlei3.php");echo $para;
$outPut	=	$dir->output_to_array("D:/wamp/www/test3/fenlei3.php");echo $para;
print_r($outPut);
?>

列出所有的目录和文件(使用了递归readdir等函数)

function file_list($path)
{
	if ($handle = opendir($path)) 
	{
		while (false !== ($file = readdir($handle))) 
		{
			if ($file != "." && $file != "..") 
			{
				if (is_dir($path."/".$file)) 
				{
					echo $path.": ".$file."<br>";
					file_list($path."/".$file);
				} 
				else 
				{
					echo $path.": ".$file."<br>";
				}
			}
		}
	}
}
file_list('D:/wamp/www');

9 php加密解密处理类

<?php
/*===========================================================
= 版权协议:
= GPL (The GNU GENERAL PUBLIC LICENSE Version 2, June 1991)
=------------------------------------------------------------
= 文件名称:cls.sys_crypt.php
= 摘    要:php加密解密处理类
= 版    本:1.0
= 参    考:Discuz论坛的passport相关函数
=------------------------------------------------------------
= Script Written By PHPWMS项目组
= 最后更新:xinge
= 最后日期:2007-12-09
============================================================*/
 
class SysCrypt {
 
private $crypt_key;
 
// 构造函数
public function __construct($crypt_key) {
   $this -> crypt_key = $crypt_key;
}
 
public function php_encrypt($txt) {
   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(self::__key($tmp,$this -> crypt_key));
}
 
public function php_decrypt($txt) {
   $txt = self::__key(base64_decode($txt),$this -> crypt_key);
   $tmp = '';
   for($i = 0;$i < strlen($txt); $i++) {
    $md5 = $txt[$i];
    $tmp .= $txt[++$i] ^ $md5;
   }
   return $tmp;
}
 
private function __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 function __destruct() {
   $this -> crypt_key = null;
}
}
 
 
$sc = new SysCrypt('phpwms');
$text = '110';
print($sc -> php_encrypt($text));
print('<br>');
print($sc -> php_decrypt($sc -> php_encrypt($text)));
?>