PHP购物车类

 <?
// 购物车类 

/*
使用说明:
构造函数 cart 可以使用参数:
cart($cartname = 'myCart', $session_id = '', $savetype = 'session', $cookietime = 86400, $cookiepath = '/', $cookiedomain = '')
$cartname 是购物车的标识,可以指定,可以保证不重名,不会有相关冲突
$session_id 是 session_id,默认是使用 cookie 来传输,也可以自定义,如果存储类型是 session 才起效
$savetype 存储类型,有 session 和 cookie 方式
... 其他是 cookie 需要的参数

如果程序本身也需要使用 session,建议购物车使用 cookie 存储




添加一个商品
============================================================
// 引用类
require_once './cart.class.php';
// 建立类实例
$cart = new cart();

// 商品已经存在 修改数据
if ($cart->data[$id]) {
$cart->data[$id]['count'] += $count;
$cart->data[$id]['money'] += $cart->data[$id]['price'] * $count;
// 添加商品
} else {
$cart->data[$id]['name'] = $name;
$cart->data[$id]['price'] = $price;
$cart->data[$id]['count'] = $count;
$cart->data[$id]['money'] = $price * $count;
}
// 保存购物车数据
$cart->save();
============================================================



编辑一个商品数量
============================================================
// 引用类
require_once './cart.class.php';
// 建立类实例
$cart = new cart();

// 商品已经存在 修改数据
if ($cart->data[$id]) {
$cart->data[$id]['count'] = $count;
$cart->data[$id]['money'] = $cart->data[$id]['price'] * $count;

// 保存购物车数据
$cart->save();
}
============================================================



删除一个商品
============================================================
// 引用类
require_once './cart.class.php';
// 建立类实例
$cart = new cart();

// 删除商品
unset($cart->data[$id]);

// 保存购物车数据
$cart->save();
============================================================



列表购物车
============================================================
// 引用类
require_once './cart.class.php';
// 建立类实例
$cart = new cart();

foreach ($cart->data AS $k => $v) {
echo '商品 ID: '.$k;
echo '商品名称: '.$v['name'];
echo '商品单价: '.$v['price'];
echo '商品数量: '.$v['count'];
echo '商品总价: '.$v['money'];
}
============================================================



某字段总累计 --- 如所有商品总价格
============================================================
// 引用类
require_once './cart.class.php';
// 建立类实例
$cart = new cart();

// 累计 money 字段
$cart->sum('money')
============================================================



清空购物车
============================================================
// 引用类
require_once './cart.class.php';
// 建立类实例
$cart = new cart();

// 清除数据
unset($cart->data);

// 保存购物车数据
$cart->save();
============================================================
*/


class cart {

// 购物车标识
var $cartname = '';
// 存储类型
var $savetype = '';
// 购物车中商品数据
var $data = array();
// Cookie 数据
var $cookietime = 0;
var $cookiepath = '/';
var $cookiedomain = '';

// 构造函数 (购物车标识, $session_id, 存储类型(session或cookie), 默认是一天时间, $cookiepath, $cookiedomain)
function cart($cartname = 'myCart', $session_id = '', $savetype = 'session', $cookietime = 86400, $cookiepath = '/', $cookiedomain = '') {

// 采用 session 存储
if ($savetype == 'session') {

if (!$session_id && $_COOKIE[$cartname.'_session_id']) {
session_id($_COOKIE[$cartname.'_session_id']);
} elseif($session_id)
session_id($session_id);

session_start();

if (!$session_id && !$_COOKIE[$cartname.'_session_id'])
setcookie($cartname.'_session_id', session_id(), $cookietime + time(), $cookiepath, $cookiedomain);
}

$this->cartname = $cartname;
$this->savetype = $savetype;
$this->cookietime = $cookietime;
$this->cookiepath = $cookiepath;
$this->cookiedomain = $cookiedomain;
$this->readdata();
}

// 读取数据
function readdata() {
if ($this->savetype == 'session') {
if ($_SESSION[$this->cartname] && is_array($_SESSION[$this->cartname]))
$this->data = $_SESSION[$this->cartname];
else 
$this->data = array();
} elseif ($this->savetype == 'cookie') {
if ($_COOKIE[$this->cartname])
$this->data = unserialize($_COOKIE[$this->cartname]);
else 
$this->data = array();
}

}

// 保存购物车数据
function save() {
if ($this->savetype == 'session') {
$_SESSION[$this->cartname] = $this->data;
} elseif ($this->savetype == 'cookie') {
if ($this->data)
setcookie($this->cartname, serialize($this->data), $this->cookietime + time(), $this->cookiepath, $this->cookiedomain);
}
}

// 返回商品某字段累加
function sum($field) {

$sum = 0;
if ($this->data)
foreach ($this->data AS $v)
if ($v[$field])
$sum += $v[$field] + 0;

return $sum;
}

}
?>

标签: php, , 购物车

php的简单模板类

 

<?php

 

/*

 * 简单替换模板类

 * 

 * 

 */

 

class QuickTpl

{

var $filename; //模板文件

var $content; //返回内容

 

//初始化模板文件,将所有内容读入

function quicktpl($tplfilename) {

$this->filename=$tplfilename;

$fd = fopen( $this->filename, "r" );

$this->content = fread($fd, filesize($this->filename));

fclose( $fd );

}

 

//替换标志位内容

function Assign($key,$value){

$this->content=str_replace("{".$key."}",$value,$this->content);

}

 

//替换标志块内容

function BlockAssign($block_name,$values){ 

//获得替换块的子模板

if(is_array($values)){ 

ereg("{".$block_name."}.*{/".$block_name."}",$this->content,$regs);

$str_block=substr($regs[0],2+strlen($block_name),-(strlen($block_name)+3));

$str_replace="";

$block_replace="";

foreach($values as $subarr){

$str_replace=$str_block;

while ( list( $key, $val ) = each( $subarr ) ){

$str_replace=str_replace("{".$key."}",$val,$str_replace);

}

$block_replace.=$str_replace;

}

$this->content=ereg_replace ("{".$block_name."}.*{/".$block_name."}",$block_replace,$this->content);

}

else{

$this->content=ereg_replace ("{".$block_name."}.*{/".$block_name."}","none",$this->content);

}

}

 

//输出模板内容

function Show(){

echo $this->content;

}

}

 

?>


以下是一个演示用的模板文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>{title}</title>
<link href="{cssfile}" rel="stylesheet" type="text/css" />
<meta http-equiv='Cache-Control' content='max-age=0'/>
<meta http-equiv='Cache-Control' content='no-cache' forua='true'/>
</head>
<body bgcolor="{bgcolor}">
<table width="100%" border="0" cellpadding="0" cellspacing="0">
  <tr width="100%"> 
    <td align="center">
     <img src="{top_logo}" />
    </td>
  </tr>
  <tr width="100%"> 
    <td align="center">
     {content}
    </td>
  </tr>
  <tr width="100%"> 
    <td align="center">
     <select name="select">
{select}
      <option value="{value}">{name}</option>
{/select}
     </select>
    </td>
  </tr>
  <tr width="100%"> 
    <td align="center">
     <img src="{bottom_img}" />
    </td>
  </tr>
</table>
{bottom}
</body>
</html>

以下是对模板调用的演示
<?php
   $qt=new QuickTpl("template/pic_view.tpl");
   $qt->Assign("title","标题");  //替换{title}
   $qt->Assign("cssfile","style.css");  //替换{cssfile}
   $qt->Assign("bgcolor","#EEEEEE");  //替换{bgcolor}
   $qt->Assign("top_logo","logo.gif");  //替换{top_logo}
   $select[]=array("name"=>"test1","value"=>"1");
   $select[]=array("name"=>"test2","value"=>"2");
   $select[]=array("name"=>"test3","value"=>"3");
   $qt->BlockAssign("select",$select);
   $qt->Assign("content","大家Hello~啊!");
   $qt->Assign("bottom_img","bottom.gif");   //替换{bottom_img}
   $qt->ASsign("bottom","copyright ..."); //替换{bottom}
   $qt->Show();  //显示替换后的模板
?>

标签: php, , 模板

javascript代码整理(多且精)

一、验证类
1、数字验证内
  1.1 整数
      /^(-|\+)?\d+$/.test(str)
  1.2 大于0的整数 (用于传来的ID的验证)
      /^\d+$/.test(str)
  1.3 负整数的验证
      /^-\d+$/.test(str)
2、时间类
  2.1 短时间,形如 (13:04:06)
      function isTime(str)
      {
        var a = str.match(/^(\d{1,2})(:)?(\d{1,2})\2(\d{1,2})$/);
        if (a == null) {alert('输入的参数不是时间格式'); return false;}
        if (a[1]>24 || a[3]>60 || a[4]>60)
        {
          alert("时间格式不对");
          return false
        }
        return true;
      }
  2.2 短日期,形如 (2003-12-05)
      function strDateTime(str)
      {
         var r = str.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
         if(r==null)return false;
         var d= new Date(r[1], r[3]-1, r[4]);
         return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]);
      }
  2.3 长时间,形如 (2003-12-05 13:04:06)
      function strDateTime(str)
      {
        var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
        var r = str.match(reg);
        if(r==null)return false;
        var d= new Date(r[1], r[3]-1,r[4],r[5],r[6],r[7]);
        return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]&&d.getHours()==r[5]&&d.getMinutes()==r[6]&&d.getSeconds()==r[7]);
      }
  2.4 只有年和月。形如(2003-05,或者2003-5)
  2.5 只有小时和分钟,形如(12:03)
3、表单类
  3.1 所有的表单的值都不能为空
      <input onblur="if(this.value.replace(/^\s+|\s+$/g,'')=='')alert('不能为空!')">
  3.2 多行文本框的值不能为空。
  3.3 多行文本框的值不能超过sMaxStrleng
  3.4 多行文本框的值不能少于sMixStrleng
  3.5 判断单选框是否选择。
  3.6 判断复选框是否选择.
  3.7 复选框的全选,多选,全不选,反选
  3.8 文件上传过程中判断文件类型
4、字符类
  4.1 判断字符全部由a-Z或者是A-Z的字字母组成
      <input onblur="if(/[^a-zA-Z]/g.test(this.value))alert('有错')">
  4.2 判断字符由字母和数字组成。
      <input onblur="if(/[^0-9a-zA-Z]/g.test(this.value))alert('有错')">
  4.3 判断字符由字母和数字,下划线,点号组成.且开头的只能是下划线和字母
      /^([a-zA-z_]{1})([\w]*)$/g.test(str)
  4.4 字符串替换函数.Replace();
5、浏览器类
  5.1 判断浏览器的类型
      window.navigator.appName
  5.2 判断ie的版本
      window.navigator.appVersion
  5.3 判断客户端的分辨率
      window.screen.height;  window.screen.width;
 
6、结合类
  6.1 email的判断。
      function ismail(mail)
      {
        return(new RegExp(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/).test(mail));
      }
  6.2 手机号码的验证
  6.3 身份证的验证
      function isIdCardNo(num)
      {
        if (isNaN(num)) {alert("输入的不是数字!"); return false;}
        var len = num.length, re;
        if (len == 15)
          re = new RegExp(/^(\d{6})()?(\d{2})(\d{2})(\d{2})(\d{3})$/);
        else if (len == 18)
          re = new RegExp(/^(\d{6})()?(\d{4})(\d{2})(\d{2})(\d{3})(\d)$/);
        else {alert("输入的数字位数不对!"); return false;}
        var a = num.match(re);
        if (a != null)
        {
          if (len==15)
          {
            var D = new Date("19"+a[3]+"/"+a[4]+"/"+a[5]);
            var B = D.getYear()==a[3]&&(D.getMonth()+1)==a[4]&&D.getDate()==a[5];
          }
          else
          {
            var D = new Date(a[3]+"/"+a[4]+"/"+a[5]);
            var B = D.getFullYear()==a[3]&&(D.getMonth()+1)==a[4]&&D.getDate()==a[5];
          }
          if (!B) {alert("输入的身份证号 "+ a[0] +" 里出生日期不对!"); return false;}
        }
        return true;
      }

画图:
<OBJECT
id=S
style="LEFT: 0px; WIDTH: 392px; TOP: 0px; HEIGHT: 240px"
height=240
width=392
classid="clsid:369303C2-D7AC-11D0-89D5-00A0C90833E6">
</OBJECT>
<SCRIPT>
S.DrawingSurface.ArcDegrees(0,0,0,30,50,60);
S.DrawingSurface.ArcRadians(30,0,0,30,50,60);
S.DrawingSurface.Line(10,10,100,100);
</SCRIPT>

写注册表:
<SCRIPT>
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.RegWrite ("HKCU\\Software\\ACME\\FortuneTeller\\", 1, "REG_BINARY");
WshShell.RegWrite ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader", "Goocher!", "REG_SZ");
var bKey =    WshShell.RegRead ("HKCU\\Software\\ACME\\FortuneTeller\\");
WScript.Echo (WshShell.RegRead ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader"));
WshShell.RegDelete ("HKCU\\Software\\ACME\\FortuneTeller\\MindReader");
WshShell.RegDelete ("HKCU\\Software\\ACME\\FortuneTeller\\");
WshShell.RegDelete ("HKCU\\Software\\ACME\\");
</SCRIPT>

 

 

TABLAE相关(客户端动态增加行列)
<HTML>
<SCRIPT LANGUAGE="JScript">
function numberCells() {
    var count=0;
    for (i=0; i < document.all.mytable.rows.length; i++) {
        for (j=0; j < document.all.mytable.rows(i).cells.length; j++) {
            document.all.mytable.rows(i).cells(j).innerText = count;
            count++;
        }
    }
}
</SCRIPT>
<BODY onload="numberCells()">
<TABLE id=mytable border=1>
<TR><TH>&nbsp;</TH><TH>&nbsp;</TH><TH>&nbsp;</TH><TH>&nbsp;</TH></TR>
<TR><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD></TR>
<TR><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD><TD>&nbsp;</TD></TR>
</TABLE>
</BODY>
</HTML>

 

//打开模式对话框
function doSelectUser(txtId)
{

      strFeatures="dialogWidth=500px;dialogHeight=360px;center=yes;middle=yes ;help=no;status=no;scroll=no";
      var url,strReturn;
 
      url="selUser.aspx";
       
      strReturn=window.showModalDialog(url,'',strFeatures);  

}

 

//返回模式对话框的值
function okbtn_onclick()
{
var commstr='';         
     
window.returnValue=commstr;

      window.close() ;
}


全屏幕打开IE 窗口
var winWidth=screen.availWidth ;
var winHeight=screen.availHeight-20;
window.open("main.aspx","surveyWindow","toolbar=no,width="+ winWidth  +",height="+ winHeight  +",top=0,left=0,scrollbars=yes,resizable=yes,center:yes,statusbars=yes");
break
//脚本中中使用xml
function initialize() {
  var xmlDoc
  var xslDoc

  xmlDoc = new ActiveXObject('Microsoft.XMLDOM')
  xmlDoc.async = false;

  xslDoc = new ActiveXObject('Microsoft.XMLDOM')
  xslDoc.async = false;

 xmlDoc.load("tree.xml")
  xslDoc.load("tree.xsl")
 
 
  folderTree.innerHTML = xmlDoc.documentElement.transformNode(xslDoc)
}

 

 

贴两个关于treeview的 
  <script language="javascript">
<!--
//初始化选中节点
function initchecknode()
{
 var node=TreeView1.getTreeNode("1");
 node.setAttribute("Checked","true");
 setcheck(node,"true");
 FindCheckedFromNode(TreeView1);
}
//oncheck事件
function tree_oncheck(tree)
{
 var node=tree.getTreeNode(tree.clickedNodeIndex);
 var Pchecked=tree.getTreeNode(tree.clickedNodeIndex).getAttribute("checked");
 setcheck(node,Pchecked);
 document.all.checked.value="";
 document.all.unchecked.value="";
 FindCheckedFromNode(TreeView1);
}
//设置子节点选中
function setcheck(node,Pc)
{
 var i;
 var ChildNode=new Array();
 ChildNode=node.getChildren();
 
 if(parseInt(ChildNode.length)==0)
  return;
 else
 {
  for(i=0;i<ChildNode.length;i++)
  {
   var cNode;
   cNode=ChildNode[i];
   if(parseInt(cNode.getChildren().length)!=0)
    setcheck(cNode,Pc);
   cNode.setAttribute("Checked",Pc);
  }
 }
}
//获取所有节点状态
function FindCheckedFromNode(node) {
 var i = 0;
 var nodes = new Array();
 nodes = node.getChildren();
 
 for (i = 0; i < nodes.length; i++) {
  var cNode;
  cNode=nodes[i];
  if (cNode.getAttribute("Checked"))
   AddChecked(cNode);
  else
      AddUnChecked(cNode);
 
  if (parseInt(cNode.getChildren().length) != 0 ) {
   FindCheckedFromNode(cNode);
  }
 }
}
//添加选中节点
function AddChecked(node) {
 document.all.checked.value += node.getAttribute("NodeData");
 document.all.checked.value += ',';
}
//添加未选中节点
function AddUnChecked(node) {
 document.all.unchecked.value += node.getAttribute("NodeData");
 document.all.unchecked.value += ',';
}
//-->
  </script>

 

/********************
函数名称:IsNumber
函数功能:检测字符串是否全为数字
函数参数:str,需要检测的字符串
********************/
function IsNumber(str)
{
var number_chars = "1234567890";
var i;
for (i=0;i<str.length;i++)
{
if (number_chars.indexOf(str.charAt(i))==-1) return false;
}
return true;
}

/********************
函数名称:Trim
函数功能:去除字符串两边的空格
函数参数:str,需要处理的字符串
********************/
function Trim(str)
{
return str.replace(/(^\s*)|(\s*$)/g, "");
}

/********************
函数名称:LTrim
函数功能:去除左边的空格
函数参数:str,需要处理的字符串
********************/
function LTrim(str)
{
return str.replace(/(^\s*)/g, "");
}

/********************
函数名称:RTrim
函数功能:去除右边的空格
函数参数:str,需要处理的字符串
********************/
function RTrim(str)
{
 return this.replace(/(\s*$)/g, "");
}

/********************
函数名称:IsNull
函数功能:判断给定字符串是否为空
函数参数:str,需要处理的字符串
********************/
function IsNull(str)
{
if(Trim(str)=="")
{
return false;
}
else
{
return true;
}
}

 


/********************************************************************
**
*函数功能:判断输入的字符串是否为合法的时间*
*输入参数:输入的字符串*
*返回值:true-合法的时间/false-非法的时间*
*调用函数:*
**
********************************************************************/
function checkDate(strDate)
{
var strDateArray;
var strDay;
var strMonth;
var strYear;
var intday;
var intMonth;
var intYear;
var strSeparator = "-";
var err = 0;

strDateArray = strDate.split(strSeparator);

if (strDateArray.length != 3)
{
err = 1;
return false;
}
else
{
strYear = strDateArray[0];
strMonth = strDateArray[1];
strDay = strDateArray[2];
}

intday = parseInt(strDay, 10);
if (isNaN(intday))
{
err = 2;
return false;
}
intMonth = parseInt(strMonth, 10);
if (isNaN(intMonth))
{
        err = 3;
return false;
}
intYear = parseInt(strYear, 10);
if(strYear.length != 4)
{
return false;
}
if (isNaN(intYear))
{
err = 4;
return false;
}


if (intMonth>12 || intMonth<1)
{
err = 5;
return false;
}

if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1))
{
err = 6;
return false;
}

if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1))
{
err = 7;
return false;
}

if (intMonth == 2)
{
if (intday < 1)
{
err = 8;
return false;
}

if (LeapYear(intYear) == true)
{
if (intday > 29)
{
err = 9;
return false;
}
}
else
{
if (intday > 28)
{
err = 10;
return false;
}
}
}

return true;
}

 

 


自动显示TXT文本的内容
把如下代码加入<body>区域中
 <script language=vbscript>
Function bytes2BSTR(vIn)
    strReturn = ""
    For i = 1 To LenB(vIn)
        ThisCharCode = AscB(MidB(vIn,i,1))
        If ThisCharCode < &H80 Then
            strReturn = strReturn & Chr(ThisCharCode)
        Else
            NextCharCode = AscB(MidB(vIn,i+1,1))
            strReturn = strReturn & Chr(CLng(ThisCharCode) * &H100 + CInt(NextCharCode))
            i = i + 1
        End If
    Next
    bytes2BSTR = strReturn
End Function
</script>
<script language="JavaScript">
var xmlUrl = new ActiveXObject('Microsoft.XMLHTTP');
xmlUrl.Open('GET','1.txt');
xmlUrl.Send();
setTimeout('alert(bytes2BSTR(xmlUrl.ResponseBody))',2000);
</script>

 

/********************
函数名称:CookieEnabled
函数功能:判断cookie是否开启
********************/
function CookieEnabled()
{
return (navigator.cookieEnabled)? true : false;
}

/********************
函数名称:PopWindow
函数功能:弹出新窗口
函数参数:pageUrl,新窗口地址;WinWidth,窗口的宽;WinHeight,窗口的高
********************/
function PopWindow(pageUrl,WinWidth,WinHeight)
{
var popwin=window.open(pageUrl,"PopWin","scrollbars=yes,toolbar=no,location=no,directories=no,status=no,menubar=no,resizable=no,width="+WinWidth+",height="+WinHeight);
return false;
}

 


/********************
函数名称:StrLenthByByte
函数功能:计算字符串的字节长度,即英文算一个,中文算两个字节
函数参数:str,为需要计算长度的字符串
********************/
function StrLenthByByte(str)
{
var len;
var i;
len = 0;
for (i=0;i<str.length;i++)
{
if (str.charCodeAt(i)>255) len+=2; else len++;
}
return len;
}

 

 

* JS 中,一些东西不可用的三种展现方式。
我们在WEB项目中,有时候需要在用户点击某个东西的时候,一些东西不可用。如果在客户端实现。最简单的就是利用disabled 。下面罗列的其中三种方式:依次是:不可用(disabled);用一个空白来代替这个地方(Blank);这个区域为空(None)。具体可以查看这个Blog的源文件:
obj.disabled = false;

obj.style.visibility = "hidden";

obj.style.display = "none";


<SCRIPT language=javascript>
function ShowDisableObject(obj)
{
 if(obj.disabled == false)
 {
  obj.disabled = true;
 }
 else{
  obj.disabled = false;
 }
 var coll = obj.all.tags("INPUT");
 if (coll!=null)
 {
  for (var i=0; i<coll.length; i++)
  {
   coll[i].disabled = obj.disabled;
  }
 }
}

function ShowBlankObject(obj)
{
 if(obj.style.visibility == "hidden")
 {
  obj.style.visibility = "visible";
 }
 else
 {
  obj.style.visibility = "hidden";
 }
}

function ShowNoneObject(obj)
{
 if(obj.style.display == "none")
 {
  obj.style.display = "block";
 }
 else
 {
  obj.style.display = "none";
 }
}

</SCRIPT>

 

三個實用的小技巧:關閉輸入法.禁止貼上.禁止複製

 

 

關閉輸入法

本文字框輸入法被關閉: 
語法: style="ime-mode:disabled"
範例:<input type="text" name="textfield" style="ime-mode:disabled">

禁止貼上

本文字框禁止貼上文字: 
語法:onpaste="return false"
範例:<input type="text" name="textfield" onpaste="return false">

禁止複製

本文字框禁止複製: 
語法:oncopy="return false;" oncut="return false;"
範例:<input name="textfield" type="text" value="不能複製裡面的字" oncopy="return false;" oncut="return false;">

 

 

PHP 生成缩略图的类

PHP代码

<?php   
  
/**  
* 功能:生成缩略图  
* 作者:phpox  
* 日期:Thu May 17 09:57:05 CST 2007  
*/  
  
class CreatMiniature   
{   
    //公共变量   
    var $srcFile="";        //原图   
    var $echoType;            //输出图片类型,link--不保存为文件;file--保存为文件   
    var $im="";                //临时变量   
    var $srcW="";            //原图宽   
    var $srcH="";            //原图高   
  
    //设置变量及初始化   
    function SetVar($srcFile,$echoType)   
    {   
        if (!file_exists($srcFile)){   
            echo '源图片文件不存在!';   
            exit();   
        }   
        $this->srcFile=$srcFile;   
        $this->echoType=$echoType;   
  
        $info = "";   
        $data = GetImageSize($this->srcFile,$info);   
        switch ($data[2])    
        {   
         case 1:   
           if(!function_exists("imagecreatefromgif")){   
            echo "你的GD库不能使用GIF格式的图片,请使用Jpeg或PNG格式!<a href='javascript:go(-1);'>返回</a>";   
            exit();   
           }   
           $this->im = ImageCreateFromGIF($this->srcFile);   
           break;   
        case 2:   
          if(!function_exists("imagecreatefromjpeg")){   
           echo "你的GD库不能使用jpeg格式的图片,请使用其它格式的图片!<a href='javascript:go(-1);'>返回</a>";   
           exit();   
          }   
          $this->im = ImageCreateFromJpeg($this->srcFile);       
          break;   
        case 3:   
          $this->im = ImageCreateFromPNG($this->srcFile);       
          break;   
      }   
      $this->srcW=ImageSX($this->im);   
      $this->srcH=ImageSY($this->im);    
    }   
       
    //生成扭曲型缩图   
    function Distortion($toFile,$toW,$toH)   
    {   
        $cImg=$this->CreatImage($this->im,$toW,$toH,0,0,0,0,$this->srcW,$this->srcH);   
        return $this->EchoImage($cImg,$toFile);   
        ImageDestroy($cImg);   
    }   
       
    //生成按比例缩放的缩图   
    function Prorate($toFile,$toW,$toH)   
    {   
        $toWH=$toW/$toH;   
        $srcWH=$this->srcW/$this->srcH;   
        if($toWH<=$srcWH)   
        {   
            $ftoW=$toW;   
            $ftoH=$ftoW*($this->srcH/$this->srcW);   
        }   
        else  
        {   
              $ftoH=$toH;   
              $ftoW=$ftoH*($this->srcW/$this->srcH);   
        }   
        if($this->srcW>$toW||$this->srcH>$toH)   
        {   
            $cImg=$this->CreatImage($this->im,$ftoW,$ftoH,0,0,0,0,$this->srcW,$this->srcH);   
            return $this->EchoImage($cImg,$toFile);   
            ImageDestroy($cImg);   
        }   
        else  
        {   
            $cImg=$this->CreatImage($this->im,$this->srcW,$this->srcH,0,0,0,0,$this->srcW,$this->srcH);   
            return $this->EchoImage($cImg,$toFile);   
            ImageDestroy($cImg);   
        }   
    }   
       
    //生成最小裁剪后的缩图   
    function Cut($toFile,$toW,$toH)   
    {   
          $toWH=$toW/$toH;   
          $srcWH=$this->srcW/$this->srcH;   
          if($toWH<=$srcWH)   
          {   
               $ctoH=$toH;   
               $ctoW=$ctoH*($this->srcW/$this->srcH);   
          }   
          else  
          {   
              $ctoW=$toW;   
              $ctoH=$ctoW*($this->srcH/$this->srcW);   
          }    
        $allImg=$this->CreatImage($this->im,$ctoW,$ctoH,0,0,0,0,$this->srcW,$this->srcH);   
        $cImg=$this->CreatImage($allImg,$toW,$toH,0,0,($ctoW-$toW)/2,($ctoH-$toH)/2,$toW,$toH);   
        return $this->EchoImage($cImg,$toFile);   
        ImageDestroy($cImg);   
        ImageDestroy($allImg);   
    }   
  
    //生成背景填充的缩图   
    function BackFill($toFile,$toW,$toH,$bk1=255,$bk2=255,$bk3=255)   
    {   
        $toWH=$toW/$toH;   
        $srcWH=$this->srcW/$this->srcH;   
        if($toWH<=$srcWH)   
        {   
            $ftoW=$toW;   
            $ftoH=$ftoW*($this->srcH/$this->srcW);   
        }   
        else  
        {   
              $ftoH=$toH;   
              $ftoW=$ftoH*($this->srcW/$this->srcH);   
        }   
        if(function_exists("imagecreatetruecolor"))   
        {   
            @$cImg=ImageCreateTrueColor($toW,$toH);   
            if(!$cImg)   
            {   
                $cImg=ImageCreate($toW,$toH);   
            }   
        }   
        else  
        {   
            $cImg=ImageCreate($toW,$toH);   
        }   
        $backcolor = imagecolorallocate($cImg, $bk1, $bk2, $bk3);        //填充的背景颜色   
        ImageFilledRectangle($cImg,0,0,$toW,$toH,$backcolor);   
        if($this->srcW>$toW||$this->srcH>$toH)   
        {        
            $proImg=$this->CreatImage($this->im,$ftoW,$ftoH,0,0,0,0,$this->srcW,$this->srcH);   
             if($ftoW<$toW)   
             {   
                 ImageCopy($cImg,$proImg,($toW-$ftoW)/2,0,0,0,$ftoW,$ftoH);   
             }   
             else if($ftoH<$toH)   
             {   
                 ImageCopy($cImg,$proImg,0,($toH-$ftoH)/2,0,0,$ftoW,$ftoH);   
             }   
             else  
             {   
                 ImageCopy($cImg,$proImg,0,0,0,0,$ftoW,$ftoH);   
             }   
        }   
        else  
        {   
             ImageCopyMerge($cImg,$this->im,($toW-$ftoW)/2,($toH-$ftoH)/2,0,0,$ftoW,$ftoH,100);   
        }   
        return $this->EchoImage($cImg,$toFile);   
        ImageDestroy($cImg);   
    }   
       
  
    function CreatImage($img,$creatW,$creatH,$dstX,$dstY,$srcX,$srcY,$srcImgW,$srcImgH)   
    {   
        if(function_exists("imagecreatetruecolor"))   
        {   
            @$creatImg = ImageCreateTrueColor($creatW,$creatH);   
            if($creatImg)    
                ImageCopyResampled($creatImg,$img,$dstX,$dstY,$srcX,$srcY,$creatW,$creatH,$srcImgW,$srcImgH);   
            else  
            {   
                $creatImg=ImageCreate($creatW,$creatH);   
                ImageCopyResized($creatImg,$img,$dstX,$dstY,$srcX,$srcY,$creatW,$creatH,$srcImgW,$srcImgH);   
            }   
         }   
         else  
         {   
            $creatImg=ImageCreate($creatW,$creatH);   
            ImageCopyResized($creatImg,$img,$dstX,$dstY,$srcX,$srcY,$creatW,$creatH,$srcImgW,$srcImgH);   
         }   
         return $creatImg;   
    }   
       
    //输出图片,link---只输出,不保存文件。file--保存为文件   
    function EchoImage($img,$to_File)   
    {   
        switch($this->echoType)   
        {   
            case "link":   
                if(function_exists('imagejpeg')) return ImageJpeg($img);   
                else return ImagePNG($img);   
                break;   
            case "file":   
                if(function_exists('imagejpeg')) return ImageJpeg($img,$to_File);   
                else return ImagePNG($img,$to_File);   
                break;   
        }   
    }   
}   
?> 

标签: php,