Archive for 四月, 2010

LIGHT BOX效果JS大集合(Jquery相关)

1. Shadowbox http://mjijackson.com/shadowbox/(经典)

<link rel=”stylesheet” type=”text/css” href=”shadowbox.css” media=”screen”>
<script type=”text/javascript” src=”jquery-1.4.1.min.js”></script>
<script type=”text/javascript” src=”shadowbox.js”></script>
<script type=”text/javascript”>Shadowbox.init({overlayOpacity: 0.3});</script>

<a rel="shadowbox[Mixed];" href="myimage.jpg">jpg</a><a rel="shadowbox[Mixed];width=520;height=390" href="myswf.swf">swf</a><a rel="shadowbox[Mixed];width=292;height=218" href="mymovie.mp4">movie</a><a rel="shadowbox[Mixed]" href="mywebsite.html">iframe</a>

——————————————————————————————————————-

2. LightWindow v2.0 http://stickmanlabs.com/lightwindow/

3. FancyBox http://fancy.klade.lv/

4. prettyPhoto www.no-margin-for-errors.com/projects/prettyPhoto/

        <script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>	<link rel="stylesheet" href="css/prettyPhoto.css" type="text/css" media="screen" charset="utf-8" />	<script src="js/jquery.prettyPhoto.js" type="text/javascript" charset="utf-8"></script>         <script type="text/javascript" charset="utf-8">		$(document).ready(function(){			$("a[rel^='prettyPhoto']").prettyPhoto();		});	</script>

5. nyroModal http://nyromodal.nyrodev.com/ (iframe固定)

6. FaceBox http://famspam.com/facebox

7. ClearBox http://www.clearbox.hu/

—————————————–

jQuery Lightbox Plugin

Download Lightbox script

Supported Media: Images

View Demo

Download

Fancybox

Download Lightbox script

Supported Media: Images, Inline HTML, iFrame

View Demo

Download

Shadowbox

Download Lightbox script

Supported Media: Images, Inline HTML, iFrame, AJAX, Flash, Video

View Demo

Download

ThickBox

Download Lightbox script

Supported Media: Images, Inline HTML, iFrame, AJAX

View Demo

Download

Slightly Thickerbox

Download Lightbox script

Supported Media: Images, AJAX, Video

View Demo

Download

Fancy Zoom

Download Lightbox script

Supported Media: Images, Inline HTML, Flash

View Demo

Download

Facebox

Download Lightbox script

Supported Media: Images, Inline HTML, AJAX

View Demo

Download

nyroModal

Download Lightbox script

Supported Media: Images, Inline HTML, iFrame, AJAX, Video

View Demo

Download

Interface Imagebox Demo

Download Lightbox script

Supported Media: Images

View Demo

Download

piroBox

Download Lightbox script

Supported Media: Images

View Demo

Download

Greybox Redux

Download Lightbox script

Supported Media: Images, iFrame

View Demo

Download

prettyPhoto

Download Lightbox script

Supported Media: Images

View Demo

Download

colorbox

http://colorpowered.com/colorbox/


锚点滑动效果

Scroller = {

speed:20,

gy: function (d) {
gy = d.offsetTop
if (d.offsetParent) while (d = d.offsetParent) gy += d.offsetTop
return gy
},

scrollTop: function (){
body=document.body
d=document.documentElement
if (body && body.scrollTop) return body.scrollTop
if (d && d.scrollTop) return d.scrollTop
if (window.pageYOffset) return window.pageYOffset
return 0
},

add: function(event, body, d) {
if (event.addEventListener) return event.addEventListener(body, d,false)
if (event.attachEvent) return event.attachEvent('on'+body, d)
},

end: function(e){
if (window.event) {
window.event.cancelBubble = true
window.event.returnValue = false
return;
}
if (e.preventDefault && e.stopPropagation) {
e.preventDefault()
e.stopPropagation()
}
},

scroll: function(d){
i = window.innerHeight || document.documentElement.clientHeight;
h=document.body.scrollHeight;
a = Scroller.scrollTop()
if(d>a)
if(h-d>i)
a+=Math.ceil((d-a)/Scroller.speed)
else
a+=Math.ceil((d-a-(h-d))/Scroller.speed)
else
a = a+(d-a)/Scroller.speed;
window.scrollTo(0,a)
if(a==d || Scroller.offsetTop==a)clearInterval(Scroller.interval)
Scroller.offsetTop=a
},

init: function(obj){
Scroller.add(window,'load', Scroller.render)
},

render: function(){
a = document.getElementsByTagName('a');
Scroller.end(this);
window.onscroll
for (i=0;i


IE与FireFox在javascript中兼容性问题(经典)

  1. window.event
    • IE:有window.event对象
    • FF:没有window.event对象。可以通过给函数的参数传递event对象。如onmousemove=doMouseMove(event)
  2. 鼠标当前坐标
    • IE:event.x和event.y。
    • FF:event.pageX和event.pageY。
    • 通用:两者都有event.clientX和event.clientY属性。
  3. 鼠标当前坐标(加上滚动条滚过的距离)
    • IE:event.offsetX和event.offsetY。
    • FF:event.layerX和event.layerY。
    • 通用:event.clientY+document.documentElement.scrollTop(加垂直滚动条)。
    • 通用:event.clientX+document.documentElement.scrollLeft(加水平滚动条)。
    • 例:
      <script>
      function xyzb(xy){
      xl=xy.clientX+document.documentElement.scrollLeft;
      yr=xy.clientY+document.documentElement.scrollTop;
      document.getElementById("xys").innerHTML=xl+","+yr;
      }
      </script>
      <div id="xys" style="width:500px;height:500px;border:1px solid;" onmousemove="xyzb(event);"></div>
  4. 标签的x和y的坐标位置:style.posLeft 和 style.posTop
    • IE:有。
    • FF:没有。
    • 通用:object.offsetLeft 和 object.offsetTop。
  5. 窗体的高度和宽度
    • IE:document.body.offsetWidth和document.body.offsetHeight。注意:此时页面一定要有body标签。
    • FF:window.innerWidth和window.innerHegiht,以及document.documentElement.clientWidth和document.documentElement.clientHeight。
    • 通用:document.body.clientWidth和document.body.clientHeight。
  6. 添加事件
    • IE:element.attachEvent("onclick", func);。
    • FF:element.addEventListener("click", func, true)。
    • 通 用:element.onclick=func。虽然都可以使用onclick事件,但是onclick和上面两种方法的效果是不一样的,onclick 只有执行一个过程,而attachEvent和addEventListener执行的是一个过程列表,也就是多个过程。例如: element.attachEvent("onclick", func1);element.attachEvent("onclick", func2)这样func1和func2都会被执行。
  7. 标签的自定义属性
    • IE:如果给标签div1定义了一个属性value,可以div1.value和div1["value"]取得该值。
    • FF:不能用div1.value和div1["value"]取。
    • 通用:div1.getAttribute("value")。
  8. 父节点、子节点和删除节点
    • IE:parentElement、parement.children,element.romoveNode(true)。
    • FF:parentNode、parentNode.childNodes,node.parentNode.removeChild(node)。
  9. 画图
    • IE:VML。
    • FF:SVG。
  10. CSS:透明
    • IE:filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=60)。
    • FF:opacity:0.6。
  11. CSS:圆角
    • IE:不支持圆角。
    • FF: -moz-border-radius:4px,或者-moz-border-radius-topleft:4px;-moz-border- radius-topright:4px;-moz-border-radius-bottomleft:4px;-moz-border- radius- bottomright:4px;。
  12. CSS:双线凹凸边框
    • IE:border:2px outset;。
    • FF: -moz-border-top-colors: #d4d0c8 white;-moz-border-left-colors: #d4d0c8 white;-moz-border-right-colors:#404040 #808080;-moz-border-bottom-colors:#404040 #808080;。

setTimeout和setInterval的使用

这两个方法都可以用来实现在一个固定时间段之后去执行JavaScript。不过两者各有各的应用场景。

 方 法

实际上,setTimeout和setInterval的语法相同。它们都有两个参数,一个是将要执行的代码字符串,还有一个是以毫秒为单位的时间间隔,当过了那个时间段之后就将执行那段代码。

不过这两个函数还是有区别的,setInterval在执行完一次代码之后,经过了那个固定的时间间隔,它还会自动重复执行代码,而setTimeout只执行一次那段代码。

虽然表面上看来setTimeout只能应用在on-off方式的动作上,不过可以通过创建一个函数循环重复调用setTimeout,以实现重复的操作:

File: settimeout_setinterval.js

showTime();

function showTime()

{

    var today = new Date();

    alert("The time is: " + today.toString());

    setTimeout("showTime()", 5000);

}

一旦调用了这个函数,那么就会每隔5秒钟就显示一次时间。如果使用setInterval,则相应的代码如下所示:

File: settimeout_setinterval2.js

setInterval("showTime()", 5000);

function showTime()

{

    var today = new Date();

    alert("The time is: " + today.toString());

}

这两种方法可能看起来非常像,而且显示的结果也会很 相似,不过两者的最大区别就是,setTimeout方法不会每隔5秒钟就执行一次showTime函数,它是在每次调用setTimeout后过5秒钟 再去执行showTime函数。这意味着如果showTime函数的主体部分需要2秒钟执行完,那么整个函数则要每7秒钟才执行一次。而 setInterval却没有被自己所调用的函数所束缚,它只是简单地每隔一定时间就重复执行一次那个函数。

如果要求在每隔一个固定的时间间隔后就精确地执行某动作,那么最好使用setInterval,而如果不想由于连续调用产生互相干扰的问题,尤其是每次函数的调用需要繁重的计算以及很长的处理时间,那么最好使用setTimeout。

函数指针的使用

两个计时函数中的第一个参数是一段代码的字符串,其实该参数也可以是一个函数指针,不过Mac下的IE 5对此不支持。

如果用函数指针作为setTimeout和setInterval函数的第二个参数,那么它们就可以去执行一个在别处定义的函数了:

setTimeout(showTime, 500);

function showTime()

{

    var today = new Date();

    alert("The time is: " + today.toString());

}

另外,匿名函数还可以声明为内联函数:

setTimeout(function(){var today = new Date();

     alert("The time is: " + today.toString());}, 500);

 讨 论

如果对计时函数不加以处理,那么setInterval将会持续执行相同的代码,一直到浏览器窗口关闭,或者用户转到了另外一个页面为止。不过还是有办法可以终止setTimeout和setInterval函数的执行。

当setInterval调用执行完毕时,它将返回一个timer ID,将来便可以利用该值对计时器进行访问,如果将该ID传递给clearInterval,便可以终止那段被调用的过程代码的执行了,具体实现如下:

File: settimeout_setinterval3.js (excerpt)

var intervalProcess = setInterval("alert(‘GOAL!’)", 3000);

var stopGoalLink = document.getElementById("stopGoalLink");

attachEventListener(stopGoalLink, "click", stopGoal, false);

function stopGoal()

{

    clearInterval(intervalProcess);

}

只要点击了stopGoalLink,不管是什么时 候点击,intervalProcess都会被取消掉,以后都不会再继续反复执行intervalProcess。如果在超时时间段内就取消 setTimeout,那么这种终止效果也可以在setTimeout身上实现,具体实现如下:

File: settimeout_setinterval4.js (excerpt)

var timeoutProcess = setTimeout("alert(‘GOAL!’)", 3000);

var stopGoalLink = document.getElementById("stopGoalLink");

attachEventListener(stopGoalLink, "click", stopGoal, false);

function stopGoal()

{

    clearTimeout(timeoutProcess);

}


页面内层的拖动以及仿lightbox显隐效果

调用的JS代码:

var Layer=”;
var iLayerMaxNum=1000;
var a;
document.onmouseup=me;
document.onmousemove=ms;
var b;
var c;
function Move(Object,event){
Layer=Object.id;
if(document.all){
   document.getElementById(Layer).setCapture();
   b=event.x-document.getElementById(Layer).style.pixelLeft;
   c=event.y-document.getElementById(Layer).style.pixelTop;
}else if(window.captureEvents){
   window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP);
   b=event.layerX;
   c=event.layerY+100;
};
if(Layer!="Layer"+a){
   document.getElementById(Layer).style.zIndex=iLayerMaxNum;
   iLayerMaxNum=iLayerMaxNum+1;
}
}
function ms(d){
if(Layer!=”){
   if(document.all){
    document.getElementById(Layer).style.left=event.x-b;
    document.getElementById(Layer).style.top=event.y-c;
   }else if(window.captureEvents){
    document.getElementById(Layer).style.left=(d.clientX-b)+"px";
    document.getElementById(Layer).style.top=(d.clientY-c)+"px";
   }
}
}
function me(d){
if(Layer!=”){
   if(document.all){
    document.getElementById(Layer).releaseCapture();
    Layer=”;
   }else if(window.captureEvents){
    window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP);
    Layer=”;
   }
}
}
function Close(n){
var e=’Layer’+n;           
document.getElementById(e).style.display=’none’;
}
function Show(n){
var e=’Layer’+n;
document.getElementById(e).style.zIndex =iLayerMaxNum+1;
document.getElementById("aspk").style.display = "block";
document.getElementById("aspk").style.zIndex = iLayerMaxNum;
var size = getPageSize();
document.getElementById("aspk").style.width = size[0];
document.getElementById("aspk").style.height = size[1];
}
function Hide(){
document.getElementById("aspk").style.display = "none";
iLayerMaxNum=iLayerMaxNum+2;
}
function getPageSize(){
var de = document.documentElement;
var w = de.clientWidth;
var h = de.clientHeight;
arrayPageSize = new Array(w,h);
return arrayPageSize;
}

html文件演示代码:

    <div style="display:none;" id="aspk" onclick="Hide();"></div>
    <div>
        <div id="Layer1" style="position:absolute;cursor:move;" onmousedown="Move(this,event)" ondblclick="Show(1)">aaaaaaa</div>
        <div id="Layer2" style="position:absolute;cursor:move;" onmousedown="Move(this,event)" ondblclick="Show(2)">bbbbbbb</div>
        ……
    </div>


PHP图片缩放函数

在PHP网站开发过程中,如果你建立的网站涉及大量的图片处理,必然涉及到图片上传,缩放,而如何保持图片不失真,是很多初级PHP网站开发者比较头疼的一件事,今天David就和大家分享一下如何进行图片缩放。使用之前你需要下载安装GD库,以支持PHP图片处理。下面我们结合代码讲解具体的PHP图片缩放处理的思路。

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
function resizeImage($im,$maxwidth,$maxheight,$name,$filetype,$folder)
{
    $pic_width = imagesx($im);
    $pic_height = imagesy($im);

    if(($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight))
    {
        if($maxwidth && $pic_width>$maxwidth)
        {
            $widthratio = $maxwidth/$pic_width;
            $resizewidth_tag = true;
        }

        if($maxheight && $pic_height>$maxheight)
        {
            $heightratio = $maxheight/$pic_height;
            $resizeheight_tag = true;
        }

        if($resizewidth_tag && $resizeheight_tag)
        {
            if($widthratio<$heightratio)
                $ratio = $widthratio;
            else
                $ratio = $heightratio;
        }

        if($resizewidth_tag && !$resizeheight_tag)
            $ratio = $widthratio;
        if($resizeheight_tag && !$resizewidth_tag)
            $ratio = $heightratio;

        $newwidth = $pic_width * $ratio;
        $newheight = $pic_height * $ratio;

        if(function_exists("imagecopyresampled"))
        {
            $newim = imagecreatetruecolor($newwidth,$newheight);
           imagecopyresampled($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);
        }
        else
        {
            $newim = imagecreate($newwidth,$newheight);
           imagecopyresized($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);
        }

        $name = $name.$filetype;

        createTempImage($newim,$folder.$name,$filetype);
        imagedestroy($newim);
    }
    else
    {
        $name = $name.$filetype;
        createTempImage($im,$folder.$name,$filetype);
    }          
}

 

function createTempImage($newim,$name,$type) {
    switch($type)
    {
        case ‘.jpg’:
            imagejpeg($newim,$name);
            break;
        case ‘.gif’:
            imagegif($newim,$name);
            break;
        case ‘.png’:
            imagepng($newim,$name);
            break;
    }
}
 
用法:
$im = imagecreatefromjpeg(‘test.jpg’);

echo "<img src=’temp/". resizeImage($im,200,200,’WLK’,’.png’,’temp/’)."’/>";

参数说明

$im 图片对象,应用函数之前,你需要用imagecreatefromjpeg()读取图片对象,如果PHP环境支持PNG,GIF,也可使用imagecreatefromgif(),imagecreatefrompng()

$maxwidth 定义生成图片的最大宽度(单位:像素)

$maxheight 生成图片的最大高度(单位:像素)

$name 生成的图片名

$filetype 最终生成的图片类型(.jpg/.png/.gif)

代码注释

第3~4行:读取需要缩放的图片实际宽高

第8~26行:通过计算实际图片宽高与需要生成图片的宽高的压缩比例最终得出进行图片缩放是根据宽度还是高度进行缩放,当前程序是根据宽度进行图片缩放。如果你想根据高度进行图片缩放,你可以将第22行的语句改成$widthratio>$heightratio

第28~31行:如果实际图片的长度或者宽度小于规定生成图片的长度或者宽度,则要么根据长度进行图片缩放,要么根据宽度进行图片缩放。

第33~34行:计算最终缩放生成的图片长宽。

第36~45行:根据计算出的最终生成图片的长宽改变图片大小,有两种改变图片大小的方法:ImageCopyResized()函数在所有GD版本中有效,但其缩放图像的算法比较粗糙。ImageCopyResamples(),其像素插值算法得到的图像边缘比较平滑,但该函数的速度比ImageCopyResized()慢。

第47~49行:最终生成经过处理后的图片,如果你需要生成GIF或PNG,你需要将imagejpeg()函数改成imagegif()或imagepng()

第51~56行:如果实际图片的长宽小于规定生成的图片长宽,则保持图片原样,同理,如果你需要生成GIF或PNG,你需要将imagejpeg()函数改成imagegif()或imagepng()。

特别说明

  GD库1.6.2版以前支持GIF格式,但因GIF格式使用LZW演算法牵涉专利权,因此在GD1.6.2版之后不支持GIF的格式。如果你是 WINDOWS的环境,你只要进入PHP.INI文件找到extension=php_gd2.dll,将#去除,重启APACHE即可,如果你是 Linux环境,又想支持GIF,PNG,JPEG,你需要去下载libpngzlib,以及freetype字体并安装。

  OK,PHP图片压缩函数完成,最后我们概述一下整个处理的思路:

  通过计算实际图片的长宽与规定生成图片的长宽之间的缩放比例,根据实际的需求(按照宽度还是按照高度进行图片缩放)计算出最终生成图片的大小,然后应用PHP图片处理函数对图片进行处理,最后输出图片。

  以上就是关于PHP图片处理中如何对图片进行压缩并保持不失真的函数说明,有疑问或者好的建议欢迎给我留言,下次我将分享在PHP网站开发建设完成后,由于图片目录没有规划好,我们该如何对图片进行迁移的思路。


PclZip简介与使用


PclZip介绍
PclZip library能够压缩与解压缩Zip格式的压缩档(WinZip、PKZIP);且能对此类类档案进行处理,包括产生压缩档、列出压缩档的内容以及解压缩档案等等。由于能够在伺服器端进行压缩与解压缩的动作,所以相当方便使用。
PclZip定义一个PclZip类别,其类别物件可视为一个ZIP档案,亦提供method来进行处理。

如何使用PclZip
1.基础
所有的功能都由pclzip.lib.php这个档案提供,PclZip library可于其首页(www.phpconcept.net/pclzip/index.en.php)下载。所有的PKZIP档案其实就是一个 PclZip的类别物件。当产生一个PclZip档案(ie, PclZip类别物件),就会先产生一个压缩档,且档名已经指定,但此压缩档的内容尚未存在:

< ?PHP
         require_once(‘pclzip.lib.php’);
         $archive = new PclZip("archive.zip");
?>

此物件提供了一些public method可用来处理此档案。

 

2.参数
每一个method有其各自可使用的参数,包括有必须与非必须的参数:

< ?PHP
         require_once(‘pclzip.lib.php’);
         $archive = new PclZip(‘archive.zip’);
 
         $v_list = $archive->add(‘dev/file.txt’,
                                    PCLZIP_OPT_REMOVE_PATH, ‘dev’);
?>

上例中的’dev/file.txt’就是必须参数;’PCLZIP_OPT_REMOVE_PATH’则为非必须参数。当然有些method也可以只包含非必须的参数:

< ?PHP
         $list = $archive->extract(PCLZIP_OPT_PATH, "folder",
                          PCLZIP_OPT_REMOVE_PATH, "data",
                                PCLZIP_CB_PRE_EXTRACT, "callback_pre_extract",);
?>

上例中原本压缩档内档案存放的路径为/data,不过你可以指定解压缩至/folder中。此外,在解压缩之前,会呼叫callback function(’callback_pre_extract()’),此function可让使用者在解压缩的过程中变更档案存放路径与档名,或是选 择某些档案不解压缩。
所有可用的非必要参数可参考网址(www.phpconcept.net/pclzip/man/en/index.php)。

3.回传值
每个method所回传的值可能会不同,将会在每个method中说明。不过大部分的method回传0、error或是阵列。

4.错误处理
从版本1.3之后,错误处理已经整合至PclZip类别中,当一个method回传错误码,可以得知一些额外的讯息以方便错误处理:
* errorName():回传错误名称
* errorCode():回传错误码
* errorInfo():回传错误的描述

接下来会举几个例子来说明如何使用PclZip。

PclZip实例1、产生ZIP压缩档
PclZip($zipname):为PclZip constructor,$zipname为PKZIP压缩档的档名。
主要是产生一个PclZip物件,即一个PKZIP压缩档;但此时,只有压缩档产生出来,并做一些检查(例如是否有开启zlib extension…等),除此之外,并没有做其他动作。
create($filelist, [optional arguments list]):将参数$filelist指定的档案或目录(包含当中所有档案与子目录)加入上述所产生的压缩档中。
而非必要的参数则能够修改压缩档内的档案存放路径。
此method可用的参数可以参考网志(www.phpconcept.net/pclzip/man/en/index.php)。

下面的示例说明如何产生PKZIP压缩档(档名为archive.zip),并将file.txt、data/text.txt以及目录folder(包含当中的档案与子目录)加入刚刚产生的archive.zip中:

< ?PHP
        include_once(‘pclzip.lib.php’);
        $archive = new PclZip(‘archive.zip’);
        $v_list = $archive->create(‘file.txt,data/text.txt,folder’);
        if ($v_list == 0) {
            die("Error : ".$archive->errorInfo(true));
        }
?>

下面的示例说明基本上与上例一样产生archive.zip,但在将file.txt与text.txt压缩于其中时,将路径由data/改为 install/ ;因此,在archive.zip中这两个档案的路径会是install/file.txt与install/text.txt

< ?PHP
        include_once(‘pclzip.lib.php’);
        $archive = new PclZip(‘archive.zip’);
        $v_list = $archive->create(‘data/file.txt,data/text.txt’,
                                         PCLZIP_OPT_REMOVE_PATH, ‘data’,
                                         PCLZIP_OPT_ADD_PATH, ‘install’);
        if ($v_list == 0) {
            die("Error : ".$archive->errorInfo(true));
        }
?>

PclZip实例2、列出压缩档内容
listContent( ) :列出压缩档中的内容,包括档案的属性与目录:

< ?PHP
        include_once(‘pclzip.lib.php’);
        $zip = new PclZip("test.zip");
 
        if (($list = $zip->listContent()) == 0) {
        die("Error : ".$zip->errorInfo(true));
        }
 
        for ($i=0; $i<sizeof ($list); $i++) {
            for(reset($list[$i]); $key = key($list[$i]); next($list[$i])) {
                echo "File $i / [$key] = ".$list[$i][$key]."<br>";
            }
            echo "<br />";
        }
?></sizeof>

上例将会回传结果:
File 0 / [filename] = data/file1.txt
File 0 / [stored_filename] = data/file1.txt
File 0 / [size] = 53
File 0 / [compressed_size] = 36
File 0 / [mtime] = 1010440428
File 0 / [comment] =
File 0 / [folder] = 0
File 0 / [index] = 0
File 0 / [status] = ok

File 1 / [filename] = data/file2.txt
File 1 / [stored_filename] = data/file2.txt
File 1 / [size] = 54
File 1 / [compressed_size] = 53
File 1 / [mtime] = 1011197724
File 1 / [comment] =
File 1 / [folder] = 0
File 1 / [index] = 1
File 1 / [status] = ok

PclZip实例3、解压缩档案
extract([options list]) :解压缩PKZIP中的档案或目录。
[options list]可用的参数可参考网址(www.phpconcept.net/pclzip/man/en/index.php)。这些参数能让使用者在解压 缩的时候有更多的选项,譬如指定变更解压缩档案的路径、指定只解压缩某些档案或不解压缩某些档案或者是将档案解压缩成字串输出(可用于readme档)。

下例是一个简单的解压缩档案示例,将压缩档archive.zip内的档案解压缩至目前的目录:

< ?PHP
        require_once(‘pclzip.lib.php’);
        $archive = new PclZip(‘archive.zip’);
 
 
        if ($archive->extract() == 0) {
            die("Error : ".$archive->errorInfo(true));
        }
?>

下例是进阶的解压缩档案使用,archive.zip中所有档案都解压缩于data/中,而特别指明在install/release中的所有档案也直接丢于data/中,而非data/install/ release:

< ?PHP
        include(‘pclzip.lib.php’);
        $archive = new PclZip(‘archive.zip’);
        if ($archive->extract(PCLZIP_OPT_PATH, ‘data’,
                  PCLZIP_OPT_REMOVE_PATH, ‘install/release’) == 0) {
                                die("Error : ".$archive->errorInfo(true));
        }
?>

相关文档:
PclZip官方地址:http://www.phpconcept.net/pclzip/index.php
PclZip手册地址:http://www.phpconcept.net/pclzip/man/en/index.php
PEAR类创建ZIP档案文件:http://www.ccvita.com/10.html
PclZip简介与使用:http://www.ccvita.com/59.html
PclZip:强大的PHP压缩与解压缩zip类:http://www.ccvita.com/330.html


php汉字验证码-中文验证码-支持uft8和gbk

php汉字验证码-中文验证码-支持uft8和gbk

 

uft8 案例

 

  1. <?php  
  2. define(‘WWW.PHPZY.COM’, ‘WWW.PHPZY.COM’);  
  3. function verify($user_str){//从cookie中对比用户的输入  
  4.         if(md5($cookie_str.WWW.PHPZY.COM)==$_COOKIE[‘vrify’])  
  5.                 return 1;  
  6.         else 
  7.                 return 0;  
  8. }  
  9. function c2ch($num){  
  10.   $ch_h = chr(substr($num,0,2)+160);  
  11.   $ch_l = chr(substr($num,2,2)+160);  
  12.   return $ch_h.$ch_l;  
  13. }  
  14. function num_rand(){  
  15.         mt_srand((double)microtime() * 1000000);  
  16.         $d= mt_rand(16,36);  
  17.         $n= mt_rand(1,19);  
  18.         return c2ch($d*100+$n);  
  19. }  
  20.  
  21. $k[0]=num_rand();  
  22. $k[1]=num_rand();  
  23. $k[2]=num_rand();  
  24. $k[3]=num_rand();  
  25. //print_r($k);  
  26. $cookie_str=implode(”, $k);  
  27. setcookie(‘vrify’,md5($cookie_str.WWW.PHPZY.COM),time()+600);  
  28. $str[0]=iconv(‘gb2312′,’UTF-8’,$k[0]);  
  29. $str[1]=iconv(‘gb2312′,’UTF-8’,$k[1]);  
  30. $str[2]=iconv(‘gb2312′,’UTF-8’,$k[2]);  
  31. $str[3]=iconv(‘gb2312′,’UTF-8’,$k[3]);  
  32. //构造图像  
  33. $x_size=80;  
  34. $y_size=25;  
  35.  
  36. $font=’heiti.ttf’;  
  37. $pic=imagecreate($x_size,$y_size);  
  38. $background_color = imagecolorallocate ($pic, 255, 255, 255);  
  39. $black=imagecolorallocate($pic,0,0,0);  
  40. $red=imagecolorallocate($pic,255,0,0);  
  41. $ddd=imagecolorallocate($pic,255,0,255);  
  42. imagettftext($pic,15,mt_rand(-8,8),6,mt_rand(19,22),$black,$font,$str[0]);  
  43. imagettftext($pic,15,mt_rand(-8,8),37,20,$black,$font,$str[2]);  
  44. imagettftext($pic,mt_rand(15,17),mt_rand(-8,8),22,20,$ddd,$font,$str[1]);  
  45. imagettftext($pic,mt_rand(15,17),mt_rand(-8,8),54,mt_rand(19,22),$red,$font,$str[3]);  
  46. imagerectangle($pic, 0, 0, $x_size – 1, $y_size – 1,$black);  
  47. Imagepng($pic);  
  48. ImageDestroy($pic);  
  49. ?>  
  50.  

 

gbk案例

 

 

  1. <?php  
  2. error_reporting(0);  
  3. session_start();  
  4.  
  5. Header("Content-type: image/PNG");  
  6. $str = "的一是在了不和有大这主中人上为们地个用工时要动国产以我到他会作来分生对于学下级就年";  
  7. $imgWidth = 130;  
  8. $imgHeight = 40;  
  9. $authimg = imagecreate($imgWidth,$imgHeight);  
  10. $bgColor = ImageColorAllocate($authimg,255,255,255);  
  11. $fontfile = "simhei.ttf";  
  12. $white=imagecolorallocate($authimg,234,185,95);  
  13. imagearc($authimg, 150, 8, 20, 20, 75, 170, $white);  
  14. imagearc($authimg, 180, 7,50, 30, 75, 175, $white);  
  15. imageline($authimg,20,20,180,30,$white);  
  16. imageline($authimg,20,18,170,50,$white);  
  17. imageline($authimg,25,50,80,50,$white);  
  18. $noise_num = 800;  
  19. $line_num = 20;  
  20. imagecolorallocate($authimg,0xff,0xff,0xff);  
  21. $rectangle_color=imagecolorallocate($authimg,0xAA,0xAA,0xAA);  
  22. $noise_color=imagecolorallocate($authimg,0x00,0x00,0x00);  
  23. $font_color=imagecolorallocate($authimg,0x00,0x00,0x00);  
  24. $line_color=imagecolorallocate($authimg,0x00,0x00,0x00);  
  25. for($i=0;$i<$noise_num;$i++){  
  26.     imagesetpixel($authimg,mt_rand(0,$imgWidth),mt_rand(0,$imgHeight),$noise_color);  
  27. }  
  28. for($i=0;$i<$line_num;$i++){  
  29.     imageline($authimg,mt_rand(0,$imgWidth),mt_rand(0,$imgHeight),mt_rand(0,$imgWidth),mt_rand(0,$imgHeight),$line_color);  
  30. }  
  31. $randnum=rand(0,strlen($str)-4);  
  32. if($randnum%2)$randnum+=1;  
  33. $str = substr($str,$randnum,8);  
  34.  
  35. $_SESSION[chart]=$str;  
  36.  
  37. //$str = iconv("GB2312","UTF-8",$str);  
  38.  
  39. ImageTTFText($authimg, 20, 0, 16, 30, $font_color, $fontfile, $str);  
  40. //ImagePNG($authimg);  
  41. //ImageDestroy($authimg);  
  42.  
  43. @header("Expires: -1");  
  44. @header("Cache-Control: no-store, private, post-check=0, pre-check=0, max-age=0", FALSE);  
  45. @header("Pragma: no-cache");  
  46. header(‘Content-Type: image/jpeg’);  
  47. imagepng($authimg);  
  48. ?>  
  49.  

记得放字体!没有字体随便去控制面板-字体-复制一个过来就可以使用了

 

http://www.phpzy.com/phpjichuwenda/336.html


php解压zip

<?php

//验证密码,请自行修改以免被人攻击
$password = "666666";

?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>Faisun_unzip – 纯粹空间 – www.softpure.com</title>
<style type="text/css">
<!–
body,td{
    font-size: 14px;
    color: #000000;
}
a {
    color: #000066;
    text-decoration: none;
}
a:hover {
    color: #FF6600;
    text-decoration: underline;
}
–>
</style>
</head>

<body>
  <form name="myform" method="post" action="<?php echo $_SERVER[‘PHP_SELF’];?>" enctype="multipart/form-data" onSubmit="return check_uploadObject(this);">
<?php
    if(!isset($_REQUEST["myaction"])):
?>

<script language="javascript">
function check_uploadObject(form){
    if(form.password.value==”){
        alert(‘请输入密码.’);
        return false;
    }
    return true;
}
</script>

<table width="100%" border="0" cellspacing="0" cellpadding="4">
    <tr>
      <td height="40" colspan="2" style="color:#FF9900"><p><font color="#FF0000">在线解压ZIP文件程序</font></p>
      <p>使用方法:把zip文件通过FTP上传到本文件相同的目录下,选择zip文件;或直接点击“浏览…”上传zip文件。</p>
      <p>解压的结果保留原来的目录结构。</p>
      <p>&nbsp;</p></td>
    </tr>
    <tr>
      <td width="11%">选择ZIP文件: </td>
      <td width="89%"><select name="zipfile">
        <option value="" selected>- 请选择 -</option>
<?php
      $fdir = opendir(‘./’);
    while($file=readdir($fdir)){
        if(!is_file($file)) continue;
        if(preg_match(‘/\.zip$/mis’,$file)){
            echo "<option value=’$file’>$file</option>\r\n";
        }
    }
?>
      </select></td>
    </tr>
    <tr>
      <td width="11%" nowrap>或上传文件: </td>
      <td width="89%"><input name="upfile" type="file" id="upfile" size="20"></td>
    </tr>
    <tr>
      <td>解压到目录: </td>
      <td><input name="todir" type="text" id="todir" value="" size="15">
      (留空为本目录,必须有写入权限)</td>
    </tr>
    <tr>
      <td>验证密码: </td>
      <td><input name="password" type="password" id="password" size="15">
        (源文件中设定的密码)</td>
    </tr>
    <tr>
      <td><input name="myaction" type="hidden" id="myaction" value="dounzip"></td>
      <td><input type="submit" name="Submit" value=" 解 压 "></td>
    </tr>
  </table>

<?php

elseif($_REQUEST["myaction"]=="dounzip"):

class zip
{

 var $total_files = 0;
 var $total_folders = 0;

 function Extract ( $zn, $to, $index = Array(-1) )
 {
   $ok = 0; $zip = @fopen($zn,’rb’);
   if(!$zip) return(-1);
   $cdir = $this->ReadCentralDir($zip,$zn);
   $pos_entry = $cdir[‘offset’];

   if(!is_array($index)){ $index = array($index);  }
   for($i=0; $index[$i];$i++){
           if(intval($index[$i])!=$index[$i]||$index[$i]>$cdir[‘entries’])
        return(-1);
   }
   for ($i=0; $i<$cdir[‘entries’]; $i++)
   {
     @fseek($zip, $pos_entry);
     $header = $this->ReadCentralFileHeaders($zip);
     $header[‘index’] = $i; $pos_entry = ftell($zip);
     @rewind($zip); fseek($zip, $header[‘offset’]);
     if(in_array("-1",$index)||in_array($i,$index))
         $stat[$header[‘filename’]]=$this->ExtractFile($header, $to, $zip);
   }
   fclose($zip);
   return $stat;
 }

  function ReadFileHeader($zip)
  {
    $binary_data = fread($zip, 30);
    $data = unpack(‘vchk/vid/vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len’, $binary_data);

    $header[‘filename’] = fread($zip, $data[‘filename_len’]);
    if ($data[‘extra_len’] != 0) {
      $header[‘extra’] = fread($zip, $data[‘extra_len’]);
    } else { $header[‘extra’] = ”; }

    $header[‘compression’] = $data[‘compression’];$header[‘size’] = $data[‘size’];
    $header[‘compressed_size’] = $data[‘compressed_size’];
    $header[‘crc’] = $data[‘crc’]; $header[‘flag’] = $data[‘flag’];
    $header[‘mdate’] = $data[‘mdate’];$header[‘mtime’] = $data[‘mtime’];

    if ($header[‘mdate’] && $header[‘mtime’]){
     $hour=($header[‘mtime’]&0xF800)>>11;$minute=($header[‘mtime’]&0x07E0)>>5;
     $seconde=($header[‘mtime’]&0x001F)*2;$year=(($header[‘mdate’]&0xFE00)>>9)+1980;
     $month=($header[‘mdate’]&0x01E0)>>5;$day=$header[‘mdate’]&0x001F;
     $header[‘mtime’] = mktime($hour, $minute, $seconde, $month, $day, $year);
    }else{$header[‘mtime’] = time();}

    $header[‘stored_filename’] = $header[‘filename’];
    $header[‘status’] = "ok";
    return $header;
  }

 function ReadCentralFileHeaders($zip){
    $binary_data = fread($zip, 46);
    $header = unpack(‘vchkid/vid/vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset’, $binary_data);

    if ($header[‘filename_len’] != 0)
      $header[‘filename’] = fread($zip,$header[‘filename_len’]);
    else $header[‘filename’] = ”;

    if ($header[‘extra_len’] != 0)
      $header[‘extra’] = fread($zip, $header[‘extra_len’]);
    else $header[‘extra’] = ”;

    if ($header[‘comment_len’] != 0)
      $header[‘comment’] = fread($zip, $header[‘comment_len’]);
    else $header[‘comment’] = ”;

    if ($header[‘mdate’] && $header[‘mtime’])
    {
      $hour = ($header[‘mtime’] & 0xF800) >> 11;
      $minute = ($header[‘mtime’] & 0x07E0) >> 5;
      $seconde = ($header[‘mtime’] & 0x001F)*2;
      $year = (($header[‘mdate’] & 0xFE00) >> 9) + 1980;
      $month = ($header[‘mdate’] & 0x01E0) >> 5;
      $day = $header[‘mdate’] & 0x001F;
      $header[‘mtime’] = mktime($hour, $minute, $seconde, $month, $day, $year);
    } else {
      $header[‘mtime’] = time();
    }
    $header[‘stored_filename’] = $header[‘filename’];
    $header[‘status’] = ‘ok’;
    if (substr($header[‘filename’], -1) == ‘/’)
      $header[‘external’] = 0x41FF0010;
    return $header;
 }

 function ReadCentralDir($zip,$zip_name){
    $size = filesize($zip_name);

    if ($size < 277) $maximum_size = $size;
    else $maximum_size=277;

    @fseek($zip, $size-$maximum_size);
    $pos = ftell($zip); $bytes = 0x00000000;

    while ($pos < $size){
        $byte = @fread($zip, 1); $bytes=($bytes << 8) | ord($byte);
        if ($bytes == 0x504b0506 or $bytes == 0x2e706870504b0506){ $pos++;break;} $pos++;
    }

    $fdata=fread($zip,18);

    $data=@unpack(‘vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size’,$fdata);

    if ($data[‘comment_size’] != 0) $centd[‘comment’] = fread($zip, $data[‘comment_size’]);
    else $centd[‘comment’] = ”; $centd[‘entries’] = $data[‘entries’];
    $centd[‘disk_entries’] = $data[‘disk_entries’];
    $centd[‘offset’] = $data[‘offset’];$centd[‘disk_start’] = $data[‘disk_start’];
    $centd[‘size’] = $data[‘size’];  $centd[‘disk’] = $data[‘disk’];
    return $centd;
  }

 function ExtractFile($header,$to,$zip){
    $header = $this->readfileheader($zip);

    if(substr($to,-1)!="/") $to.="/";
    if($to==’./’) $to = ”;
    $pth = explode("/",$to.$header[‘filename’]);
    $mydir = ”;
    for($i=0;$i<count($pth)-1;$i++){
        if(!$pth[$i]) continue;
        $mydir .= $pth[$i]."/";
        if((!is_dir($mydir) && @mkdir($mydir,0777)) || (($mydir==$to.$header[‘filename’] || ($mydir==$to && $this->total_folders==0)) && is_dir($mydir)) ){
            @chmod($mydir,0777);
            $this->total_folders ++;
            echo "<input name=’dfile[]’ type=’checkbox’ value=’$mydir’ checked> <a href=’$mydir’ target=’_blank’>目录: $mydir</a><br>";
        }
    }

    if(strrchr($header[‘filename’],’/’)==’/’) return;

    if (!($header[‘external’]==0x41FF0010)&&!($header[‘external’]==16)){
        if ($header[‘compression’]==0){
            $fp = @fopen($to.$header[‘filename’], ‘wb’);
            if(!$fp) return(-1);
            $size = $header[‘compressed_size’];

            while ($size != 0){
                $read_size = ($size < 2048 ? $size : 2048);
                $buffer = fread($zip, $read_size);
                $binary_data = pack(‘a’.$read_size, $buffer);
                @fwrite($fp, $binary_data, $read_size);
                $size -= $read_size;
            }
            fclose($fp);
            touch($to.$header[‘filename’], $header[‘mtime’]);
        }else{
            $fp = @fopen($to.$header[‘filename’].’.gz’,’wb’);
            if(!$fp) return(-1);
            $binary_data = pack(‘va1a1Va1a1’, 0x8b1f, Chr($header[‘compression’]),
            Chr(0x00), time(), Chr(0x00), Chr(3));

            fwrite($fp, $binary_data, 10);
            $size = $header[‘compressed_size’];

            while ($size != 0){
                $read_size = ($size < 1024 ? $size : 1024);
                $buffer = fread($zip, $read_size);
                $binary_data = pack(‘a’.$read_size, $buffer);
                @fwrite($fp, $binary_data, $read_size);
                $size -= $read_size;
            }

            $binary_data = pack(‘VV’, $header[‘crc’], $header[‘size’]);
            fwrite($fp, $binary_data,8); fclose($fp);

            $gzp = @gzopen($to.$header[‘filename’].’.gz’,’rb’) or die("Cette archive est compress閑");
            if(!$gzp) return(-2);
            $fp = @fopen($to.$header[‘filename’],’wb’);
            if(!$fp) return(-1);
            $size = $header[‘size’];

            while ($size != 0){
                $read_size = ($size < 2048 ? $size : 2048);
                $buffer = gzread($gzp, $read_size);
                $binary_data = pack(‘a’.$read_size, $buffer);
                @fwrite($fp, $binary_data, $read_size);
                $size -= $read_size;
            }
            fclose($fp); gzclose($gzp);

            touch($to.$header[‘filename’], $header[‘mtime’]);
            @unlink($to.$header[‘filename’].’.gz’);

        }
    }

    $this->total_files ++;
    echo "<input name=’dfile[]’ type=’checkbox’ value=’$to$header[filename]’ checked> <a href=’$to$header[filename]’ target=’_blank’>文件: $to$header[filename]</a><br>";

    return true;
 }

// end class
}

    set_time_limit(0);

    if ($_POST[‘password’] != $password) die("输入的密码不正确,请重新输入。");
    if(!$_POST["todir"]) $_POST["todir"] = ".";
    $z = new Zip;
    $have_zip_file = 0;
    function start_unzip($tmp_name,$new_name,$checked){
        global $_POST,$z,$have_zip_file;
        $upfile = array("tmp_name"=>$tmp_name,"name"=>$new_name);
        if(is_file($upfile[‘tmp_name’])){
            $have_zip_file = 1;
            echo "<br>正在解压: <input name=’dfile[]’ type=’checkbox’ value=’$upfile[name]’ ".($checked?"checked":"")."> $upfile[name]<br><br>";
            if(preg_match(‘/\.zip$/mis’,$upfile[‘name’])){
                $result=$z->Extract($upfile[‘tmp_name’],$_POST["todir"]);
                if($result==-1){
                    echo "<br>文件 $upfile[name] 错误.<br>";
                }
                echo "<br>完成,共建立 $z->total_folders 个目录,$z->total_files 个文件.<br><br><br>";
            }else{
                echo "<br>$upfile[name] 不是 zip 文件.<br><br>";
            }
            if(realpath($upfile[‘name’])!=realpath($upfile[‘tmp_name’])){
                @unlink($upfile[‘name’]);
                rename($upfile[‘tmp_name’],$upfile[‘name’]);
            }
        }
    }
    clearstatcache();

    start_unzip($_POST["zipfile"],$_POST["zipfile"],0);
    start_unzip($_FILES["upfile"][‘tmp_name’],$_FILES["upfile"][‘name’],1);

    if(!$have_zip_file){
        echo "<br>请选择或上传文件.<br>";
    }
?>
<input name="password" type="hidden" id="password" value="<?php echo $_POST[‘password’];?>">
<input name="myaction" type="hidden" id="myaction" value="dodelete">
<input name="按钮" type="button" value="返回" onclick="window.location='<?php echo $_SERVER[‘PHP_SELF’];?>’;">

<input type=’button’ value=’反选’ onclick=’selrev();’> <input type=’submit’ onclick=’return confirm("删除选定文件?");’ value=’删除选定’>

<script language=’javascript’>
function selrev() {
    with(document.myform) {
        for(i=0;i<elements.length;i++) {
            thiselm = elements[i];
            if(thiselm.name.match(/dfile\[]/))    thiselm.checked = !thiselm.checked;
        }
    }
}
alert(‘完成.’);
</script>
<?php

elseif($_REQUEST["myaction"]=="dodelete"):
    set_time_limit(0);
    if ($_POST[‘password’] != $password) die("输入的密码不正确,请重新输入。");

    $dfile = $_POST["dfile"];
    echo "正在删除文件…<br><br>";
    if(is_array($dfile)){
        for($i=count($dfile)-1;$i>=0;$i–){
            if(is_file($dfile[$i])){
                if(@unlink($dfile[$i])){
                    echo "已删除文件: $dfile[$i]<br>";
                }else{
                    echo "删除文件失败: $dfile[$i]<br>";
                }
            }else{
                if(@rmdir($dfile[$i])){
                    echo "已删除目录: $dfile[$i]<br>";
                }else{
                    echo "删除目录失败: $dfile[$i]<br>";
                }
            }

        }
    }
    echo "<br>完成.<br><br><input type=’button’ value=’返回’ onclick=\"window.location=’".$_SERVER[‘PHP_SELF’]."’;\"><br><br>
         <script language=’javascript’>(‘完成.’);</script>";

endif;

?>
  </form>
</body>
</html>


PHP最大上传文件大小限制修改

PHP默认的上传文件大小限制为2M,可以修改php.ini文件来增大上传大小。
改成50M需修改如下:
upload_max_filesize = 50M
post_max_size = 100M
memory_limit = 150M

需要保持memory_limit (如果有設定的話) > post_max_size > upload_max_filesize

max_execution_time = 150 脚本执行时间(秒)
max_input_time = 300 脚本解析时间(秒)

执行时间适当改大,保证php脚本的执行不会在上传过程中超时


Copyright © 1996-2010 Add Lives. All rights reserved.
iDream theme by Templates Next | Powered by WordPress