iLeichun

当前位置:首页PHP

PHP生成同比例的缩略图代码

分类:PHP  来源:网络  时间:2011-3-12 20:24:30

创建图像缩略图需要许多时间,此代码将有助于了解缩略图的逻辑。
 
/**********************
*@filename - path to the image
*@tmpname - temporary path to thumbnail
*@xmax - max width
*@ymax - max height
*/
function resize_image($filename, $tmpname, $xmax, $ymax)
{
    $ext = explode(".", $filename);
    $ext = $ext[count($ext)-1];

    if($ext == "jpg" || $ext == "jpeg")
        $im = imagecreatefromjpeg($tmpname);
    elseif($ext == "png")
        $im = imagecreatefrompng($tmpname);
    elseif($ext == "gif")
        $im = imagecreatefromgif($tmpname);

    $x = imagesx($im);
    $y = imagesy($im);

    if($x <= $xmax && $y <= $ymax)
        return $im;

    if($x >= $y) {
        $newx = $xmax;
        $newy = $newx * $y / $x;
    }
    else {
        $newy = $ymax;
        $newx = $x / $y * $newy;
    }

    $im2 = imagecreatetruecolor($newx, $newy);
    imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);
    return $im2;
}

 

文章来源:侠客站长站(www.xkzzz.com) 详文参考:http://www.xkzzz.com/zz/netbc/php/201009/22-56337.html

PHP Zip压缩和解压缩

分类:PHP  来源:网络  时间:2011-3-12 20:22:46

PHP文件 Zip 压缩

/* creates a compressed zip file */
function create_zip($files = array(),$destination = ¹¹,$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return false; }
//vars
$valid_files = array();
//if files were passed in...
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$zip->addFile($file,$file);
}
//debug
//echo ¹The zip archive contains ¹,$zip->numFiles,¹ files with a status of ¹,$zip->status;

//close the zip -- done!
$zip->close();

//check to make sure the file exists
return file_exists($destination);
}
else
{
return false;
}
}
/***** Example Usage ***/
$files=array(¹file1.jpg¹, ¹file2.jpg¹, ¹file3.gif¹);
create_zip($files, ¹myzipfile.zip¹, true);


PHP解压缩 Zip 文件

/**********************
*@file - path to zip file
*@destination - destination directory for unzipped files
*/
function unzip_file($file, $destination){
// create object
$zip = new ZipArchive() ;
// open archive
if ($zip->open($file) !== TRUE) {
die (’Could not open archive’);
}
// extract contents to destination directory
$zip->extractTo($destination);
// close archive
$zip->close();
echo ¹Archive extracted to directory¹;
}

 

文章来源:侠客站长站(www.xkzzz.com) 详文参考:http://www.xkzzz.com/zz/netbc/php/201009/22-56339.html

PHP获取客户端真实IP地址

分类:PHP  来源:网络  时间:2011-3-12 20:20:59

该函数将获取用户的真实 IP 地址,即便他使用代理服务器。

function getRealIpAddr()
{
    if (!emptyempty($_SERVER[¹HTTP_CLIENT_IP¹]))
    {
        $ip=$_SERVER[¹HTTP_CLIENT_IP¹];
    }
    elseif (!emptyempty($_SERVER[¹HTTP_X_FORWARDED_FOR¹]))
    //to check ip is pass from proxy
    {
        $ip=$_SERVER[¹HTTP_X_FORWARDED_FOR¹];
    }
    else
    {
        $ip=$_SERVER[¹REMOTE_ADDR¹];
    }
    return $ip;
}

 

文章来源:侠客站长站(www.xkzzz.com) 详文参考:http://www.xkzzz.com/zz/netbc/php/201009/22-56345.html

PHP如何解析XML

分类:PHP  来源:网络  时间:2011-3-12 20:18:04

PHP解析XML数据

//xml string
$xml_string="<?xml version=¹1.0¹?>
<users>
<user id=¹398¹>
<name>Foo</name>
<email>foo@bar.com</name>
</user>
<user id=¹867¹>
<name>Foobar</name>
<email>foobar@foo.com</name>
</user>
</users>";

//load the xml string using simplexml
$xml = simplexml_load_string($xml_string);

//loop through the each node of user
foreach ($xml->user as $user)
{
//access attribute
echo $user[¹id¹], ¹ ¹;
//subnodes are accessed by -> operator
echo $user->name, ¹ ¹;
echo $user->email, ¹<br />¹;
}

 

文章来源:侠客站长站(www.xkzzz.com) 详文参考:http://www.xkzzz.com/zz/netbc/php/201009/22-56347.html

PHP反射机制代码示例

分类:PHP  来源:网络  时间:2011-3-12 20:16:02

演示用代码如下所示:

<?php
class ClassOne {
function callClassOne() {
print "In Class One";
}
}
class ClassOneDelegator {
private $targets;
function __construct() {
$this->target[] = new ClassOne();
}
function __call($name, $args) {
foreach ($this->target as $obj) {
$r = new ReflectionClass($obj);
if ($method = $r->getMethod($name)) {
if ($method->isPublic() && !$method->isAbstract()) {
return $method->invoke($obj, $args);
}
}
}
}
}
$obj = new ClassOneDelegator();
$obj->callClassOne();
?>


输出结果:
In Class One
可见,通过代理类ClassOneDelegator来代替ClassOne类来实现他的方法。
同样的,如下的代码也是能够运行的:

<?php
class ClassOne {
function callClassOne() {
print "In Class One";
}
}
class ClassOneDelegator {
private $targets;
function addObject($obj) {
$this->target[] = $obj;
}
function __call($name, $args) {
foreach ($this->target as $obj) {
$r = new ReflectionClass($obj);
if ($method = $r->getMethod($name)) {
if ($method->isPublic() && !$method->isAbstract()) {
return $method->invoke($obj, $args);
}
}
}
}
}
$obj = new ClassOneDelegator();
$obj->addObject(new ClassOne());
$obj->callClassOne();
?>

PHP中TEA算法的实现

分类:PHP  来源:网络  时间:2011-3-12 12:06:08

算法简单,而且效率高,每次可以操作8个字节的数据,加密解密的KEY为16字节,即包含4个int数据的int型数组,加密轮数应为8的倍数,一般比较常用的轮数为64,32,16,QQ原来就是用TEA16来还原密码的.

TEA算法
核心为:

 

#include <stdint.h>

void encrypt (uint32_t* v, uint32_t* k) {
    uint32_t v0=v[0], v1=v[1], sum=0, i;           /* set up */
    uint32_t delta=0x9e3779b9;                     /* a key schedule constant */
    uint32_t k0=k[0], k1=k[1], k2=k[2], k3=k[3];   /* cache key */
    for (i=0; i < 32; i++) {                       /* basic cycle start */
        sum += delta;
        v0 += ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1);
        v1 += ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3); 
    }                                              /* end cycle */
    v[0]=v0; v[1]=v1;
}

void decrypt (uint32_t* v, uint32_t* k) {
    uint32_t v0=v[0], v1=v[1], sum=0xC6EF3720, i;  /* set up */
    uint32_t delta=0x9e3779b9;                     /* a key schedule constant */
    uint32_t k0=k[0], k1=k[1], k2=k[2], k3=k[3];   /* cache key */
    for (i=0; i<32; i++) {                         /* basic cycle start */
        v1 -= ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3);
        v0 -= ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1);
        sum -= delta;                                  
    }                                              /* end cycle */
    v[0]=v0; v[1]=v1;
}

 

PHP部分代码非我原创,大家可以了解一下这方面的知识

<?php
$date = ¹8345354023476-3434¹;
$key = ¹12345¹;
$t = new tea ( );
$tea = $t->encrypt ( $date, $key );
$eetea = $t->decrypt ( $tea, $key );
var_dump ( $tea );
var_dump ( $eetea );
class tea {
    private $a, $b, $c, $d;
    private $n_iter;
    public function __construct() {
        $this->setIter ( 32 );
    }
    private function setIter($n_iter) {
        $this->n_iter = $n_iter;
    }
    private function getIter() {
        return $this->n_iter;
    }
    public function encrypt($data, $key) {
        // resize data to 32 bits (4 bytes)
        $n = $this->_resize ( $data, 4 );
       
        // convert data to long
        $data_long [0] = $n;
        $n_data_long = $this->_str2long ( 1, $data, $data_long );
       
        // resize data_long to 64 bits (2 longs of 32 bits)
        $n = count ( $data_long );
        if (($n & 1) == 1) {
            $data_long [$n] = chr ( 0 );
            $n_data_long ++;
        }
       
        // resize key to a multiple of 128 bits (16 bytes)
        $this->_resize ( $key, 16, true );
        if (¹¹ == $key)
            $key = ¹0000000000000000¹;
           
        // convert key to long
        $n_key_long = $this->_str2long ( 0, $key, $key_long );
       
        // encrypt the long data with the key
        $enc_data = ¹¹;
        $w = array (0, 0 );
        $j = 0;
        $k = array (0, 0, 0, 0 );
        for($i = 0; $i < $n_data_long; ++ $i) {
            // get next key part of 128 bits
            if ($j + 4 <= $n_key_long) {
                $k [0] = $key_long [$j];
                $k [1] = $key_long [$j + 1];
                $k [2] = $key_long [$j + 2];
                $k [3] = $key_long [$j + 3];
            } else {
                $k [0] = $key_long [$j % $n_key_long];
                $k [1] = $key_long [($j + 1) % $n_key_long];
                $k [2] = $key_long [($j + 2) % $n_key_long];
                $k [3] = $key_long [($j + 3) % $n_key_long];
            }
            $j = ($j + 4) % $n_key_long;
           
            $this->_encipherLong ( $data_long [$i], $data_long [++ $i], $w, $k );
           
            // append the enciphered longs to the result
            $enc_data .= $this->_long2str ( $w [0] );
            $enc_data .= $this->_long2str ( $w [1] );
        }
       
        return $enc_data;
    }
    public function decrypt($enc_data, $key) {
        // convert data to long
        $n_enc_data_long = $this->_str2long ( 0, $enc_data, $enc_data_long );
       
        // resize key to a multiple of 128 bits (16 bytes)
        $this->_resize ( $key, 16, true );
        if (¹¹ == $key)
            $key = ¹0000000000000000¹;
           
        // convert key to long
        $n_key_long = $this->_str2long ( 0, $key, $key_long );
       
        // decrypt the long data with the key
        $data = ¹¹;
        $w = array (0, 0 );
        $j = 0;
        $len = 0;
        $k = array (0, 0, 0, 0 );
        $pos = 0;
       
        for($i = 0; $i < $n_enc_data_long; $i += 2) {
            // get next key part of 128 bits
            if ($j + 4 <= $n_key_long) {
                $k [0] = $key_long [$j];
                $k [1] = $key_long [$j + 1];
                $k [2] = $key_long [$j + 2];
                $k [3] = $key_long [$j + 3];
            } else {
                $k [0] = $key_long [$j % $n_key_long];
                $k [1] = $key_long [($j + 1) % $n_key_long];
                $k [2] = $key_long [($j + 2) % $n_key_long];
                $k [3] = $key_long [($j + 3) % $n_key_long];
            }
            $j = ($j + 4) % $n_key_long;
           
            $this->_decipherLong ( $enc_data_long [$i], $enc_data_long [$i + 1], $w, $k );
           
            // append the deciphered longs to the result data (remove padding)
            if (0 == $i) {
                $len = $w [0];
                if (4 <= $len) {
                    $data .= $this->_long2str ( $w [1] );
                } else {
                    $data .= substr ( $this->_long2str ( $w [1] ), 0, $len % 4 );
                }
            } else {
                $pos = ($i - 1) * 4;
                if ($pos + 4 <= $len) {
                    $data .= $this->_long2str ( $w [0] );
                   
                    if ($pos + 8 <= $len) {
                        $data .= $this->_long2str ( $w [1] );
                    } elseif ($pos + 4 < $len) {
                        $data .= substr ( $this->_long2str ( $w [1] ), 0, $len % 4 );
                    }
                } else {
                    $data .= substr ( $this->_long2str ( $w [0] ), 0, $len % 4 );
                }
            }
        }
        return $data;
    }
    private function _encipherLong($y, $z, &$w, &$k) {
        $sum = ( integer ) 0;
        $delta = 0x9E3779B9;
        $n = ( integer ) $this->n_iter;
       
        while ( $n -- > 0 ) {
                       //C v0 += ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1);
                       //C v1 += ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3); 
            $sum = $this->_add ( $sum, $delta );
            $y = $this->_add ( $y, $this->_add ( ($z << 4),$this->a) ^ $this->_add($z , $sum) ^ $this->_add($this->_rshift ( $z, 5 ), $this->b )  );
            $z = $this->_add ( $z, $this->_add ( ($y << 4),$this->a) ^ $this->_add($y , $sum) ^ $this->_add($this->_rshift ( $y, 5 ), $this->b )  );
        }
       
        $w [0] = $y;
        $w [1] = $z;
    }
    private function _decipherLong($y, $z, &$w, &$k) {
        // sum = delta<<5, in general sum = delta * n
        $sum = 0xC6EF3720;
        $delta = 0x9E3779B9;
        $n = ( integer ) $this->n_iter;
       
        while ( $n -- > 0 ) {
                    //C v1 -= ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3);
                    //C v0 -= ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1);
            $z = $this->_add ( $z, -($this->_add ( ($y << 4),$this->a) ^ $this->_add($y , $sum) ^ $this->_add($this->_rshift ( $y, 5 ), $this->b ) ) );
            $y = $this->_add ( $y, - ($this->_add ( ($z << 4),$this->a) ^ $this->_add($z , $sum) ^ $this->_add($this->_rshift ( $z, 5 ), $this->b ) ) );
            $sum = $this->_add ( $sum, - $delta );
            }
       
        $w [0] = $y;
        $w [1] = $z;
    }
    private function _resize(&$data, $size, $nonull = false) {
        $n = strlen ( $data );
        $nmod = $n % $size;
        if (0 == $nmod)
            $nmod = $size;
       
        if ($nmod > 0) {
            if ($nonull) {
                for($i = $n; $i < $n - $nmod + $size; ++ $i) {
                    $data [$i] = $data [$i % $n];
                }
            } else {
                for($i = $n; $i < $n - $nmod + $size; ++ $i) {
                    $data [$i] = chr ( 0 );
                }
            }
        }
        return $n;
    }
    private function _hex2bin($str) {
        $len = strlen ( $str );
        return pack ( ¹H¹ . $len, $str );
    }
    private function _str2long($start, &$data, &$data_long) {
        $n = strlen ( $data );
       
        $tmp = unpack ( ¹N*¹, $data );
        $j = $start;
       
        foreach ( $tmp as $value )
            $data_long [$j ++] = $value;
       
        return $j;
    }
    private function _long2str($l) {
        return pack ( ¹N¹, $l );
    }
   
   
    private function _rshift($integer, $n) {
        // convert to 32 bits
        if (0xffffffff < $integer || - 0xffffffff > $integer) {
            $integer = fmod ( $integer, 0xffffffff + 1 );
        }
       
        // convert to unsigned integer
        if (0x7fffffff < $integer) {
            $integer -= 0xffffffff + 1.0;
        } elseif (- 0x80000000 > $integer) {
            $integer += 0xffffffff + 1.0;
        }
       
        // do right shift
        if (0 > $integer) {
            $integer &= 0x7fffffff; // remove sign bit before shift
            $integer >>= $n; // right shift
            $integer |= 1 << (31 - $n); // set shifted sign bit
        } else {
            $integer >>= $n; // use normal right shift
        }
       
        return $integer;
    }
    private function _add($i1, $i2) {
        $result = 0.0;
       
        foreach ( func_get_args () as $value ) {
            // remove sign if necessary
            if (0.0 > $value) {
                $value -= 1.0 + 0xffffffff;
            }
           
            $result += $value;
        }
       
        // convert to 32 bits
        if (0xffffffff < $result || - 0xffffffff > $result) {
            $result = fmod ( $result, 0xffffffff + 1 );
        }
       
        // convert to signed integer
        if (0x7fffffff < $result) {
            $result -= 0xffffffff + 1.0;
        } elseif (- 0x80000000 > $result) {
            $result += 0xffffffff + 1.0;
        }
       
        return $result;
    }
   
// }}}
}
?>

上面的是TEA的算法,XTEA的算法为:

那PHP中只需要把运算的位置改下就OK

    private function _teaencipherLong($y, $z, &$w, &$k) {
        $sum = ( integer ) 0;
        $delta = 0x9E3779B9;
        $n = ( integer ) $this->n_iter;
       
        while ( $n -- > 0 ) {
            $y = $this->_add ( $y, $this->_add ( $z << 4 ^ $this->_rshift ( $z, 5 ), $z ) ^ $this->_add ( $sum, $k [$sum & 3] ) );
            $sum = $this->_add ( $sum, $delta );
            $z = $this->_add ( $z, $this->_add ( $y << 4 ^ $this->_rshift ( $y, 5 ), $y ) ^ $this->_add ( $sum, $k [$this->_rshift ( $sum, 11 ) & 3] ) );
        }
       
        $w [0] = $y;
        $w [1] = $z;
    }   
    private function _decipherLong($y, $z, &$w, &$k) {
        // sum = delta<<5, in general sum = delta * n
        $sum = 0xC6EF3720;
        $delta = 0x9E3779B9;
        $n = ( integer ) $this->n_iter;
       
        while ( $n -- > 0 ) {
            $z = $this->_add ( $z, - ($this->_add ( $y << 4 ^ $this->_rshift ( $y, 5 ), $y ) ^ $this->_add ( $sum, $k [$this->_rshift ( $sum, 11 ) & 3] )) );
            $sum = $this->_add ( $sum, - $delta );
            $y = $this->_add ( $y, - ($this->_add ( $z << 4 ^ $this->_rshift ( $z, 5 ), $z ) ^ $this->_add ( $sum, $k [$sum & 3] )) );
        }
       
        $w [0] = $y;
        $w [1] = $z;
    }

XXTEA的算法
核心为

 

#define MX (z>>5^y<<2) + (y>>3^z<<4)^(sum^y) + (k[p&3^e]^z);

  long btea(long* v, long n, long* k) {
    unsigned long z=v[n-1], y=v[0], sum=0, e, DELTA=0x9e3779b9;
    long p, q ;
    if (n > 1) {          /* Coding Part */
      q = 6 + 52/n;
      while (q-- > 0) {
        sum += DELTA;
        e = (sum >> 2) & 3;
        for (p=0; p<n-1; p++) y = v[p+1], z = v[p] += MX;
        y = v[0];
        z = v[n-1] += MX;
      }
      return 0 ;
    } else if (n < -1) {  /* Decoding Part */
      n = -n;
      q = 6 + 52/n;
      sum = q*DELTA ;
      while (sum != 0) {
        e = (sum >> 2) & 3;
        for (p=n-1; p>0; p--) z = v[p-1], y = v[p] -= MX;
        z = v[n-1];
        y = v[0] -= MX;
        sum -= DELTA;
      }
      return 0;
    }
    return 1;
 

#include <stdint.h>

void encipher(unsigned int num_rounds, uint32_t v[2], uint32_t const k[4]) {
    unsigned int i;
    uint32_t v0=v[0], v1=v[1], sum=0, delta=0x9E3779B9;
    for (i=0; i < num_rounds; i++) {
        v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + k[sum & 3]);
        sum += delta;
        v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + k[(sum>>11) & 3]);
    }
    v[0]=v0; v[1]=v1;
}

void decipher(unsigned int num_rounds, uint32_t v[2], uint32_t const k[4]) {
    unsigned int i;
    uint32_t v0=v[0], v1=v[1], delta=0x9E3779B9, sum=delta*num_rounds;
    for (i=0; i < num_rounds; i++) {
        v1 &#8722;= (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + k[(sum>>11) & 3]);
        sum &#8722;= delta;
        v0 &#8722;= (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + k[sum & 3]);
    }
    v[0]=v0; v[1]=v1;
}

PHP正则表达式全集

分类:PHP  来源:网络  时间:2011-3-9 0:00:55
中国电话号码验证 
匹配形式如:0511-4405222 或者021-87888822 或者 021-44055520-555 或者 (0511)4405222 
正则表达式 "((d{3,4})|d{3,4}-)?d{7,8}(-d{3})*" 
中国邮政编码验证 
匹配形式如:215421 
正则表达式 "d{6}" 
电子邮件验证 
匹配形式如:justali@justdn.com 
正则表达式 "w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*" 
身份证验证 
匹配形式如:15位或者18位身份证 
正则表达式 "d{18}|d{15}" 
常用数字验证 
正则表达式  
"d{n}" n为规定长度 
"d{n,m}" n到m的长度范围 
非法字符验证 
匹配非法字符如:< > & / ¹ |  
正则表达式 [^<>&/|¹]+ 
日期验证 
匹配形式如:20030718,030718 
范围:1900--2099 
正则表达式((((19){1}|(20){1})d{2})|d{2})[01]{1}d{1}[0-3]{1}d{1}
正则表达式是一个好东西,但是一般情况下,我们需要验证的内容少之又少。下面是常用的17种正则表达式:
"^d+$"  //非负整数(正整数 + 0) 
"^[0-9]*[1-9][0-9]*$"  //正整数 
"^((-d+)|(0+))$"  //非正整数(负整数 + 0) 
"^-[0-9]*[1-9][0-9]*$"  //负整数 
"^-?d+$"    //整数 
"^d+(.d+)?$"  //非负浮点数(正浮点数 + 0) 
"^(([0-9]+.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*.[0-9]+)|([0-9]*[1-9][0-9]*))$"  //正浮点数 
"^((-d+(.d+)?)|(0+(.0+)?))$"  //非正浮点数(负浮点数 + 0) 
"^(-(([0-9]+.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*.[0-9]+)|([0-9]*[1-9][0-9]*)))$"  //负浮点数 
"^(-?d+)(.d+)?$"  //浮点数 
"^[A-Za-z]+$"  //由26个英文字母组成的字符串 
"^[A-Z]+$"  //由26个英文字母的大写组成的字符串 
"^[a-z]+$"  //由26个英文字母的小写组成的字符串 
"^[A-Za-z0-9]+$"  //由数字和26个英文字母组成的字符串 
"^w+$"  //由数字、26个英文字母或者下划线组成的字符串 
"^[w-]+(.[w-]+)*@[w-]+(.[w-]+)+$"    //email地址 
"^[a-zA-z]+://(w+(-w+)*)(.(w+(-w+)*))*(?S*)?$"  //url
[code]电子邮件 : @"^w+((-w+)|(.w+))*@w+((.|-)w+)*.w+$"
HTTP URL : @"^[url]http://([/url][w-]+.)+[w-]+(/[w- ./?%&=]*)?";
邮编 : @"d{6}"
身份证 : @"d{18}|d{15}"
整数 : @"^d{1,}$"
数值 : @"^-?(0|d+)(.d+)?$"
日期 : @"^(?:(?:(?:(?:1[6-9]|[2-9]d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(/|-|.)(?:0?21(?:29))$)|(?:(?:1[6-9]|[2-9]d)?d{2})(/|-|.)(?:(?:(?:0?[13578]|1[02])2(?:31))|(?:(?:0?[1,3-9]|1[0-2])2(29|30))|(?:(?:0?[1-9])|(?:1[0-2]))2(?:0?[1-9]|1d|2[0-8]))$"
合法的用户名(以字母开头,长度不小于4) : @"(([a-zA-Z]){1})+(w{3,29})"[/code]
<="">[code]常用正则表达式语法例句 
这里有一些可能会遇到的正则表达式示例: 
/^[  ]*$/ "^[  ]*$" 匹配一个空白行。 
/d{2}-d{5}/ "d{2}-d{5}" 验证一个ID号码是否由一个2位字,一 
个连字符以及一个5位数字组成。 
/<(.*)>.*</1>/ "<(.*)>.*</1>" 匹配一个 HTML 标记。 
下表是元字符及其在正则表达式上下文中的行为的一个完整列表: 
字符 描述 
 将下一个字符标记为一个特殊字符、或一个原义字符、或一个 后 
向引用、或一个八进制转义符。例如,¹n¹ 匹配字符 "n"。¹ ¹ 
匹配一个换行符。序列 ¹\¹ 匹配 "" 而 "(" 则匹配 "("。 
^ 匹配输入字符串的开始位置。如果设置了 RegExp 对象的 
Multiline 属性,^ 也匹配 ¹ ¹ 或 ¹ ¹ 之后的位置。 
$ 匹配输入字符串的结束位置。如果设置了 RegExp 对象的 
Multiline 属性,$ 也匹配 ¹ ¹ 或 ¹ ¹ 之前的位置。 
* 匹配前面的子表达式零次或多次。例如,zo* 能匹配 "z" 以及 
"zoo"。 * 等价于{0,}。 
+ 匹配前面的子表达式一次或多次。例如,¹zo+¹ 能匹配 "zo" 以 
及 "zoo",但不能匹配 "z"。+ 等价于 {1,}。 
? 匹配前面的子表达式零次或一次。例如,"do(es)?" 可以匹配 
"do" 或 "does" 中的"do" 。? 等价于 {0,1}。 
{n} n 是一个非负整数。匹配确定的 n 次。例如,¹o{2}¹ 不能匹配 
"Bob" 中的 ¹o¹,但是能匹配 "food" 中的两个 o。 
{n,} n 是一个非负整数。至少匹配n 次。例如,¹o{2,}¹ 不能匹配 
"Bob" 中的 ¹o¹,但能匹配 "foooood" 中的所有 o。¹o{1,}¹ 
等价于 ¹o+¹。¹o{0,}¹ 则等价于 ¹o*¹。 
{n,m} m 和 n 均为非负整数,其中n <= m。最少匹配 n 次且最多匹 
配 m 次。刘, "o{1,3}" 将匹配 "fooooood" 中的前三个o。 
¹o{0,1}¹等价于¹o?¹。请注意在逗号和两个数之间不能有空格 
? 当该字符紧跟在任何一个其他限制符 (*, +, ?, {n}, {n,}, 
{n,m}) 后面时,匹配模式是非贪婪的。非贪婪模式尽可能少的 
匹配所搜索的字符串,而默认的贪婪模式则尽可能多的匹配所搜 
索的字符串。例如,对于字符串 "oooo",¹o+?¹ 将匹配单个 
"o",而 ¹o+¹ 将匹配所有 ¹o¹。 
. 匹配除 " " 之外的任何单个字符。要匹配包括 ¹ ¹ 在内的任 
何字符,请使用象 ¹[. ]¹ 的模式。 
(pattern) 匹配pattern 并获取这一匹配。所获取的匹配可以从产生的 
Matches 集合得到,在VBScript 中使用 SubMatches 集合,在 
Visual Basic Scripting Edition 中则使用 $0…$9 属性。要 
匹配圆括号字符,请使用 ¹(¹ 或 ¹)¹。 
(?:pattern) 匹配 pattern 但不获取匹配结果,也就是说这是一个非获取匹 
配,不进行存储供以后使用。这在使用 "或" 字符 (|) 来组合 
一个模式的各个部分是很有用。例如, ¹industr(?:y|ies) 就 
是一个比 ¹industry|industries¹ 更简略的表达式。 
(?=pattern) 正向预查,在任何匹配 pattern 的字符串开始处匹配查找字符 
串。这是一个非获取匹配,也就是说,该匹配不需要获取供以后 
使用。例如,¹Windows (?=95|98|NT|2000)¹ 能匹配"Windows 
2000"中的"Windows",但不能匹配"Windows3 .1"中"Windows"。 
预查不消耗字符,也就是说,在一个匹配发生后,在最后一次匹 
配之后立即开始下一次匹配的搜索,而不是从包含预查的字符之 
后开始。 
(?!pattern) 负向预查,在任何不匹配Negative lookahead matches the 
search string at any point where a string not matching 
pattern 的字符串开始处匹配查找字符串。这是一个非获取匹 
配,也就是说,该匹配不需要获取供以后使用。例如¹Windows 
(?!95|98|NT|2000)¹ 能匹配 "Windows 3.1" 中的 "Windows", 
但不能匹配 "Windows 2000" 中的 "Windows"。预查不消耗字 
符,也就是说,在一个匹配发生后,在最后一次匹配之后立即开 
始下一次匹配的搜索,而不是从包含预查的字符之后开始 
x|y 匹配 x 或 y。例如,¹z|food¹ 能匹配 "z" 或 "food"。¹(z|f) 
ood¹ 则匹配 "zood" 或 "food"。 
[xyz] 字符集合。匹配所包含的任意一个字符。例如, ¹[abc]¹ 可以 
匹配 "plain" 中的 ¹a¹。 
[^xyz] 负值字符集合。匹配未包含的任意字符。例如, ¹[^abc]¹ 可以 
匹配 "plain" 中的¹p¹。 
[a-z] 字符范围。匹配指定范围内的任意字符。例如,¹[a-z]¹ 可以匹 
配 ¹a¹ 到 ¹z¹ 范围内的任意小写字母字符。 
[^a-z] 负值字符范围。匹配任何不在指定范围内的任意字符。例如, 
¹[^a-z]¹ 可以匹配任何不在 ¹a¹ 到 ¹z¹ 范围内的任意字符。 
 匹配一个单词边界,也就是指单词和空格间的位置。例如, 
¹er¹ 可以匹配"never" 中的 ¹er¹,但不能匹配 "verb" 中 
的 ¹er¹。 
B 匹配非单词边界。¹erB¹ 能匹配 "verb" 中的 ¹er¹,但不能匹 
配 "never" 中的 ¹er¹。 
cx 匹配由x指明的控制字符。例如, cM 匹配一个 Control-M 或 
回车符。 x 的值必须为 A-Z 或 a-z 之一。否则,将 c 视为一 
个原义的 ¹c¹ 字符。 
d 匹配一个数字字符。等价于 [0-9]。 
D 匹配一个非数字字符。等价于 [^0-9]。 
f 匹配一个换页符。等价于 x0c 和 cL。 
 匹配一个换行符。等价于 x0a 和 cJ。 
 匹配一个回车符。等价于 x0d 和 cM。 
s 匹配任何空白字符,包括空格、制表符、换页符等等。等价于 
[ f v]。 
S 匹配任何非空白字符。等价于 [^ f v]。 
 匹配一个制表符。等价于 x09 和 cI。 
v 匹配一个垂直制表符。等价于 x0b 和 cK。 
w 匹配包括下划线的任何单词字符。等价于¹[A-Za-z0-9_]¹。 
W 匹配任何非单词字符。等价于 ¹[^A-Za-z0-9_]¹。 
xn 匹配 n,其中 n 为十六进制转义值。十六进制转义值必须为确 
定的两个数字长。例如, ¹x41¹ 匹配 "A"。¹x041¹ 则等价 
于 ¹x04¹ & "1"。正则表达式中可以使用 ASCII 编码。. 
um 匹配 num,其中num是一个正整数。对所获取的匹配的引用。 
例如,¹(.)1¹ 匹配两个连续的相同字符。 
 标识一个八进制转义值或一个后向引用。如果   之前至少 n 
个获取的子表达式,则 n 为后向引用。否则,如果 n 为八进制 
数字 (0-7),则 n 为一个八进制转义值。 
m 标识一个八进制转义值或一个后向引用。如果  m 之前至少有 
is preceded by at least nm 个获取得子表达式,则 nm 为后 
向引用。如果  m 之前至少有 n 个获取,则 n 为一个后跟文 
字 m 的后向引用。如果前面的条件都不满足,若 n 和 m 均为 
八进制数字 (0-7),则  m 将匹配八进制转义值 nm。 
ml 如果 n 为八进制数字 (0-3),且 m 和 l 均为八进制数字 (0- 
7),则匹配八进制转义值 nml。 
un 匹配 n,其中 n 是一个用四个十六进制数字表示的Unicode字 
符。例如, u00A9 匹配版权符号 (?)。 [/code]
[code]匹配中文字符的正则表达式: 
[u4e00-u9fa5]
匹配双字节字符(包括汉字在内):
[^x00-xff]
匹配空行的正则表达式:
[s| ]*
匹配HTML标记的正则表达式:
/<(.*)>.*</1>|<(.*) />/ 
匹配首尾空格的正则表达式:
(^s*)|(s*$) 
URL:
[url]http://([/url][w-]+.)+[w-]+(/[w- ./?%&=]*)?
Email:
w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*
中华人民共和国电话号码
((d{3})|d{3}-)?d{8}
中华人民共和国邮编
d{6}
门丁注册的id格式:2-12位,数字、字符、下划线(0-9,a-z,A-Z,_) 
^[0-9a-zA-Z]+(w){1,11}[/code]

PHP正则表达式的使用技巧

分类:PHP  来源:网络  时间:2011-2-24 14:50:30

PHP正则表达式主要用于字符串的模式分割、匹配、查找及替换操作。使用正则表达式在某些简单的环境下可能效率不高,因此如何更好的使用PHP正则表达式需要综合考虑。

PHP正则表达式的定义:

用于描述字符排列和匹配模式的一种语法规则。它主要用于字符串的模式分割、匹配、查找及替换操作。

PHP中的正则函数:

PHP中有两套正则函数,两者功能差不多,分别为:

一套是由PCRE(Perl Compatible Regular Expression)库提供的。使用“preg_”为前缀命名的函数;

一套由POSIX(Portable Operating System Interface of Unix )扩展提供的。使用以“ereg_”为前缀命名的函数;(POSIX的正则函数库,自PHP 5.3以后,就不在推荐使用,从PHP6以后,就将被移除)

由于POSIX正则即将推出历史舞台,并且PCRE和perl的形式差不多,更利于我们在perl和php之间切换,所以这里重点介绍PCRE正则的使用。

PCRE正则表达式

PCRE全称为Perl Compatible Regular Expression,意思是Perl兼容正则表达式。

在PCRE中,通常将模式表达式(即正则表达式)包含在两个反斜线“/”之间,如“/apple/”。

正则中重要的几个概念有:元字符、转义、模式单元(重复)、反义、引用和断言,这些概念都可以在文章[1]中轻松的理解和掌握。

常用的元字符(Meta-character):

元字符     说明

A       匹配字符串串首的原子

       匹配字符串串尾的原子

       匹配单词的边界     /is/   匹配头为is的字符串   /is/   匹配尾为is的字符串   /is/ 定界

B       匹配除单词边界之外的任意字符   /Bis/   匹配单词“This”中的“is”

d     匹配一个数字;等价于[0-9]

D     匹配除数字以外任何一个字符;等价于[^0-9]

w     匹配一个英文字母、数字或下划线;等价于[0-9a-zA-Z_]

W     匹配除英文字母、数字和下划线以外任何一个字符;等价于[^0-9a-zA-Z_]

s     匹配一个空白字符;等价于[f v]

S     匹配除空白字符以外任何一个字符;等价于[^f v]

f     匹配一个换页符等价于 x0c 或 cL

匹配一个换行符;等价于 x0a 或 cJ

匹配一个回车符等价于x0d 或 cM

     匹配一个制表符;等价于 x09或\cl

v     匹配一个垂直制表符;等价于x0b或ck

oNN   匹配一个八进制数字

xNN   匹配一个十六进制数字

cC    匹配一个控制字符

模式修正符(Pattern Modifiers):

模式修正符在忽略大小写、匹配多行中使用特别多,掌握了这一个修正符,往往能解决我们遇到的很多问题。

i     -可同时匹配大小写字母

M     -将字符串视为多行

S     -将字符串视为单行,换行符做普通字符看待,使“.”匹配任何字符

X     -模式中的空白忽略不计  

U     -匹配到最近的字符串

e     -将替换的字符串作为表达使用

格式:/apple/i匹配“apple”或“Apple”等,忽略大小写。     /i

PCRE的模式单元:

//1 提取第一位的属性

/^d{2} ([W])d{2}\1d{4}$匹配“12-31-2006”、“09/27/1996”、“86 01 4321”等字符串。但上述正则表达式不匹配“12/34-5678”的格式。这是因为模式“[W]”的结果“/”已经被存储。下个位置“1”引用 时,其匹配模式也是字符“/”。

当不需要存储匹配结果时使用非存储模式单元“(?:)”

例如/(?:a|b|c)(D|E|F)\1g/ 将匹配“aEEg”。在一些正则表达式中,使用非存储模式单元是必要的。否则,需要改变其后引用的顺序。上例还可以写成/(a|b|c)(C|E|F)2g/。

 

 

 

 

PCRE正则表达式函数:

preg_match()和preg_match_all()
preg_quote()
preg_split()
preg_grep()
preg_replace()

函数的具体使用,我们可以通过PHP手册来找到,下面分享一些平时积累的正则表达式:

匹配action属性

$str = ¹¹;
$match = ¹¹;
preg_match_all(¹/s+action="(?!http:)(.*?)"s/¹, $str, $match);
print_r($match);

在正则中使用回调函数

/**
* replace some string by callback function
*
*/
function callback_replace() {
$url = ¹http://esfang.house.sina.com.cn¹;
$str = ¹¹;
$str = preg_replace ( ¹/(?<=saction=")(?!http:)(.*?)(?="s)/e¹, ¹search($url, \1)¹, $str );

echo $str;
}

function search($url, $match){
return $url . ¹/¹ . $match;
}

带断言的正则匹配

$match = ¹¹;
$str = ¹xxxxxx.com.cn bold font
paragraph text

¹;
preg_match_all ( ¹/(?<=<(w{1})>).*(?=</1>)/¹, $str, $match );
echo "匹配没有属性的HTML标签中的内容:";
print_r ( $match );

替换HTML源码中的地址

$form_html = preg_replace ( ¹/(?<=saction="|ssrc="|shref=")(?!http:|javascript)(.*?)(?="s)/e¹, ¹add_url($url, ¹\1¹)¹, $form_html );

正则工具虽然强大,但是从效率和编写时间上来讲,有时可能没有explode来的直接,对于一些紧急或者要求不高的任务,简单、粗暴的方法也许更好。

对于preg和ereg之间的执行效率,曾看到文章说preg要更快一点,具体由于使用ereg的时候并不多,而且也要推出历史舞台了,再加个个人更偏好于PCRE的方式。

21个实用的PHP代码

分类:PHP  来源:网络  时间:2011-2-24 14:46:20

1. PHP可阅读随机字符串

此代码将创建一个可阅读的字符串,使其更接近词典中的单词,实用且具有密码验证功能。

/**************
*@length - length of random string (must be a multiple of 2)
**************/
function readable_random_string($length = 6){
    $conso=array("b","c","d","f","g","h","j","k","l",
    "m","n","p","r","s","t","v","w","x","y","z");
    $vocal=array("a","e","i","o","u");
    $password="";
    srand ((double)microtime()*1000000);
    $max = $length/2;
    for($i=1; $i<=$max; $i++)
    {
    $password.=$conso[rand(0,19)];
    $password.=$vocal[rand(0,4)];
    }
    return $password;
}

2. PHP生成一个随机字符串

如果不需要可阅读的字符串,使用此函数替代,即可创建一个随机字符串,作为用户的随机密码等。

/*************
*@l - length of random string
*/
function generate_rand($l){
  $c= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  srand((double)microtime()*1000000);
  for($i=0; $i<$l; $i++) {
      $rand.= $c[rand()%strlen($c)];
  }
  return $rand;
}

3. PHP编码电子邮件地址

使用此代码,可以将任何电子邮件地址编码为 html 字符实体,以防止被垃圾邮件程序收集。

function encode_email($email=¹info@domain.com¹, $linkText=¹Contact Us¹, $attrs =¹class="emailencoder"¹ )
{
    // remplazar aroba y puntos
    $email = str_replace(¹@¹, ¹&#64;¹, $email);
    $email = str_replace(¹.¹, ¹&#46;¹, $email);
    $email = str_split($email, 5); 

    $linkText = str_replace(¹@¹, ¹&#64;¹, $linkText);
    $linkText = str_replace(¹.¹, ¹&#46;¹, $linkText);
    $linkText = str_split($linkText, 5); 

    $part1 = ¹<a href="ma¹;
    $part2 = ¹ilto&#58;¹;
    $part3 = ¹" ¹. $attrs .¹ >¹;
    $part4 = ¹</a>¹; 

    $encoded = ¹<script type="text/javascript">¹;
    $encoded .= "document.write(¹$part1¹);";
    $encoded .= "document.write(¹$part2¹);";
    foreach($email as $e)
    {
            $encoded .= "document.write(¹$e¹);";
    }
    $encoded .= "document.write(¹$part3¹);";
    foreach($linkText as $l)
    {
            $encoded .= "document.write(¹$l¹);";
    }
    $encoded .= "document.write(¹$part4¹);";
    $encoded .= ¹</script>¹; 

    return $encoded;
}

4. PHP验证邮件地址

电子邮件验证也许是中最常用的网页表单验证,此代码除了验证电子邮件地址,也可以选择检查邮件域所属 DNS 中的 MX 记录,使邮件验证功能更加强大。

function is_valid_email($email, $test_mx = false)
{
    if(eregi("^([_a-z0-9-]+)(.[_a-z0-9-]+)*@([a-z0-9-]+)(.[a-z0-9-]+)*(.[a-z]{2,4})$", $email))
        if($test_mx)
        {
            list($username, $domain) = split("@", $email);
            return getmxrr($domain, $mxrecords);
        }
        else
            return true;
    else
        return false;
}

5. PHP列出目录内容

function list_files($dir)
{
    if(is_dir($dir))
    {
        if($handle = opendir($dir))
        {
            while(($file = readdir($handle)) !== false)
            {
                if($file != "." && $file != ".." && $file != "Thumbs.db")
                {
                    echo ¹<a target="_blank" href="¹.$dir.$file.¹">¹.$file.¹</a><br>¹." ";
                }
            }
            closedir($handle);
        }
    }
}

6. PHP销毁目录

删除一个目录,包括它的内容。

/*****
*@dir - Directory to destroy
*@virtual[optional]- whether a virtual directory
*/
function destroyDir($dir, $virtual = false)
{
    $ds = DIRECTORY_SEPARATOR;
    $dir = $virtual ? realpath($dir) : $dir;
    $dir = substr($dir, -1) == $ds ? substr($dir, 0, -1) : $dir;
    if (is_dir($dir) && $handle = opendir($dir))
    {
        while ($file = readdir($handle))
        {
            if ($file == ¹.¹ || $file == ¹..¹)
            {
                continue;
            }
            elseif (is_dir($dir.$ds.$file))
            {
                destroyDir($dir.$ds.$file);
            }
            else
            {
                unlink($dir.$ds.$file);
            }
        }
        closedir($handle);
        rmdir($dir);
        return true;
    }
    else
    {
        return false;
    }
}

7. PHP解析 JSON 数据

与大多数流行的 Web 服务如 twitter 通过开放 API 来提供数据一样,它总是能够知道如何解析 API 数据的各种传送格式,包括 JSON,XML 等等。

$json_string=¹{"id":1,"name":"foo","email":"foo@foobar.com","interest":["wordpress","php"]} ¹;
$obj=json_decode($json_string);
echo $obj->name; //prints foo
echo $obj->interest[1]; //prints php

8. PHP解析 XML 数据

 

//xml string
$xml_string="<?xml version=¹1.0¹?>
<users>
<user id=¹398¹>
<name>Foo</name>
<email>foo@bar.com</name>
</user>
<user id=¹867¹>
<name>Foobar</name>
<email>foobar@foo.com</name>
</user>
</users>";

//load the xml string using simplexml
$xml = simplexml_load_string($xml_string);

//loop through the each node of user
foreach ($xml->user as $user)
{
//access attribute
echo $user[¹id¹], ¹ ¹;
//subnodes are accessed by -> operator
echo $user->name, ¹ ¹;
echo $user->email, ¹<br />¹;
}

 

9. PHP创建日志缩略名

创建用户友好的日志缩略名。

 

function create_slug($string){
$slug=preg_replace(¹/[^A-Za-z0-9-]+/¹, ¹-¹, $string);
return $slug;
}

 

10. PHP获取客户端真实 IP 地址

该函数将获取用户的真实 IP 地址,即便他使用代理服务器。

 

function getRealIpAddr()
{
    if (!emptyempty($_SERVER[¹HTTP_CLIENT_IP¹]))
    {
        $ip=$_SERVER[¹HTTP_CLIENT_IP¹];
    }
    elseif (!emptyempty($_SERVER[¹HTTP_X_FORWARDED_FOR¹]))
    //to check ip is pass from proxy
    {
        $ip=$_SERVER[¹HTTP_X_FORWARDED_FOR¹];
    }
    else
    {
        $ip=$_SERVER[¹REMOTE_ADDR¹];
    }
    return $ip;
}

 

11. PHP强制性文件下载

为用户提供强制性的文件下载功能。

 

/********************
*@file - path to file
*/
function force_download($file)
{
if ((isset($file))&&(file_exists($file))) {
header("Content-length: ".filesize($file));
header(¹Content-Type: application/octet-stream¹);
header(¹Content-Disposition: attachment; filename="¹ . $file . ¹"¹);
readfile("$file");
} else {
echo "No file selected";
}
}

 

12. PHP创建标签云

 

function getCloud( $data = array(), $minFontSize = 12, $maxFontSize = 30 )
{
$minimumCount = min( array_values( $data ) );
$maximumCount = max( array_values( $data ) );
$spread = $maximumCount - $minimumCount;
$cloudHTML = ¹¹;
$cloudTags = array();

$spread == 0 && $spread = 1;

foreach( $data as $tag => $count )
{
$size = $minFontSize + ( $count - $minimumCount )
* ( $maxFontSize - $minFontSize ) / $spread;
$cloudTags[] = ¹<a style="font-size: ¹ . floor( $size ) . ¹px¹
. ¹" href="#" title="¹¹ . $tag .
¹¹ returned a count of ¹ . $count . ¹">¹
. htmlspecialchars( stripslashes( $tag ) ) . ¹</a>¹;
}

return join( " ", $cloudTags ) . " ";
}
/**************************
**** Sample usage ***/
$arr = Array(¹Actionscript¹ => 35, ¹Adobe¹ => 22, ¹Array¹ => 44, ¹Background¹ => 43,
¹Blur¹ => 18, ¹Canvas¹ => 33, ¹Class¹ => 15, ¹Color Palette¹ => 11, ¹Crop¹ => 42,
¹Delimiter¹ => 13, ¹Depth¹ => 34, ¹Design¹ => 8, ¹Encode¹ => 12, ¹Encryption¹ => 30,
¹Extract¹ => 28, ¹Filters¹ => 42);
echo getCloud($arr, 12, 36);

 

13. PHP寻找两个字符串的相似性

PHP 提供了一个极少使用的 similar_text 函数,但此函数非常有用,用于比较两个字符串并返回相似程度的百分比。

 

similar_text($string1, $string2, $percent);
//$percent will have the percentage of similarity

 

14. PHP在应用程序中使用 Gravatar 通用头像

随着 WordPress 越来越普及,Gravatar 也随之流行。由于 Gravatar 提供了易于使用的 API,将其纳入应用程序也变得十分方便。

 

/******************
*@email - Email address to show gravatar for
*@size - size of gravatar
*@default - URL of default gravatar to use
*@rating - rating of Gravatar(G, PG, R, X)
*/
function show_gravatar($email, $size, $default, $rating)
{
echo ¹<img src="http://www.gravatar.com/avatar.php?gravatar_id=¹.md5($email).
¹&default=¹.$default.¹&size=¹.$size.¹&rating=¹.$rating.¹" width="¹.$size.¹px"
height="¹.$size.¹px" />¹;
}

 

15. PHP在字符断点处截断文字

所谓断字 (word break),即一个单词可在转行时断开的地方。这一函数将在断字处截断字符串。

 

// Original PHP code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
function myTruncate($string, $limit, $break=".", $pad="...") {
// return with no change if string is shorter than $limit
if(strlen($string) <= $limit)
return $string;

// is $break present between $limit and the end of the string?
if(false !== ($breakpoint = strpos($string, $break, $limit))) {
if($breakpoint < strlen($string) - 1) {
$string = substr($string, 0, $breakpoint) . $pad;
}
}
return $string;
}
/***** Example ****/
$short_string=myTruncate($long_string, 100, ¹ ¹);

 

16. PHP文件 Zip 压缩

 

/* creates a compressed zip file */
function create_zip($files = array(),$destination = ¹¹,$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return false; }
//vars
$valid_files = array();
//if files were passed in...
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$zip->addFile($file,$file);
}
//debug
//echo ¹The zip archive contains ¹,$zip->numFiles,¹ files with a status of ¹,$zip->status;

//close the zip -- done!
$zip->close();

//check to make sure the file exists
return file_exists($destination);
}
else
{
return false;
}
}
/***** Example Usage ***/
$files=array(¹file1.jpg¹, ¹file2.jpg¹, ¹file3.gif¹);
create_zip($files, ¹myzipfile.zip¹, true);

 

17. PHP解压缩 Zip 文件

 

/**********************
*@file - path to zip file
*@destination - destination directory for unzipped files
*/
function unzip_file($file, $destination){
// create object
$zip = new ZipArchive() ;
// open archive
if ($zip->open($file) !== TRUE) {
die (’Could not open archive’);
}
// extract contents to destination directory
$zip->extractTo($destination);
// close archive
$zip->close();
echo ¹Archive extracted to directory¹;
}

 

18. PHP为 URL 地址预设 http 字符串

有时需要接受一些表单中的网址输入,但用户很少添加 http:// 字段,此代码将为网址添加该字段。

 

if (!preg_match("/^(http|ftp):/", $_POST[¹url¹])) {
   $_POST[¹url¹] = ¹http://¹.$_POST[¹url¹];
}

 

19. PHP将网址字符串转换成超级链接

该函数将 URL 和 E-mail 地址字符串转换为可点击的超级链接。

 

function makeClickableLinks($text) {
$text = eregi_replace(¹(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)¹,
¹<a href="1">1</a>¹, $text);
$text = eregi_replace(¹([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)¹,
¹1<a href="http://2">2</a>¹, $text);
$text = eregi_replace(¹([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})¹,
¹<a href="mailto:1">1</a>¹, $text);

return $text;
}

 

20. PHP调整图像尺寸

创建图像缩略图需要许多时间,此代码将有助于了解缩略图的逻辑。

 

/**********************
*@filename - path to the image
*@tmpname - temporary path to thumbnail
*@xmax - max width
*@ymax - max height
*/
function resize_image($filename, $tmpname, $xmax, $ymax)
{
    $ext = explode(".", $filename);
    $ext = $ext[count($ext)-1]; 

    if($ext == "jpg" || $ext == "jpeg")
        $im = imagecreatefromjpeg($tmpname);
    elseif($ext == "png")
        $im = imagecreatefrompng($tmpname);
    elseif($ext == "gif")
        $im = imagecreatefromgif($tmpname); 

    $x = imagesx($im);
    $y = imagesy($im); 

    if($x <= $xmax && $y <= $ymax)
        return $im; 

    if($x >= $y) {
        $newx = $xmax;
        $newy = $newx * $y / $x;
    }
    else {
        $newy = $ymax;
        $newx = $x / $y * $newy;
    } 

    $im2 = imagecreatetruecolor($newx, $newy);
    imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);
    return $im2;
}

 

21. PHP检测 ajax 请求

大多数的 JavaScript 框架如 jquery,Mootools 等,在发出 Ajax 请求时,都会发送额外的 HTTP_X_REQUESTED_WITH 头部信息,头当他们一个ajax请求,因此你可以在服务器端侦测到 Ajax 请求。

 

if(!emptyempty($_SERVER[¹HTTP_X_REQUESTED_WITH¹]) && strtolower($_SERVER[¹HTTP_X_REQUESTED_WITH¹]) == ¹xmlhttprequest¹){
    //If AJAX Request Then
}else{
//something else
}

英文原稿:21 Really Useful & Handy PHP Code Snippets | Web Developer Plus

PHP加密解密算法

分类:PHP  来源:网络  时间:2011-2-24 14:41:13

最近学习URL跳转的时候新进三个超好用的PHP加密解密函数,貌似是discuz里的…使用这些加密解密的原因是因为有时自己的URL地址被人获取以后想破解你里面传值的内容就必须知道你的key,没有key,他应该要破了一阵子才能知道你URL里面的内容吧。

将它们打包成一个文件就叫fun.php吧

<?php
function passport_encrypt($txt, $key) {
srand((double)microtime() * 1000000);
$encrypt_key = md5(rand(0, 32000));
$ctr = 0;
$tmp = ¹¹;
for($i = 0;$i < strlen($txt); $i++) {
$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
$tmp .= $encrypt_key[$ctr].($txt[$i] ^ $encrypt_key[$ctr++]);
}
return base64_encode(passport_key($tmp, $key));
}

function passport_decrypt($txt, $key) {
$txt = passport_key(base64_decode($txt), $key);
$tmp = ¹¹;
for($i = 0;$i < strlen($txt); $i++) {
$md5 = $txt[$i];
$tmp .= $txt[++$i] ^ $md5;
}
return $tmp;
}

function passport_key($txt, $encrypt_key) {
$encrypt_key = md5($encrypt_key);
$ctr = 0;
$tmp = ¹¹;
for($i = 0; $i < strlen($txt); $i++) {
$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
$tmp .= $txt[$i] ^ $encrypt_key[$ctr++];
}
return $tmp;
}
?>

以下一些示例加深对这三个加密解密函数的理解

//string.php
<?php
include “fun.php”;

$txt = “This is a test”;
$key = “testkey”;
$encrypt = passport_encrypt($txt,$key);
$decrypt = passport_decrypt($encrypt,$key);

echo $txt.”<br><hr>”;
echo $encrypt.”<br><hr>”;
echo $decrypt.”<br><hr>”;
?>

//array.php
<?php
include “fun.php”;

$array = array(
"a" => "1",
"b" => "2",
"c" => "3",
"d" => "4"
);
//serialize产生一个可存储的值,返回一个字符串,unserialize还原
$txt = serialize($array);
$key = “testkey”;
$encrypt = passport_encrypt($txt,$key);
$decrypt = passport_decrypt($encrypt,$key);
$decryptArray = unserialize($decrypt);

echo $txt.”<br><hr>”;
echo $encrypt.”<br><hr>”;
echo $decrypt.”<br><hr>”;
echo $decryptArray.”<br><hr>”;
?>

关键的地方来了当你要跳转到另外一个网址,但又要保证你的session无误的时候,你需要对session作一个处理.貌似一个公司有一个网站又有一个论坛,两个地方都有注册和登录,但又不想让用户在主页登录后跳转到论坛的时候session失效,即是登录一次跑完整间公司

那要怎样来处理用户的session呢

网页都是无状态的,如果要在新的网页中继续使用session,则需要把session从一个地方移到另一个地方,可能有些人已经想到了,我可以通过url传址的方式来调用它.而PHP有个处理session的变量,叫$_SESSION.于是将需要注册的session转换成一个数组吧.那么,你可以这样写:

//login.php
<?php
session_start();
include “fun.php”;
$_SESSION[“userid”];
$_SESSION[“username”];
$_SESSION[“userpwd”];

header("Location: http://$domain/process.php?s=".urlencode(passport_encrypt(serialize($_SESSION),"sessionkey")));
?>

上例中先用serialize将$_SESSION变成可存储的数据,然后通过passport_encrypt将这个数据加密,加urlencode的原因是因为$_SESSION加密时,有可能会产生像料想不到的编码,所以以防万一(事实证明非常有效)

处理下

//process.php
<?php
session_start();
include “fun.php”;
$_SESSION=unserialize(passport_decrypt($_GET["s"],"sessionkey"));
header("Location: http://$domain/index.php");
?>

 

先用$_GET[“s”]获取URL的参数,然后用passport_decrypt将其解密,再用unserialize将其数据还原成原始数据,到了这步处理,你的网页就可能通过header自由跳转啦。

这种方法还涉及到安全性的问题,如果你的url地址在传址的过程中被人家获取的话,那就真的是不好意思了人家虽然可能破解不了url里边的内容,但人家也可以直接用这个url地址来登录你的一些个人账户啊,邮箱帐户啊甚至银行帐户(当然很少人会这样写,我例外,哈哈)听起来好怕.但其实你可以在跳转页面作取消session处理.

以下是加强版的process.php

<?php
session_start();
include_once "fun.php";
$_SESSION=unserialize(passport_decrypt($_GET["s"],"sessionkey"));
if((time()-$_SESSION["TIME"])>30){
header("Location: http://$domain/ login.php");
unset($_SESSION["USERNAME"]);
unset($_SESSION["PASSWORD"]);
}
else
header("Location: http://$domain/ index.php");
?>

写这个文件之前,你还要在登录那边设置

$_SESSION["TIME"] = time();

设置这个的原因主要是获取两边的时间,如果跳转的时候超过30秒的时候,你就可以让它跳转到login.php登录页面,网速慢的客户就不好意思啦但这也预防了如果此url被人获取,而这个人又没有在30秒内登录的话,那就不好意思啊,超时重新登录.

$_SESSION["USERNAME"]和$_SESSION["PASSWORD"] 这两个东东就是用户登录时需要输入的用户名和密码了.取消这两个session的原因就是因为如果你的url被人获取了,那个人虽然在超过30秒内跳转到loign.php的页面,但那些传过来的session依然有效,只要将url后缀login.php改为index.php.那他一样登录成功。