验证码这样的功能可以说是无处不在了、那使用php来实现验证码这样的功能呢?接下来我就将验证码实现封装到一个类里面独立出来、那么后面如果再使用到验证码功能。
直接引入该类文件并创建该类的实例、就可以使用验证码了,验证码类文件vcode.class.php代码如下
//验证码类
class Vcode{
private $width;//图片宽度
private $height;//图片高度
private $num;//验证码个数
private $img;//图片资源
private $code;//验证码
private $pointNum;//干扰点个数
private $lineNum;//干扰线个数
private $fontFile;//字体文件
//构造函数初始化相关数据
function __construct($width=85,$height=34,$num=4){
$this->width=$width;
$this->height=$height;
$this->num=$num;
$this->code=$this->createCode();
$this->pointNum=100;
$this->lineNum=10;
$this->fontFile="<a href="http://dwtedx.com/font/无"
target="_blank" class="keylink">STL</a>ITI.TTF";
}
//用于设置成员属性
//@param string $key 成员属性名
//@param mixed $value 成员属性值
//@return object 返回自己对象$this,可用于连贯操作
public function set($key,$val){
//get_class_vars() 获取类中的属性组成的数组
//get_class() 返回对象的类名
if(array_key_exists($key,get_class_vars(get_class($this)))){
$this->setOption($key,$val);
}
return $this;
}
//设置参数
private function setOption($key,$value){
$this->$key=$value;
}
//获取验证码
public function getCode(){
return $this->code;
}
//输出图像
public function outImg(){
//创建图像
$this->createImage();
//画验证码
$this->drawCode();
//画干扰元素
$this->drawDisturbColor();
//输出图像
$this->printImg();
}
//画验证码
private function drawCode(){
$this->fontFile="./font/".$this->fontFile;
for($i=0;$i<$this->num;$i++){
//设置随机颜色
$randColor=imagecolorallocate($this->img,rand(0,128)
,rand(0,128),rand(0,128));
//字体大小
$fontSize=rand(20,23);
//字体水平位置
$x=($this->width/$this->num)*$i;
//水平方向的位置
$y=rand($fontSize,imagefontheight($fontSize)+3);
//画字体
imagettftext($this->img,$fontSize,0,$x,$y,$randColor,
$this->fontFile,$this->code{$i});
}
}
//画干扰元素
private function drawDisturbColor(){
//画干扰点
for($i=0;$i<$this->pointNum;$i++){
//设置随机颜色
$randColor=imagecolorallocate($this->img,rand(0,255),
rand(0,255),rand(0,255));
//画点
imagesetpixel($this->img,rand(1,$this->width-2),rand(1,
$this->height-2),$randColor);
}
//画干扰线
for($i=0;$i<$this->lineNum;$i++){
//设置随机颜色
$randColor=imagecolorallocate($this->img,rand(0,200),
rand(0,200),rand(0,200));
//画线
imageline($this->img,rand(1,$this->width-2),rand(1,
$this->height-2),rand(1,$this->height-2),
rand(1,$this->width-2),$randColor);
}
}
//创建图像
private function createImage(){
//创建一个真彩色图像
$this->img=imagecreatetruecolor($this->width,$this->height);
//设置背景色
$bgColor=imagecolorallocate($this->img,rand(200,255),
rand(200,255),rand(200,255));
//填充背景色
imagefill($this->img,0,0,$bgColor);
//设置边框颜色
$borderColor=imagecolorallocate($this->img,0,0,0);
//画一个边框
imagerectangle($this->img,0,0,$this->width-1,
$this->height-1,$borderColor);
}
//输出图像
private function printImg(){
if(imagetypes() & IMG_PNG){
//针对png
header("Content-Type:image/png");
imagepng($this->img);
}else if(imagetypes() & IMG_JPG){
//针对jpg
header("Content-Type:image/jpeg");
imagejpeg($this->img,null,100);
}else if(imagetypes() & IMG_GIF){
//针对Gif
header("Content-Type:image/gif");
imagegif($this->img);
}else if(imagetypes() & IMG_WBMP){
// 针对 WBMP
header(′Content-Type: image/vnd.wap.wbmp′);
imagewbmp($this->img);
}else{
die(′No image support in this PHP server′);
}
}
//创建验证码
private function createCode(){
//默认字符串
$codes="123456789abcdefghijkmnpqrstuvwxyABCDEFGHIJKLMNOPQRSTUVWXY";
//生成验证码
$code="";
for($i=0;$i<$this->num;$i++){
$code.=$codes{rand(0,strlen($codes)-1)};
}
return $code;
}
//析构函数用于销毁图像资源
function __destruct(){
imagedestroy($this->img);
}
}
这里我使用的画字体的函数是imagettftext()、因为这个函数可以自定义字体样式、从代码中也能看出来
传入的参数有个字体文件属性、如果不喜欢用这个函数可以使用imagestring()函数也行
只不过个人觉得这个函数的默认字体大小、也不好看、还是自定义字体看着舒服点
调用验证码类image_002.php代码如下
//开启Sessionsession_start();//引入验证码类include("vcode.class.php");//创建验证码类$vcode=new Vcode();//将获取的验证码存入到session中$_SESSION[′code′]=$vcode->getCode();//$vcode->set("pointNum",10);//自定义干扰点个数//$vcode->set("lineNum",10);//自定义干扰线个数//$vcode->set("fontFile","wawa.ttf");//自定义字体文件//输出图像$vcode->outImg();
HTML代码如下
<img src="image_002.php" onclick="this.src=′image_002.php?Math.random()′"/>
到这里整个功能就做完了、希望对一些哥们有用、同时也当自己做个笔记
我们建站的时候,开始是每次请求数据库都要重新连接的、这样显然不合理、然后自己封装了一个数据库操作类、DBTools.php、要解决一个连接多次使用的话、最好的办法是使用长连接、但是新浪的数据库用不了长连接、那么就只能换一种方式了、这里我使用的是”单例模式“
为什么要使用PHP单例模式?
1、php的应用主要在于数据库应用、所以一个应用中会存在大量的数据库操作、使用单例模式、则可以避免大量的new 操作消耗的资源
2、如果系统中需要有一个类来全局控制某些配置信息、那么使用单例模式可以很方便的实现. 这个可以参看ZF的FrontController部分
3、在一次页面请求中、便于进行调试、因为所有的代码(例如数据库操作类db)都集中在一个类中、我们可以在类中设置钩子、输出日志、从而避免到处var_dump、echo
单例类
1、构造函数需要标记为private(访问控制:防止外部代码使用new操作符创建对象)、单例类不能在其他类中实例化、只能被其自身实例化
2、拥有一个保存类的实例的静态成员变量
3、拥有一个访问这个实例的公共的静态方法(常用getInstance()方法进行实例化单例类、通过instanceof操作符可以检测到类是否已经被实例化)
4、另外、需要创建__clone()方法防止对象被复制(克隆)
单例实现方法
单例类Demo源代码
/**
* $_instance必须声明为静态的私有变量
* 构造函数和析构函数必须声明为私有,防止外部程序new
* 类从而失去单例模式的意义
* getInstance()方法必须设置为公有的,必须调用此方法
* 以返回实例的一个引用
* ::操作符只能访问静态变量和静态函数
* new对象都会消耗内存
* 使用场景:最常用的地方是数据库连接。
* 使用单例模式生成一个对象后,
* 该对象可以被其它众多对象所使用。
*/class InstanceDemo {
//保存类实例的静态成员变量
private static $_instance;
//private标记的构造方法
private function __construct(){
echo ′This is a Constructed method;′;
}
//创建__clone方法防止对象被复制克隆
public function __clone(){
trigger_error(′Clone is not allow!′,E_USER_ERROR);
}
//单例方法,用于访问实例的公共的静态方法
public static function getInstance(){
if(!(self::$_instance instanceof self)){
self::$_instance = new self;
}
return self::$_instance;
}
public function test(){
echo ′调用方法成功′;
}
}
调用方法
//正确方法,用双冒号::操作符访问静态方法获取实例$demo = InstanceDemo ::getInstance();$demo->test();
简单的说、一个对象(在学习设计模式之前、需要比较了解面向对象思想)只负责一个特定的任务、在网上看了一些资料、单例模式比较好理解、看看介绍、然后看看代码基本也就能够理解了、设计模式这些的花点心思基本的是能够理解的、不管是Java还C#、或者是PHP设计模式基本上都是通用的,以上代码、这样就完成了一个简单的单例类了、希望对大家有用。
由于现在很多网站是采用响应式布局的、难免会遇到需要判断是手机用户还是电脑用户,那么在手机访问的时候如果要显示百度广告、体验会很差、所有为响应式做的努力都白费了、下面我们找到判断为手机用户php代码分享给大家。
方法一
<?php
function isMobile(){
$useragent=isset($_SERVER[′HTTP_USER_AGENT′]) ?
$_SERVER[′HTTP_USER_AGENT′] : ′′;
$useragent_commentsblock=preg_match(′|(.*?)|
′,$useragent,$matches)>0?$matches[0]:′′;
function CheckSubstrs($substrs,$text){
foreach($substrs as $substr)
if(false!==strpos($text,$substr)){
return true;
}
return false;
}
$mobile_os_list=array(′Google Wireless Transcoder′,′Windows CE′,
′WindowsCE′,′Symbian′,′Android′,′armv6l′,′armv5′,′Mobile′,
′CentOS′,′mowser′,′AvantGo′,′Opera Mobi′,′J2ME/MIDP′,
′Smartphone′,′Go.Web′,′Palm′,′iPAQ′);
$mobile_token_list=array(′Profile/MIDP′,′Configuration/CLDC-′,
′160×160′,′176×220′,′240×240′,′240×320′,′320×240′,′UP.Browser′,
′UP.Link′,′SymbianOS′,′PalmOS′,′PocketPC′,′SonyEricsson′,
′Nokia′,′BlackBerry′,′Vodafone′,′BenQ′,′Novarra-Vision′,
′Iris′,′NetFront′,′HTC_′,′Xda_′,′SAMSUNG-SGH′,′Wapaka′,
′DoCoMo′,′iPhone′,′iPod′);
$found_mobile=CheckSubstrs($mobile_os_list,$useragent_commentsblock) ||
CheckSubstrs($mobile_token_list,$useragent);
if ($found_mobile){
return true;
}else{
return false;
} } if (isMobile())
echo ′手机访问 DD博客′; else
echo ′电脑访问 DD博客′; ?>
方法二
function is_mobile_request() {
$_SERVER[′ALL_HTTP′] = isset($_SERVER[′ALL_HTTP′])
? $_SERVER[′ALL_HTTP′] : ′′;
$mobile_browser = ′0′;
if(preg_match(′/(up.browser|up.link|mmp|symbian|smartphone|
midp|wap|phone|iphone|ipad|ipod|android|xoom)/i′,
strtolower($_SERVER[′HTTP_USER_AGENT′])))
$mobile_browser ;
if((isset($_SERVER[′HTTP_ACCEPT′])) and (strpos(strtolower(
$_SERVER[′HTTP_ACCEPT′]),′application/vnd.wap.xhtml xml′) !== false))
$mobile_browser ;
if(isset($_SERVER[′HTTP_X_WAP_PROFILE′]))
$mobile_browser ;
if(isset($_SERVER[′HTTP_PROFILE′]))
$mobile_browser ;
$mobile_ua = strtolower(substr($_SERVER[′HTTP_USER_AGENT′],0,4));
$mobile_agents = array(
′w3c ′,′acs-′,′alav′,′alca′,′amoi′,′audi′,′avan′,′benq′,′bird′,′blac′,
′blaz′,′brew′,′cell′,′cldc′,′cmd-′,′dang′,′doco′,′eric′,′hipt′,′inno′,
′ipaq′,′java′,′jigs′,′kddi′,′keji′,′leno′,′lg-c′,′lg-d′,′lg-g′,′lge-′,
′maui′,′maxo′,′midp′,′mits′,′mmef′,′mobi′,′mot-′,′moto′,′mwbp′,′nec-′,
′newt′,′noki′,′oper′,′palm′,′pana′,′pant′,′phil′,′play′,′port′,′prox′,
′qwap′,′sage′,′sams′,′sany′,′sch-′,′sec-′,′send′,′seri′,′sgh-′,′shar′,
′sie-′,′siem′,′smal′,′smar′,′sony′,′sph-′,′symb′,′t-mo′,′teli′,′tim-′,
′tosh′,′tsm-′,′upg1′,′upsi′,′vk-v′,′voda′,′wap-′,′wapa′,′wapi′,′wapp′,
′wapr′,′webc′,′winw′,′winw′,′xda′,′xda-′
);
if(in_array($mobile_ua, $mobile_agents))
$mobile_browser ;
if(strpos(strtolower($_SERVER[′ALL_HTTP′]), ′operamini′) !== false)
$mobile_browser ;
// Pre-final check to reset everything if the user is on Windows
if(strpos(strtolower($_SERVER[′HTTP_USER_AGENT′]), ′windows′) !== false)
$mobile_browser=0;
// But WP7 is also Windows, with a slightly different characteristic
if(strpos(strtolower($_SERVER[′HTTP_USER_AGENT′]), ′windows phone′) !== false)
$mobile_browser ;
if($mobile_browser>0)
return true;
else
return false;}
这两种方法我都亲测过、没有问题的、希望对大家有用