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;
}
文章来源:侠客站长站(www.xkzzz.com) 详文参考:http://www.xkzzz.com/zz/netbc/php/201009/22-56337.html
PHP Zip压缩和解压缩
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地址
该函数将获取用户的真实 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解析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
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算法的实现
算法简单,而且效率高,每次可以操作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 −= (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + k[(sum>>11) & 3]);
sum −= delta;
v0 −= (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + k[sum & 3]);
}
v[0]=v0; v[1]=v1;
}
PHP正则表达式全集
<="">[code]常用正则表达式语法例句
PHP正则表达式的使用技巧
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代码
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(¹@¹, ¹@¹, $email); $email = str_replace(¹.¹, ¹.¹, $email); $email = str_split($email, 5); $linkText = str_replace(¹@¹, ¹@¹, $linkText); $linkText = str_replace(¹.¹, ¹.¹, $linkText); $linkText = str_split($linkText, 5); $part1 = ¹<a href="ma¹; $part2 = ¹ilto:¹; $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 地址字符串转换为可点击的超级链接。
|
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加密解密算法
最近学习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.那他一样登录成功。
- 默认分类(20)
- J2EE(25)
- Java(56)
- PHP(55)
- SEO(10)
- 网页设计(20)
- 网站建设(37)
- 数据库(7)
- JavaScript(17)
- JQuery(6)
- MySQL(20)
- SQL Server(6)
- Access(1)
- Oracle(6)
- office(6)
- Dreamweaver(4)
- Photoshop(12)
- Flash(9)
- Fireworks(13)
- CSS(14)
- HTML(4)
- .NET(7)
- ASP(2)
- DB2(1)
- Ajax(2)
- Linux(12)
- Struts(7)
- Hibernate(8)
- Spring(2)
- Jsp(22)
- Asp(8)
- C#(3)
- C++(1)
- 网络安全(5)
- 软件工程(7)
- XML(1)
- English(2)
- 计算机等级考试(2)
- 计算机病毒(4)
- 个人日志(76)
- 互联网(15)
- ActionScript(10)
- Android(3)
- 数据结构与算法(1)
- 游戏策略(3)
- 美文翻译(2)
- 编程开发(19)
- 计算机应用(4)
- 计算机(10)
- Unity3d(6)
- 其他(1)
- egret(1)