当前位置:文档之家› 再来二十一段救命的PHP代码

再来二十一段救命的PHP代码

再来二十一段救命的PHP代码
再来二十一段救命的PHP代码

. PHP可阅读随机字符串此代码将创建一个可阅读的字符串,使其更接近词典中的单词,实用且具有密码验证功能。 /************** *@length-lengthofrandomstring(mustbeamultipleof2) **************/ function readable_random_string( $length =6){ $conso

1. PHP可阅读随机字符串

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

1/**************

2*@length - length of random string (must be a multiple of 2)

3**************/

4function readable_random_string($length = 6){

5$conso=array("b","c","d","f","g","h","j","k","l",

6"m","n","p","r","s","t","v","w","x","y","z");

7$vocal=array("a","e","i","o","u");

8$password="";

9srand ((double)microtime()*1000000);

10$max = $length/2;

11for($i=1; $i<=$max; $i++)

12{

13$password.=$conso[rand(0,19)];

14$password.=$vocal[rand(0,4)];

15}

16return $password;

17}

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

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

18/*************

19*@l - length of random string

20*/

21function generate_rand($l){

22$c= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

23srand((double)microtime()*1000000);

24for($i=0; $i<$l; $i++) {

25$rand.= $c[rand()%strlen($c)];

26}

27return $rand;

28}

3. PHP编码电子邮件地址

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

29function encode_email($email='info@https://www.doczj.com/doc/a2229987.html,', $linkText='Contact Us', $attrs ='class="emailencoder"' )

30{

31// remplazar aroba y puntos

32$email = str_replace('@', '@', $email);

33$email = str_replace('.', '.', $email);

34$email = str_split($email, 5);

35

36$linkText = str_replace('@', '@', $linkText);

37$linkText = str_replace('.', '.', $linkText);

38$linkText = str_split($linkText, 5);

39

40$part1 = '';

43$part4 = '';

44

45$encoded = '';

59

60return $encoded;

61}

4. PHP验证邮件地址

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

62function is_valid_email($email, $test_mx = false)

63{

64if(eregi("^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[ a-z]{2,4})$", $email))

65if($test_mx)

66{

67list($username, $domain) = split("@", $email);

68return getmxrr($domain, $mxrecords);

69}

70else

71return true;

72else

73return false;

74}

5. PHP列出目录内容

75function list_files($dir)

76{

77if(is_dir($dir))

78{

79if($handle = opendir($dir))

80{

81while(($file = readdir($handle)) !== false)

82{

83if($file != "." && $file != ".." && $file != "Thumbs.db")

84{

85echo ''.$file.'
'."\n"; 86}

87}

88closedir($handle);

89}

90}

91}

6. PHP销毁目录

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

92/*****

93*@dir - Directory to destroy

94*@virtual[optional]- whether a virtual directory

95*/

96function destroyDir($dir, $virtual = false)

97{

98$ds = DIRECTORY_SEPARATOR;

99$dir = $virtual ? realpath($dir) : $dir;

100$dir = substr($dir, -1) == $ds ? substr($dir, 0, -1) : $dir;

101if (is_dir($dir) && $handle = opendir($dir))

102{

103while ($file = readdir($handle))

104{

105if ($file == '.' || $file == '..')

106{

107continue;

108}

109elseif (is_dir($dir.$ds.$file))

110{

111destroyDir($dir.$ds.$file);

112}

113else

114{

115unlink($dir.$ds.$file);

116}

117}

118closedir($handle);

119rmdir($dir);

120return true;

121}

122else

123{

124return false;

125}

126}

7. PHP解析 JSON 数据

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

127$json_string='{"id":1,"name":"foo","email":"foo@https://www.doczj.com/doc/a2229987.html,","interest":[ "wordpress","php"]} ';

128$obj=json_decode($json_string);

129echo $obj->name; //prints foo

130echo $obj->interest[1]; //prints php

8. PHP解析 XML 数据

131//xml string

132$xml_string="

133

134

135Foo

136foo@https://www.doczj.com/doc/a2229987.html,

137

138

139Foobar

140foobar@https://www.doczj.com/doc/a2229987.html,

141

142";

143

144//load the xml string using simplexml

145$xml = simplexml_load_string($xml_string);

146

147//loop through the each node of user

148foreach ($xml->user as $user)

149{

150//access attribute

151echo $user['id'], ' ';

152//subnodes are accessed by -> operator

153echo $user->name, ' ';

154echo $user->email, '
';

155}

9. PHP创建日志缩略名

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

156function create_slug($string){

157$slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string); 158return $slug;

159}

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

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

160function getRealIpAddr()

161{

162if (!emptyempty($_SERVER['HTTP_CLIENT_IP']))

163{

164$ip=$_SERVER['HTTP_CLIENT_IP'];

165}

166elseif (!emptyempty($_SERVER['HTTP_X_FORWARDED_FOR'])) 167//to check ip is pass from proxy

168{

169$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];

170}

171else

172{

173$ip=$_SERVER['REMOTE_ADDR'];

174}

175return $ip;

176}

11. PHP强制性文件下载

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

177/********************

178*@file - path to file

179*/

180function force_download($file)

181{

182if ((isset($file))&&(file_exists($file))) {

183header("Content-length: ".filesize($file));

184header('Content-Type: application/octet-stream');

185header('Content-Disposition: attachment; filename="' . $file . '"');

186readfile("$file");

187} else {

188echo "No file selected";

189}

190}

12. PHP创建标签云

191function getCloud( $data = array(), $minFontSize = 12, $maxFontSize = 30 ) 192{

193$minimumCount = min( array_values( $data ) );

194$maximumCount = max( array_values( $data ) );

195$spread = $maximumCount - $minimumCount;

196$cloudHTML = '';

197$cloudTags = array();

198

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

200

201foreach( $data as $tag => $count )

202{

203$size = $minFontSize + ( $count - $minimumCount )

204* ( $maxFontSize - $minFontSize ) / $spread;

205$cloudTags[] = ''

208. htmlspecialchars( stripslashes( $tag ) ) . '';

209}

210

211return join( "\n", $cloudTags ) . "\n";

212}

213/**************************

214**** Sample usage ***/

215$arr = Array('Actionscript' => 35, 'Adobe' => 22, 'Array' => 44, 'Background' => 43,

216'Blur' => 18, 'Canvas' => 33, 'Class' => 15, 'Color Palette' => 11, 'Crop' => 42,

217'Delimiter' => 13, 'Depth' => 34, 'Design' => 8, 'Encode' => 12, 'Encryption' => 30,

218'Extract' => 28, 'Filters' => 42);

219echo getCloud($arr, 12, 36);

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

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

220similar_text($string1, $string2, $percent);

221//$percent will have the percentage of similarity

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

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

222/******************

223*@email - Email address to show gravatar for

224*@size - size of gravatar

225*@default - URL of default gravatar to use

226*@rating - rating of Gravatar(G, PG, R, X)

227*/

228function show_gravatar($email, $size, $default, $rating)

229{

230echo '

src="https://www.doczj.com/doc/a2229987.html,/avatar.php?gravatar_id='.md5($email).

231'&default='.$default.'&size='.$size.'&rating='.$rating.'"

width="'.$size.'px"

232height="'.$size.'px" />';

233}

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

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

234// Original PHP code by Chirp Internet: https://www.doczj.com/doc/a2229987.html,.au

235// Please acknowledge use of this code by including this header.

236function myTruncate($string, $limit, $break=".", $pad="...") {

237// return with no change if string is shorter than $limit

238if(strlen($string) <= $limit)

239return $string;

240

241// is $break present between $limit and the end of the string?

242if(false !== ($breakpoint = strpos($string, $break, $limit))) {

243if($breakpoint < strlen($string) - 1) {

244$string = substr($string, 0, $breakpoint) . $pad;

245}

246}

247return $string;

248}

249/***** Example ****/

250$short_string=myTruncate($long_string, 100, ' ');

16. PHP文件 Zip 压缩

251/* creates a compressed zip file */

252function create_zip($files = array(),$destination = '',$overwrite = false) {

253//if the zip file already exists and overwrite is false, return false 254if(file_exists($destination) && !$overwrite) { return false; }

255//vars

256$valid_files = array();

257//if files were passed in...

258if(is_array($files)) {

259//cycle through each file

260foreach($files as $file) {

261//make sure the file exists

262if(file_exists($file)) {

263$valid_files[] = $file;

264}

265}

266}

267//if we have good files...

268if(count($valid_files)) {

269//create the archive

270$zip = new ZipArchive();

271if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {

272return false;

273}

274//add the files

275foreach($valid_files as $file) {

276$zip->addFile($file,$file);

277}

278//debug

279//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;

280

281//close the zip -- done!

282$zip->close();

283

284//check to make sure the file exists

285return file_exists($destination);

286}

287else

288{

289return false;

290}

291}

292/***** Example Usage ***/

293$files=array('file1.jpg', 'file2.jpg', 'file3.gif');

294create_zip($files, 'myzipfile.zip', true);

17. PHP解压缩 Zip 文件

295/**********************

296*@file - path to zip file

297*@destination - destination directory for unzipped files

298*/

299function unzip_file($file, $destination){

300// create object

301$zip = new ZipArchive() ;

302// open archive

303if ($zip->open($file) !== TRUE) {

304die (’Could not open archive’);

305}

306// extract contents to destination directory

307$zip->extractTo($destination);

308// close archive

309$zip->close();

310echo 'Archive extracted to directory';

311}

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

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

312if (!preg_match("/^(http|ftp):/", $_POST['url'])) {

313$_POST['url'] = 'http://'.$_POST['url'];

314}

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

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

315function makeClickableLinks($text) {

316$text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)', 317'\1', $text);

318$text =

eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)',

319'\1\2', $text);

320$text = eregi_replace('([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})', 321'\1', $text);

322

323return $text;

324}

20. PHP调整图像尺寸

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

325/**********************

326*@filename - path to the image

327*@tmpname - temporary path to thumbnail

328*@xmax - max width

329*@ymax - max height

330*/

331function resize_image($filename, $tmpname, $xmax, $ymax)

332{

333$ext = explode(".", $filename);

334$ext = $ext[count($ext)-1];

335

336if($ext == "jpg" || $ext == "jpeg")

337$im = imagecreatefromjpeg($tmpname);

338elseif($ext == "png")

339$im = imagecreatefrompng($tmpname);

340elseif($ext == "gif")

341$im = imagecreatefromgif($tmpname);

342

343$x = imagesx($im);

344$y = imagesy($im);

345

346if($x <= $xmax && $y <= $ymax)

347return $im;

348

349if($x >= $y) {

350$newx = $xmax;

351$newy = $newx * $y / $x;

352}

353else {

354$newy = $ymax;

355$newx = $x / $y * $newy;

356}

357

358$im2 = imagecreatetruecolor($newx, $newy);

359imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);

360return $im2;

361}

21. PHP检测 ajax 请求

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

362if(!emptyempty($_SERVER['HTTP_X_REQUESTED_WITH']) &&

strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){

363//If AJAX Request Then

364}else{

365//something else

366}

相关主题
相关文档 最新文档