Archive for January, 2012

作者:AngryFox 分类: Uncategorized January 29th, 2012 暂无评论

但是要一次查询到重复字段的id值,就必须使用子查询了,于是使用下面的语句来实现MySQL大表重复字段查询

。
    SELECT `id`,`name`
    FROM `table`
    WHERE `name` in (
       SELECT `name`
       FROM `table`
       GROUP BY `name` HAVING count(`name`) >1
    );
  但是这条语句在mysql中效率太差,感觉mysql并没有为子查询生成临时表。
  于是使用先建立临时表
    create table `tmptable` as (
       SELECT `name`
       FROM `table`
       GROUP BY `name` HAVING count(`name`) >1
    );
  然后使用多表连接查询
    SELECT a.`id`, a.`name`
    FROM `table` a, `tmptable` t
    WHERE a.`name` = t.`name`;   

  结果这次结果很快就出来了。

  用 distinct去重复

    SELECT distinct a.`id`, a.`name`
    FROM `table` a, `tmptable` t
    WHERE a.`name` = t.`name`;   
作者:AngryFox 分类: Uncategorized January 3rd, 2012 暂无评论
<?php
/**
* Pinyin.php
* Author  :  冷流云
**/
function Pinyin($_String, $_Code='gb2312')
{
        $_DataKey = "a|ai|an|ang|ao|ba|bai|ban|bang|bao|bei|ben|beng|bi|bian|biao|bie|bin|bing|bo|bu|ca|cai|can|cang|cao|ce|ceng|cha".
                "|chai|chan|chang|chao|che|chen|cheng|chi|chong|chou|chu|chuai|chuan|chuang|chui|chun|chuo|ci|cong|cou|cu|".
                "cuan|cui|cun|cuo|da|dai|dan|dang|dao|de|deng|di|dian|diao|die|ding|diu|dong|dou|du|duan|dui|dun|duo|e|en|er".
                "|fa|fan|fang|fei|fen|feng|fo|fou|fu|ga|gai|gan|gang|gao|ge|gei|gen|geng|gong|gou|gu|gua|guai|guan|guang|gui".
                "|gun|guo|ha|hai|han|hang|hao|he|hei|hen|heng|hong|hou|hu|hua|huai|huan|huang|hui|hun|huo|ji|jia|jian|jiang".
                "|jiao|jie|jin|jing|jiong|jiu|ju|juan|jue|jun|ka|kai|kan|kang|kao|ke|ken|keng|kong|kou|ku|kua|kuai|kuan|kuang".
                "|kui|kun|kuo|la|lai|lan|lang|lao|le|lei|leng|li|lia|lian|liang|liao|lie|lin|ling|liu|long|lou|lu|lv|luan|lue".
                "|lun|luo|ma|mai|man|mang|mao|me|mei|men|meng|mi|mian|miao|mie|min|ming|miu|mo|mou|mu|na|nai|nan|nang|nao|ne".
                "|nei|nen|neng|ni|nian|niang|niao|nie|nin|ning|niu|nong|nu|nv|nuan|nue|nuo|o|ou|pa|pai|pan|pang|pao|pei|pen".
                "|peng|pi|pian|piao|pie|pin|ping|po|pu|qi|qia|qian|qiang|qiao|qie|qin|qing|qiong|qiu|qu|quan|que|qun|ran|rang".
                "|rao|re|ren|reng|ri|rong|rou|ru|ruan|rui|run|ruo|sa|sai|san|sang|sao|se|sen|seng|sha|shai|shan|shang|shao|".
                "she|shen|sheng|shi|shou|shu|shua|shuai|shuan|shuang|shui|shun|shuo|si|song|sou|su|suan|sui|sun|suo|ta|tai|".
                "tan|tang|tao|te|teng|ti|tian|tiao|tie|ting|tong|tou|tu|tuan|tui|tun|tuo|wa|wai|wan|wang|wei|wen|weng|wo|wu".
                "|xi|xia|xian|xiang|xiao|xie|xin|xing|xiong|xiu|xu|xuan|xue|xun|ya|yan|yang|yao|ye|yi|yin|ying|yo|yong|you".
                "|yu|yuan|yue|yun|za|zai|zan|zang|zao|ze|zei|zen|zeng|zha|zhai|zhan|zhang|zhao|zhe|zhen|zheng|zhi|zhong|".
                "zhou|zhu|zhua|zhuai|zhuan|zhuang|zhui|zhun|zhuo|zi|zong|zou|zu|zuan|zui|zun|zuo"; 

        $_DataValue = "-20319|-20317|-20304|-20295|-20292|-20283|-20265|-20257|-20242|-20230|-20051|-20036|-20032|-20026|-20002|-19990".
                "|-19986|-19982|-19976|-19805|-19784|-19775|-19774|-19763|-19756|-19751|-19746|-19741|-19739|-19728|-19725".
                "|-19715|-19540|-19531|-19525|-19515|-19500|-19484|-19479|-19467|-19289|-19288|-19281|-19275|-19270|-19263".
                "|-19261|-19249|-19243|-19242|-19238|-19235|-19227|-19224|-19218|-19212|-19038|-19023|-19018|-19006|-19003".
                "|-18996|-18977|-18961|-18952|-18783|-18774|-18773|-18763|-18756|-18741|-18735|-18731|-18722|-18710|-18697".
                "|-18696|-18526|-18518|-18501|-18490|-18478|-18463|-18448|-18447|-18446|-18239|-18237|-18231|-18220|-18211".
                "|-18201|-18184|-18183|-18181|-18012|-17997|-17988|-17970|-17964|-17961|-17950|-17947|-17931|-17928|-17922".
                "|-17759|-17752|-17733|-17730|-17721|-17703|-17701|-17697|-17692|-17683|-17676|-17496|-17487|-17482|-17468".
                "|-17454|-17433|-17427|-17417|-17202|-17185|-16983|-16970|-16942|-16915|-16733|-16708|-16706|-16689|-16664".
                "|-16657|-16647|-16474|-16470|-16465|-16459|-16452|-16448|-16433|-16429|-16427|-16423|-16419|-16412|-16407".
                "|-16403|-16401|-16393|-16220|-16216|-16212|-16205|-16202|-16187|-16180|-16171|-16169|-16158|-16155|-15959".
                "|-15958|-15944|-15933|-15920|-15915|-15903|-15889|-15878|-15707|-15701|-15681|-15667|-15661|-15659|-15652".
                "|-15640|-15631|-15625|-15454|-15448|-15436|-15435|-15419|-15416|-15408|-15394|-15385|-15377|-15375|-15369".
                "|-15363|-15362|-15183|-15180|-15165|-15158|-15153|-15150|-15149|-15144|-15143|-15141|-15140|-15139|-15128".
                "|-15121|-15119|-15117|-15110|-15109|-14941|-14937|-14933|-14930|-14929|-14928|-14926|-14922|-14921|-14914".
                "|-14908|-14902|-14894|-14889|-14882|-14873|-14871|-14857|-14678|-14674|-14670|-14668|-14663|-14654|-14645".
                "|-14630|-14594|-14429|-14407|-14399|-14384|-14379|-14368|-14355|-14353|-14345|-14170|-14159|-14151|-14149".
                "|-14145|-14140|-14137|-14135|-14125|-14123|-14122|-14112|-14109|-14099|-14097|-14094|-14092|-14090|-14087".
                "|-14083|-13917|-13914|-13910|-13907|-13906|-13905|-13896|-13894|-13878|-13870|-13859|-13847|-13831|-13658".
                "|-13611|-13601|-13406|-13404|-13400|-13398|-13395|-13391|-13387|-13383|-13367|-13359|-13356|-13343|-13340".
                "|-13329|-13326|-13318|-13147|-13138|-13120|-13107|-13096|-13095|-13091|-13076|-13068|-13063|-13060|-12888".
                "|-12875|-12871|-12860|-12858|-12852|-12849|-12838|-12831|-12829|-12812|-12802|-12607|-12597|-12594|-12585".
                "|-12556|-12359|-12346|-12320|-12300|-12120|-12099|-12089|-12074|-12067|-12058|-12039|-11867|-11861|-11847".
                "|-11831|-11798|-11781|-11604|-11589|-11536|-11358|-11340|-11339|-11324|-11303|-11097|-11077|-11067|-11055".
                "|-11052|-11045|-11041|-11038|-11024|-11020|-11019|-11018|-11014|-10838|-10832|-10815|-10800|-10790|-10780".
                "|-10764|-10587|-10544|-10533|-10519|-10331|-10329|-10328|-10322|-10315|-10309|-10307|-10296|-10281|-10274".
                "|-10270|-10262|-10260|-10256|-10254";
        $_TDataKey   = explode('|', $_DataKey);
        $_TDataValue = explode('|', $_DataValue); 

        $_Data = (PHP_VERSION>='5.0')?array_combine($_TDataKey,$_TDataValue):_Array_Combine($_TDataKey,$_TDataValue);
        arsort($_Data);
        reset($_Data); 

        if($_Code != 'gb2312') $_String = _U2_Utf8_Gb($_String);
        $_Res = '';
        for($i=0; $i<strlen($_String); $i++)
        {
                $_P = ord(substr($_String, $i, 1));
                if($_P>160) { $_Q = ord(substr($_String, ++$i, 1)); $_P = $_P*256 + $_Q - 65536; }
                $_Res .= _Pinyin($_P, $_Data);
        }
        return preg_replace("/[^a-z0-9]*/", '', $_Res);
} 

function _Pinyin($_Num, $_Data)
{
        if    ($_Num>0      && $_Num<160   ) return chr($_Num);
        elseif($_Num<-20319 || $_Num>-10247) return '';
        else  {
                foreach($_Data as $k=>$v){ if($v<=$_Num) break; }
                return $k;
        }
} 

function _U2_Utf8_Gb($_C)
{
        $_String = '';
        if($_C < 0x80) $_String .= $_C;
        elseif($_C < 0x800)
        {
                $_String .= chr(0xC0 | $_C>>6);
                $_String .= chr(0x80 | $_C & 0x3F);
        }elseif($_C < 0x10000){
                $_String .= chr(0xE0 | $_C>>12);
                $_String .= chr(0x80 | $_C>>6 & 0x3F);
                $_String .= chr(0x80 | $_C & 0x3F);
        } elseif($_C < 0x200000) {
                $_String .= chr(0xF0 | $_C>>18);
                $_String .= chr(0x80 | $_C>>12 & 0x3F);
                $_String .= chr(0x80 | $_C>>6 & 0x3F);
                $_String .= chr(0x80 | $_C & 0x3F);
        }
        return iconv('UTF-8', 'GB2312', $_String);
} 

function _Array_Combine($_Arr1, $_Arr2)
{
        for($i=0; $i<count($_Arr1); $i++) $_Res[$_Arr1[$i]] = $_Arr2[$i];
        return $_Res;
} 

echo Pinyin('这是WEB开发'); //默认是gb编码
echo Pinyin('这是WEB开发',1); //第二个参数随意设置即为utf8编码
?>
作者:AngryFox 分类: Uncategorized January 3rd, 2012 暂无评论
$runtime= new runtime;
$runtime->start();

$runtime->stop();

echo "页面执行时间: ".$runtime->spent()." 毫秒";

class runtime
{
    var $StartTime = 0;
    var $StopTime = 0;
    function get_microtime()
    {
        list($usec, $sec) = explode(' ', microtime());
        return ((float)$usec + (float)$sec);
    }

    function start()
    {
        $this->StartTime = $this->get_microtime();
    }

    function stop()
    {
        $this->StopTime = $this->get_microtime();
    }

    function spent()
    {
        return round(($this->StopTime - $this->StartTime) * 1000, 1);
    }
}
?>
作者:AngryFox 分类: Uncategorized January 3rd, 2012 暂无评论
function cutstr($string, $length, $dot = ' ...')
{
	global $charset;

	if(strlen($string) <= $length) return $string;

	$string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);

	$strcut = '';

	if(strtolower($charset) == 'utf-8')
	{
		$n = $tn = $noc = 0;

		while($n < strlen($string))
		{
			$t = ord($string[$n]);

			// 特别要注意这部分,utf-8是1--6位不定长表示的,这里就是如何
			// 判断utf-8是1位2位还是3位还是4、5、6位,这对其他语言的编程也有用处
			// 具体可以查看rfc3629或rfc2279
			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126))
			{
				$tn = 1; $n++; $noc++;
			}
			elseif(194 <= $t && $t <= 223)
			{
				$tn = 2; $n += 2; $noc += 2;
			}
			elseif(224 <= $t && $t < 239)
			{
				$tn = 3; $n += 3; $noc += 2;
			}
			elseif(240 <= $t && $t <= 247)
			{
				$tn = 4; $n += 4; $noc += 2;
			}
			elseif(248 <= $t && $t <= 251)
			{
				$tn = 5; $n += 5; $noc += 2;
			}
			elseif($t == 252 || $t == 253)
			{
				$tn = 6; $n += 6; $noc += 2;
			}
			else
			{
				$n++;
			}

			if($noc >= $length)
			{
				break;
			}

		}

		if($noc > $length) $n -= $tn;

		$strcut = substr($string, 0, $n);
	}
	else
	{
		for($i = 0; $i < $length; $i++)
		{
			$strcut .= ord($string[$i]) > 127 ? $string[$i] . $string[++$i] : $string[$i];
		}
	}

	$strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);

	return $strcut . $dot;
}
$testStr = "好好学习!(good good study)天天向上!(day day up)";     // ^_^! V

// 使用utf文档
echo cutstr($testStr, 10);

// 使用dos文档使用以下代码测试utf-8的效果
//$testStr = iconv('GBK', 'UTF-8', $testStr);
//echo iconv('UTF-8', 'GBK', cutstr($testStr, 10));
作者:AngryFox 分类: Uncategorized January 3rd, 2012 暂无评论

借用memcache的 get set del的思想,把数据存在文件中,is_file存在则导入数据,不存在就重新获取数据。

file_put_contents('arr.php' , '<?php return '.var_export($arr , true).'; ?>');

对于访问量 日不足100万的,可以直接生成静态文件

作者:AngryFox 分类: Uncategorized January 3rd, 2012 暂无评论
Begin; 

Select   restnum  from  book  where  id =1  for   update ;
Update   book  set restnum=restnum-1 where id=1 ;  

Commit;   

update book set restnum=restnum-1 where id=1 and restnum>0;
作者:AngryFox 分类: Uncategorized January 3rd, 2012 暂无评论
<?php
class Mcrypt
{
	/**
	 * 解密
	 *
	 * @param string $encryptedText 已加密字符串
	 * @param string $key  密钥
	 * @return string
	 */
	public static function _decrypt($encryptedText,$key = null)
	{
		$key = $key === null ? Config::get('secret_key') : $key;
		$cryptText = base64_decode($encryptedText);
		$ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
		$iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
		$decryptText = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $cryptText, MCRYPT_MODE_ECB, $iv);
		return trim($decryptText);
	}

	/**
	 * 加密
	 *
	 * @param string $plainText	未加密字符串
	 * @param string $key		 密钥
	 */
	public static function _encrypt($plainText,$key = null)
	{
		$key = $key === null ? Config::get('secret_key') : $key;
		$ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
		$iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
		$encryptText = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $plainText, MCRYPT_MODE_ECB, $iv);
		return trim(base64_encode($encryptText));
	}
}

<?php
class Cookie extends Mcrypt
{
	/**
	 * 删除cookie
	 *
	 * @param array $args
	 * @return boolean
	 */
	public static function del($args)
	{
		$name = $args['name'];
		$domain = isset($args['domain']) ? $args['domain'] : null;
		return isset($_COOKIE[$name]) ? setcookie($name, '', time() - 86400, '/', $domain) : true;
	}

	/**
	 * 得到指定cookie的值
	 *
	 * @param string $name
	 */
	public static function get($name)
	{
		return isset($_COOKIE[$name]) ? parent::_decrypt($_COOKIE[$name]) : null;
	}

	/**
	 * 设置cookie
	 *
	 * @param array $args
	 * @return boolean
	 */
	public static function set($args)
	{
		$name = $args['name'];
		$value= parent::_encrypt($args['value']);
		$expire = isset($args['expire']) ? $args['expire'] : null;
		$path = isset($args['path']) ? $args['path'] : '/';
		$domain = isset($args['domain']) ? $args['domain'] : null;
		$secure = isset($args['secure']) ? $args['secure'] : 0;
		return setcookie($name, $value, $expire, $path, $domain, $secure);
	}
}
作者:AngryFox 分类: Uncategorized January 3rd, 2012 暂无评论
<?php
/*
本类支持多文件上传,图片生成略缩图,加水印,按日期生成目录的基本功能
调用例子:
控制器代码:
<?php
if ($_GET['action'] == 'save') {
    $up = new upload();     //创建
    $up->set_dir(dirname(__FILE__).'/upload/','{y}/{m}');   //保存路径,支持{y}{m}{d}这几个选项
    $up->set_thumb(100,80);       //缩略图大小设置.单位为像素
    $up->set_watermark(dirname(__FILE__).'/jblog/images/watermark.png',6,90);       //水印设置
    $fs = $up->execute();    //开始执行   

    var_dump($fs);       //测试用 查看类的情况
}
?>
/////视图表单---------
<html>
    <head><title>test</title></head>
    <body style="margin:0;padding:0″>
    <form name="upload" method="post" action="?action=save" enctype="multipart/form-data" style="margin:0″>
        <input type="file" name="attach[]" />
        <input type="file" name="attach[]" />     //支持多张图片上传
        <input type="submit" name="submit" value="上 传" />
    </form>
    </body>
</html> 

*/
class upload {       

    var $dir;            //附件存放物理目录
    var $time;           //自定义文件上传时间
    var $allow_types;    //允许上传附件类型
    var $field;          //上传控件名称
    var $maxsize;        //最大允许文件大小,单位为KB       

    var $thumb_width;    //缩略图宽度
    var $thumb_height;   //缩略图高度       

    var $watermark_file; //水印图片地址
    var $watermark_pos;  //水印位置
    var $watermark_trans;//水印透明度       

    //构造函数
    //$types : 允许上传的文件类型 , $maxsize : 允许大小 ,  $field : 上传控件名称 , $time : 自定义上传时间
    function upload($types = 'jpg|png', $maxsize = 1024, $field = 'attach', $time = '') {
        $this->allow_types = explode('|',$types);
        $this->maxsize = $maxsize * 1024;
        $this->field = $field;
        $this->time = $time ? $time : time();
    }       

    //设置并创建文件具体存放的目录
    //$basedir  : 基目录,必须为物理路径
    //$filedir  : 自定义子目录,可用参数{y}、{m}、{d}
    function set_dir($basedir,$filedir = '') {
        $dir = $basedir;
        !is_dir($dir) && @mkdir($dir,0777);
        if (!empty($filedir)) {
            $filedir = str_replace(array('{y}','{m}','{d}'),array(date('Y',$this->time),date('m',$this->time),date('d',$this->time)),strtolower($filedir));//用string_replace把{y} {m} {d}几个标签进行替换
            $dirs = explode('/',$filedir);
            foreach ($dirs as $d) {
                !empty($d) && $dir .= $d.'/';
                !is_dir($dir) && @mkdir($dir,0777);
            }
        }
        $this->dir = $dir;
    }       

    //图片缩略图设置,如果不生成缩略图则不用设置
    //$width : 缩略图宽度 , $height : 缩略图高度
    function set_thumb ($width = 0, $height = 0) {
        $this->thumb_width  = $width;
        $this->thumb_height = $height;
    }       

    //图片水印设置,如果不生成添加水印则不用设置
    //$file : 水印图片 , $pos : 水印位置 , $trans : 水印透明度
    function set_watermark ($file, $pos = 6, $trans = 80) {
        $this->watermark_file  = $file;
        $this->watermark_pos   = $pos;
        $this->watermark_trans = $trans;
    }       

    /*—————————————————————-
    执行文件上传,处理完返回一个包含上传成功或失败的文件信息数组,
    其中:name 为文件名,上传成功时是上传到服务器上的文件名,上传失败则是本地的文件名
          dir  为服务器上存放该附件的物理路径,上传失败不存在该值
          size 为附件大小,上传失败不存在该值
          flag 为状态标识,1表示成功,-1表示文件类型不允许,-2表示文件大小超出
    —————————————————————–*/
    function execute() {
        $files = array(); //成功上传的文件信息
        $field = $this->field;
        $keys = array_keys($_FILES[$field]['name']);
        foreach ($keys as $key) {
            if (!$_FILES[$field]['name'][$key]) continue;       

            $fileext = $this->fileext($_FILES[$field]['name'][$key]); //获取文件扩展名
            $filename = date('Ymdhis',$this->time).mt_rand(10,99).'.'.$fileext; //生成文件名
            $filedir = $this->dir;  //附件实际存放目录
            $filesize = $_FILES[$field]['size'][$key]; //文件大小       

            //文件类型不允许
            if (!in_array($fileext,$this->allow_types)) {
                $files[$key]['name'] = $_FILES[$field]['name'][$key];
                $files[$key]['flag'] = -1;
                continue;
            }       

            //文件大小超出
            if ($filesize > $this->maxsize) {
                $files[$key]['name'] = $_FILES[$field]['name'][$key];
                $files[$key]['name'] = $filesize;
                $files[$key]['flag'] = -2;
                continue;
            }       

            $files[$key]['name'] = $filename;
            $files[$key]['dir'] = $filedir;
            $files[$key]['size'] = $filesize;       

            //保存上传文件并删除临时文件
            if (is_uploaded_file($_FILES[$field]['tmp_name'][$key])) {
                move_uploaded_file($_FILES[$field]['tmp_name'][$key],$filedir.$filename);
                @unlink($_FILES[$field]['tmp_name'][$key]);
                $files[$key]['flag'] = 1;       

                //对图片进行加水印和生成缩略图,这里演示只支持jpg和png(gif生成的话会没了帧的)
                if (in_array($fileext,array('jpg','png'))) {
                    if ($this->thumb_width) {
                        if ($this->create_thumb($filedir.$filename,$filedir.'thumb_'.$filename)) {
                            $files[$key]['thumb'] = 'thumb_'.$filename;  //缩略图文件名
                        }
                    }
                    $this->create_watermark($filedir.$filename);
                }
            }
        }       

        return $files;
    }       

    //创建缩略图,以相同的扩展名生成缩略图
    //$src_file : 来源图像路径 , $thumb_file : 缩略图路径
    function create_thumb ($src_file,$thumb_file) {
        $t_width  = $this->thumb_width;
        $t_height = $this->thumb_height;       

        if (!file_exists($src_file)) return false;       

        $src_info = getImageSize($src_file);       

        //如果来源图像小于或等于缩略图则拷贝源图像作为缩略图,免去操作
        if ($src_info[0] <= $t_width && $src_info[1] <= $t_height) {
            if (!copy($src_file,$thumb_file)) {
                return false;
            }
            return true;
        }       

        //按比例计算缩略图大小
        if (($src_info[0]-$t_width) > ($src_info[1]-$t_height)) {
            $t_height = ($t_width / $src_info[0]) * $src_info[1];
        } else {
            $t_width = ($t_height / $src_info[1]) * $src_info[0];
        }       

        //取得文件扩展名
        $fileext = $this->fileext($src_file);       

        switch ($fileext) {
            case 'jpg' :
                $src_img = ImageCreateFromJPEG($src_file); break;
            case 'png' :
                $src_img = ImageCreateFromPNG($src_file); break;
            case 'gif' :
                $src_img = ImageCreateFromGIF($src_file); break;
        }       

        //创建一个真彩色的缩略图像
        $thumb_img = @ImageCreateTrueColor($t_width,$t_height);       

        //ImageCopyResampled函数拷贝的图像平滑度较好,优先考虑
        if (function_exists('imagecopyresampled')) {
            @ImageCopyResampled($thumb_img,$src_img,0,0,0,0,$t_width,$t_height,$src_info[0],$src_info[1]);
        } else {
            @ImageCopyResized($thumb_img,$src_img,0,0,0,0,$t_width,$t_height,$src_info[0],$src_info[1]);
        }       

        //生成缩略图
        switch ($fileext) {
            case 'jpg' :
                ImageJPEG($thumb_img,$thumb_file); break;
            case 'gif' :
                ImageGIF($thumb_img,$thumb_file); break;
            case 'png' :
                ImagePNG($thumb_img,$thumb_file); break;
        }       

        //销毁临时图像
        @ImageDestroy($src_img);
        @ImageDestroy($thumb_img);       

        return true;       

    }       

    //为图片添加水印
    //$file : 要添加水印的文件
    function create_watermark ($file) {       

        //文件不存在则返回
        if (!file_exists($this->watermark_file) || !file_exists($file)) return;
        if (!function_exists('getImageSize')) return;       

        //检查GD支持的文件类型
        $gd_allow_types = array();
        if (function_exists('ImageCreateFromGIF')) $gd_allow_types['image/gif'] = 'ImageCreateFromGIF';
        if (function_exists('ImageCreateFromPNG')) $gd_allow_types['image/png'] = 'ImageCreateFromPNG';
        if (function_exists('ImageCreateFromJPEG')) $gd_allow_types['image/jpeg'] = 'ImageCreateFromJPEG';       

        //获取文件信息
        $fileinfo = getImageSize($file);
        $wminfo   = getImageSize($this->watermark_file);       

        if ($fileinfo[0] < $wminfo[0] || $fileinfo[1] < $wminfo[1]) return;       

        if (array_key_exists($fileinfo['mime'],$gd_allow_types)) {
            if (array_key_exists($wminfo['mime'],$gd_allow_types)) {       

                //从文件创建图像
                $temp = $gd_allow_types[$fileinfo['mime']]($file);
                $temp_wm = $gd_allow_types[$wminfo['mime']]($this->watermark_file);       

                //水印位置
                switch ($this->watermark_pos) {
                    case 1 :  //顶部居左
                        $dst_x = 0; $dst_y = 0; break;
                    case 2 :	//顶部居中
                        $dst_x = ($fileinfo[0] - $wminfo[0])/2; $dst_y = 0; break;
                    case 3 :  //顶部居右
                        $dst_x = $fileinfo[0]; $dst_y = 0; break;
                    case 4 :  //底部居左
                        $dst_x = 0; $dst_y = $fileinfo[1]; break;
                    case 5 :  //底部居中
                        $dst_x = ($fileinfo[0] - $wminfo[0]) / 2; $dst_y = $fileinfo[1]; break;
                    case 6 :  //底部居右
                        $dst_x = $fileinfo[0]-$wminfo[0]; $dst_y = $fileinfo[1]-$wminfo[1]; break;
                    default : //随机
                        $dst_x = mt_rand(0,$fileinfo[0]-$wminfo[0]); $dst_y = mt_rand(0,$fileinfo[1]-$wminfo[1]);
                }       

                if (function_exists('ImageAlphaBlending')) ImageAlphaBlending($temp_wm,True); //设定图像的混色模式
                if (function_exists('ImageSaveAlpha')) ImageSaveAlpha($temp_wm,True); //保存完整的 alpha 通道信息       

                //为图像添加水印
                if (function_exists('imageCopyMerge')) {
                    ImageCopyMerge($temp,$temp_wm,$dst_x,$dst_y,0,0,$wminfo[0],$wminfo[1],$this->watermark_trans);
                } else {
                    ImageCopyMerge($temp,$temp_wm,$dst_x,$dst_y,0,0,$wminfo[0],$wminfo[1]);
                }       

                //保存图片
                switch ($fileinfo['mime']) {
                    case 'image/jpeg' :
                        @imageJPEG($temp,$file);
                        break;
                    case 'image/png' :
                        @imagePNG($temp,$file);
                        break;
                    case 'image/gif' :
                        @imageGIF($temp,$file);
                        break;
                }
                //销毁零时图像
                @imageDestroy($temp);
                @imageDestroy($temp_wm);
            }
        }
    }       

    //获取文件扩展名
    function fileext($filename) {
        return strtolower(substr(strrchr($filename,'.'),1,10));
    }
}
?>
作者:AngryFox 分类: Uncategorized January 3rd, 2012 暂无评论
<?php
class AvatarUploader
{
    // ? url
    private function getThisUrl()
    {
        $thisUrl = $_SERVER['SCRIPT_NAME'];
        $thisUrl = "http://{$_SERVER['HTTP_HOST']}{$thisUrl}";
        return $thisUrl;
    }

    // ? base-url /
    private function getBaseUrl()
    {
        $baseUrl = $this->getThisUrl();
        $baseUrl = substr( $baseUrl, 0, strrpos( $baseUrl, '/' ) + 1 );
        return $baseUrl;
    }

    // ???? DIRECTORY_SEPARATOR
    private function getBasePath()
    {
        $basePath = $_SERVER['SCRIPT_FILENAME'];
        $basePath = substr( $basePath, 0, strrpos($basePath, '/' ) + 1 );
        $basePath = str_replace( '/', DIRECTORY_SEPARATOR, $basePath );
        return $basePath;
    }

    // ???????
    private function uploadAvatar( $uid )
    {
        // ??
        if ( empty($_FILES['Filedata']) ) {
            return -3; // No photograph be upload!
        }

        // ?
        $tmpPath = $this->getBasePath() . "data" . DIRECTORY_SEPARATOR . "{$uid}";

        // ????
        $dir = dirname( $tmpPath );
        if ( !file_exists( $dir ) ) {
            @mkdir( $dir, 0777, true );
        }

        // ??????
        if ( file_exists($tmpPath) ) {
            @unlink($tmpPath);
        }

        // ?????
        if ( @copy($_FILES['Filedata']['tmp_name'], $tmpPath) || @move_uploaded_file($_FILES['Filedata']['tmp_name'], $tmpPath)) {
            @unlink($_FILES['Filedata']['tmp_name']);
            list($width, $height, $type, $attr) = getimagesize($tmpPath);
            if ( $width < 10 || $height < 10 || $width > 3000 || $height > 3000 || $type == 4 ) {
                @unlink($tmpPath);
                return -2; // Invalid photograph!
            }
        } else {
            @unlink($_FILES['Filedata']['tmp_name']);
            return -4; // Can not write to the data/tmp folder!
        }

        // ????? url
        $tmpUrl = $this->getBaseUrl() . "data/{$uid}";
        return $tmpUrl;
    }

    private function flashdata_decode($s) {
        $r = '';
        $l = strlen($s);
        for($i=0; $i<$l; $i=$i+2) {
            $k1 = ord($s[$i]) - 48;
            $k1 -= $k1 > 9 ? 7 : 0;
            $k2 = ord($s[$i+1]) - 48;
            $k2 -= $k2 > 9 ? 7 : 0;
            $r .= chr($k1 << 4 | $k2);
        }
        return $r;
    }

    // ?????
    private function rectAvatar( $uid )
    {
        //  $_POST ???
        $bigavatar    = $this->flashdata_decode( $_POST['avatar1'] );
        $middleavatar = $this->flashdata_decode( $_POST['avatar2'] );
        $smallavatar  = $this->flashdata_decode( $_POST['avatar3'] );
        if ( !$bigavatar || !$middleavatar || !$smallavatar ) {
            return '<root><message type="error" value="-2" /></root>';
        }

        // ????
        $bigavatarfile    = $this->getBasePath() . "data" . DIRECTORY_SEPARATOR . "{$uid}_big.jpg";
        $middleavatarfile = $this->getBasePath() . "data" . DIRECTORY_SEPARATOR . "{$uid}_middle.jpg";
        $smallavatarfile  = $this->getBasePath() . "data" . DIRECTORY_SEPARATOR . "{$uid}_small.jpg";

        $success = 1;
        $fp = @fopen($bigavatarfile, 'wb');
        @fwrite($fp, $bigavatar);
        @fclose($fp);

        $fp = @fopen($middleavatarfile, 'wb');
        @fwrite($fp, $middleavatar);
        @fclose($fp);

        $fp = @fopen($smallavatarfile, 'wb');
        @fwrite($fp, $smallavatar);
        @fclose($fp);

        // ?????
        $biginfo    = @getimagesize($bigavatarfile);
        $middleinfo = @getimagesize($middleavatarfile);
        $smallinfo  = @getimagesize($smallavatarfile);
        if ( !$biginfo || !$middleinfo || !$smallinfo || $biginfo[2] == 4 || $middleinfo[2] == 4 || $smallinfo[2] == 4 ) {
            file_exists($bigavatarfile) && unlink($bigavatarfile);
            file_exists($middleavatarfile) && unlink($middleavatarfile);
            file_exists($smallavatarfile) && unlink($smallavatarfile);
            $success = 0;
        }
        // ????
        $tmpPath = $this->getBasePath() . "data" . DIRECTORY_SEPARATOR . "{$uid}";
        @unlink($tmpPath);

        return '<?xml version="1.0" ?><root><face success="' . $success . '"/></root>';
    }

    // ?????? url
    public function getAvatarUrl( $uid, $size='middle' )
    {
        return $this->getBaseUrl() . "data/{$uid}_{$size}.jpg";
    }

    //  HTTP Request
    // ??? request?? true?? false
    public function processRequest()
    {
        //  input ?
        $arr = array();
        parse_str( $_GET['input'], $arr );
        $uid = intval($arr['uid']);

        if ( $_GET['a'] == 'uploadavatar') {

            // ???????
            echo $this->uploadAvatar( $uid );
            return true;

        } else if ( $_GET['a'] == 'rectavatar') {

            // ?????
            echo $this->rectAvatar( $uid );
            return true;
        }

        return false;
    }

    // ?? camera.swf  HTML
    public function renderHtml( $uid )
    {
        // ???? input
        $input = urlencode( "uid={$uid}" );

        $baseUrl = $this->getBaseUrl();
        $uc_api = urlencode( $this->getThisUrl() );
        $urlCameraFlash = "{$baseUrl}camera.swf?ucapi={$uc_api}&input={$input}";
        $urlCameraFlash = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="447" height="477" id="mycamera" align="middle">
                <param name="allowScriptAccess" value="always" />
                <param name="scale" value="exactfit" />
                <param name="wmode" value="transparent" />
                <param name="quality" value="high" />
                <param name="bgcolor" value="#ffffff" />
                <param name="movie" value="'.$urlCameraFlash.'" />
                <param name="menu" value="false" />
                <embed src="'.$urlCameraFlash.'" quality="high" bgcolor="#ffffff" width="447" height="477" name="mycamera" align="middle" allowScriptAccess="always" allowFullScreen="false" scale="exactfit"  wmode="transparent" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
            </object>';
        return $urlCameraFlash;
    }
}

header("Expires: 0");
header("Cache-Control: private, post-check=0, pre-check=0, max-age=0", FALSE);
header("Pragma: no-cache");
header("Cache-Control:no-cache");

$au = new AvatarUploader();
if ( $au->processRequest() ) {
    exit();
}

// ???? camera.swf
$uid = intval($_GET['uid']);
$urlAvatarBig    = $au->getAvatarUrl( $uid, 'big' );
$urlAvatarMiddle = $au->getAvatarUrl( $uid, 'middle' );
$urlAvatarSmall  = $au->getAvatarUrl( $uid, 'small' );
$urlCameraFlash = $au->renderHtml( $uid );
?>
<script type="text/javascript">
function updateavatar() {
    window.location.reload();
}
</script>
<img src="<?php echo $urlAvatarBig ?>">
<img src="<?php echo  $urlAvatarMiddle ?>">
<img src="<?php echo  $urlAvatarSmall ?>">
<hr>
<?php echo  $urlCameraFlash ?>
还有附件,我没传,如果大家需要这种效果可以联系 我qq
作者:AngryFox 分类: Uncategorized January 3rd, 2012 暂无评论
//本程序适用于迅雷、快车和QQ旋风专用链接加解密,其他的暂未支持。
<?php
/**
*专用链接加解密
* 本程序适用于迅雷、快车和QQ旋风专用链接加解密,其他的暂未支持。程序较简单,有PHP基础的一看就明白。
function encrypt($url = null, $type = "thunder"){
	$types = array("thunder", "flashget", "qqdl");
	$type = strtolower($type);
	$url = trim($url);
	if ($url == null) return null;
	if (false == array_search($type, $types)) $type = "thunder";

	switch ($type){
		case "thunder":
			$url = "thunder://" . base64_encode("AA".$url."ZZ");
			break;
		case "flashget":
			$url = "flashget://" . base64_encode("[FLASHGET]".$url."[FLASHGET]") . "&bao";
			break;
		case "qqdl":
			$url = "qqdl://" . base64_encode($url);
			break;
	}
	return $url;
}

function decrypt($url_origin = null){
	$url = trim($url_origin);
	if ($url == null) return null;
	$count = preg_match("/(\w+):\/\//i", $url, $matches);
	if($count == 0 || $count == false){
		return $url_origin;
	}else{
		$type = strtolower($matches[1]);
	}

	$count = preg_match("/:\/\/([a-zA-Z0-9+\/]+={0,2})/i", $url, $matches);
	if($count == 0 || $count == false){
		return $url_origin;
	}else{
		$url = $matches[1];
	}
	switch ($type){
		case "thunder":
			$url = base64_decode($url);
			$count = preg_match("/^AA(.+)ZZ$/i", $url, $matches);
			if($count == 0 || $count == false){
				return $url_origin;
			}else{
				$url = $matches[1];
			}
			break;
		case "flashget":
			$url = base64_decode($url);
			$count = preg_match("/\[FLASHGET\](.+)\[FLASHGET\]/i", $url, $matches);
			if($count == 0 || $count == false){
				return $url_origin;
			}else{
				$url = $matches[1];
			}
			break;
		case "qqdl":
			$url = base64_decode($url);
			break;
		default:
			return $url_origin;
	}
	return $url;
}
?>

<html>
<head>
<title>专用链接加解密</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
body{
	text-align:center;
	padding-top:50px;
}
#tb{
	background-color:green;
	margin:10px auto;
}
#result{
	text-align:left;
	width:60%;
	margin:10px auto;
}
</style>
</head>
<body>
	<div id="link">
		<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" >
			<table id="tb">
			<tr><td>链接</td><td colspan=2><textarea rows=3 name="url"></textarea></td></tr>
			<tr><td ><input type="radio" name="endecode" value="decode" id="decode" checked><label for="decode">解密</label></td><td><input type="radio" name="endecode" value="encode" id="encode"><label for="encode">加密</label></td><td></td></tr>
			<tr><td><input type="radio" name="type" value="thunder" checked>迅雷</td><td><input type="radio" name="type" value="flashget">快车</td><td><input type="radio" name="type" value="qqdl">QQ旋风</td></tr>
			<tr><td><input type="submit" name="submit" value="确定"></td><td><input type="reset" name="reset"></td><td></td></tr>
			</table>
		</form>
	</div>
	<div id = "result">
	<?php
	if(isset($_POST['endecode']) && isset($_POST['type']) && isset($_POST['url'])){
		$url = $_POST['url'];
		$type = $_POST['type'];
		$endecode = $_POST['endecode'];
		if($endecode == "decode"){
			$url2 = decrypt($url);
			echo "<p>解密前的地址: $url </p>";
			echo "<p>解密后的地址: $url2 </p>";
		}elseif($endecode == "encode"){
			$url2 = encrypt($url,$type);
			echo "<p>加密前的地址: $url </p>";
			echo "<p>加密后的地址: $url2 </p>";
		}
	}
	?>
	</div>
</body>
</html>