PHP实用代码片段(二)
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();
}
?>
PHP实用代码片段(二)的更多相关文章
- 回归 | js实用代码片段的封装与总结(持续更新中...)
上一次更博还是去年10月28号了,截至今天已经有整整4个月没有更新博客了,没更新博客不是代表不学了,期间我已经用vue做了两个项目,微信小程序做了一个项目,只是毕竟找到工作了,想偷偷懒,你懂的. ...
- PHP实用代码片段(三)
1. 目录清单 使用下面的 PHP 代码片段可以在一个目录中列出所有文件和文件夹. function list_files($dir) { if(is_dir($dir)) { if($handle ...
- C#程序员经常用到的10个实用代码片段 - 操作系统
原文地址 如果你是一个C#程序员,那么本文介绍的10个C#常用代码片段一定会给你带来帮助,从底层的资源操作,到上层的UI应用,这些代码也许能给你的开发节省不少时间.以下是原文: 1 读取操作系统和C ...
- Android 实用代码片段
一些不常见确又很实用的代码块. 1.精确获取屏幕尺寸(例如:3.5.4.0.5.0寸屏幕) public static double getScreenPhysicalSize(Activity ct ...
- android代码片段二
1.Android拦截短信 一.AndroidManifest.xml <uses-permission android:name="android.permission.RECE ...
- Android实用代码片段
有时候,需要一些小的功能,找到以后,就把它贴到了博客下面,作为留言,查找起来很不方便,所以就整理一下,方便自己和他人. 一. 获取系统版本号: 1 PackageInfo info = this.g ...
- C#程序员经常用到的10个实用代码片段
1 读取操作系统和CLR的版本 OperatingSystem os = System.Environment.OSVersion; Console.WriteLine(“Platform: {}”, ...
- [python实用代码片段]python获取当前时间的前一天,前一周,前一个月
python获取当前时间的前一天,前一周,前一个月. 实用python的datetime.timedelta方法,避免了有的月份是30和31等不同的情况. 获取前一个月的时间,方法实现:首先datet ...
- PHP实用代码片段(四)
1. 删除文件夹内容 function Delete($path) { if (is_dir($path) === true) { $files = array_diff(scandir($path) ...
随机推荐
- spring applicationContext.xml最全约束
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp ...
- c/ c++ 多态
多态 1.多态用途 为了代码可以简单的重复使用,添加一个功能时,接口不需要修改. #include <iostream> using namespace std; class A{ pub ...
- 【PAT】B1005 继续(3n+1)猜想
没有婼姐写得好 将所有的输入放入mp,mp2 覆盖的数存入mp 一开始认为mp中只出现一次的元素就是,忘了可能只被覆盖一次的情况 所以添加了mp2保存输入 #include <iostream& ...
- GitHub-分支管理03-多人合作【重点】
参考博文:廖雪峰Git教程 1. 多人协作 当你从远程仓库克隆时,实际上Git自动把本地的master分支和远程的master分支对应起来了,并且,远程仓库的默认名称是origin. 要查看远程库的信 ...
- 转 CSS3+js实现多彩炫酷旋转圆环时钟效果
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content ...
- ORCFILE IN HDP 2: BETTER COMPRESSION, BETTER PERFORMANCE
ORCFILE IN HDP 2: BETTER COMPRESSION, BETTER PERFORMANCE by Carter Shanklin The upcoming Hive 0.12 ...
- Contest Setting 2018 ICPC Pacific Northwest Regional Contest dp
题目:https://vj.69fa.cn/12703be72f729288b4cced17e2501850?v=1552995458 dp这个题目网上说是dp+离散化这个题目要对这些数字先处理然后进 ...
- Codeforces Round #546 (Div. 2) C. Nastya Is Transposing Matrices
C. Nastya Is Transposing Matrices time limit per test 1 second memory limit per test 256 megabytes i ...
- nginx学习笔记(一)
select模型主要是apache用 FD 文件描述符 soa架构 安装nginx ping baidu.com netstat -lntup 查看端口 cat /etc/redhat-rel ...
- 使用vue-cli脚手架创建项目
ue-cli 是一个官方发布 vue.js 项目脚手架,使用 vue-cli 可以快速创建 vue 项目. GitHub地址是:https://github.com/vuejs/vue-cli 一.安 ...