PHP实用代码片段(二)
程序员文章站
2024-01-05 15:38:34
1. 转换 URL:从字符串变成超链接 如果你正在开发论坛,博客或者是一个常规的表单提交,很多时候都要用户访问一个网站。使用这个函数,URL 字符串就可以自动的转换为超链接。 语法: 2. 阻止多个 IP 访问你的网站 这个代码片段可以方便你禁止某些特定的 IP 地址访问你的网站。 3. 强制性文件 ......
1. 转换 URL:从字符串变成超链接
如果你正在开发论坛,博客或者是一个常规的表单提交,很多时候都要用户访问一个网站。使用这个函数,URL 字符串就可以自动的转换为超链接。
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; }
语法:
<?php $text = "This is my first post on http://blog.koonk.com"; $text = makeClickableLinks($text); echo $text; ?>
2. 阻止多个 IP 访问你的网站
这个代码片段可以方便你禁止某些特定的 IP 地址访问你的网站。
if ( !file_exists('blocked_ips.txt') ) { $deny_ips = array( '127.0.0.1', '192.168.1.1', '83.76.27.9', '192.168.1.163' ); } else { $deny_ips = file('blocked_ips.txt'); } // read user ip adress: $ip = isset($_SERVER['REMOTE_ADDR']) ? trim($_SERVER['REMOTE_ADDR']) : ''; // search current IP in $deny_ips array if ( (array_search($ip, $deny_ips))!== FALSE ) { // address is blocked: echo 'Your IP adress ('.$ip.') was blocked!'; exit; }
3. 强制性文件下载
如果你需要下载特定的文件而不用另开新窗口,下面的代码片段可以帮助你。
function force_download($file) { $dir = "../log/exports/"; if ((isset($file))&&(file_exists($dir.$file))) { header("Content-type: application/force-download"); header('Content-Disposition: inline; filename="' . $dir.$file . '"'); header("Content-Transfer-Encoding: Binary"); header("Content-length: ".filesize($dir.$file)); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . $file . '"'); readfile("$dir$file"); } else { echo "No file selected"; } }
语法:
<php force_download("image.jpg"); ?>
4. 创建 JSON 数据
使用下面的 PHP 片段可以创建 JSON 数据,可以方便你创建移动应用的 Web 服务。
$json_data = array ('id'=>1,'name'=>"Mohit"); echo json_encode($json_data);
5. 压缩 zip 文件
使用下面的 PHP 片段可以即时压缩 zip 文件。
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; } }
语法:
<?php $files=array('file1.jpg', 'file2.jpg', 'file3.gif'); create_zip($files, 'myzipfile.zip', true); ?>
6. 解压文件
function unzip($location,$newLocation) { if(exec("unzip $location",$arr)){ mkdir($newLocation); for($i = 1;$i< count($arr);$i++){ $file = trim(preg_replace("~inflating: ~","",$arr[$i])); copy($location.'/'.$file,$newLocation.'/'.$file); unlink($location.'/'.$file); } return TRUE; }else{ return FALSE; } }
语法:
<?php unzip('test.zip','unziped/test'); //File would be unzipped in unziped/test folder ?>
7. 缩放图片
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; }
8. 使用 mail() 发送邮件
function send_mail($to,$subject,$body) { $headers = "From: KOONK\r\n"; $headers .= "Reply-To: blog@koonk.com\r\n"; $headers .= "Return-Path: blog@koonk.com\r\n"; $headers .= "X-Mailer: PHP5\n"; $headers .= 'MIME-Version: 1.0' . "\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; mail($to,$subject,$body,$headers); }
语法:
<?php $to = "admin@koonk.com"; $subject = "This is a test mail"; $body = "Hello World!"; send_mail($to,$subject,$body); ?>
9. 把秒转换成天数,小时数和分钟
function secsToStr($secs) { if($secs>=86400){$days=floor($secs/86400);$secs=$secs%86400;$r=$days.' day';if($days<>1){$r.='s';}if($secs>0){$r.=', ';}} if($secs>=3600){$hours=floor($secs/3600);$secs=$secs%3600;$r.=$hours.' hour';if($hours<>1){$r.='s';}if($secs>0){$r.=', ';}} if($secs>=60){$minutes=floor($secs/60);$secs=$secs%60;$r.=$minutes.' minute';if($minutes<>1){$r.='s';}if($secs>0){$r.=', ';}} $r.=$secs.' second';if($secs<>1){$r.='s';} return $r; }
语法:
<?php $seconds = "56789"; $output = secsToStr($seconds); echo $output; ?>
10. 数据库连接
连接 MySQL 数据库
<?php $DBNAME = 'koonk'; $HOST = 'localhost'; $DBUSER = 'root'; $DBPASS = 'koonk'; $CONNECT = mysql_connect($HOST,$DBUSER,$DBPASS); if(!$CONNECT) { echo 'MySQL Error: '.mysql_error(); } $SELECT = mysql_select_db($DBNAME); if(!$SELECT) { echo 'MySQL Error: '.mysql_error(); } ?>