php : 收集整理的非常有用的函数

项目中经常会需要一些让人头疼的函数,作为开发者应该整理一个自己的函数库,在需要之时复制过来即可。以下是收集整理数十个PHP项目中常用的函数

1、PHP加密解密
PHP加密和解密函数可以用来加密一些有用的字符串存放在数据库里,并且通过可逆解密字符串,该函数使用了base64和MD5加密和解密。

function encryptDecrypt($key, $string, KaTeX parse error: Expected '}', got 'EOF' at end of input: …crypt){ if(decrypt){
d e c r y p t e d = r t r i m ( m c r y p t d e c r y p t ( M C R Y P T R I J N D A E L 2 56 , m d 5 ( decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5( decrypted=rtrim(mcryptdecrypt(MCRYPTRIJNDAEL256,md5(key), base64_decode( s t r i n g ) , M C R Y P T M O D E C B C , m d 5 ( m d 5 ( string), MCRYPT_MODE_CBC, md5(md5( string),MCRYPTMODECBC,md5(md5(key))), “12”);
return $decrypted;
}else{
e n c r y p t e d = b a s e 6 4 e n c o d e ( m c r y p t e n c r y p t ( M C R Y P T R I J N D A E L 2 56 , m d 5 ( encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5( encrypted=base64encode(mcryptencrypt(MCRYPTRIJNDAEL256,md5(key), s t r i n g , M C R Y P T M O D E C B C , m d 5 ( m d 5 ( string, MCRYPT_MODE_CBC, md5(md5( string,MCRYPTMODECBC,md5(md5(key))));
return $encrypted;
}
}
使用方法如下

//以下是将字符串“Helloweba欢迎您”分别加密和解密
//加密:
echo encryptDecrypt(‘password’, ‘Helloweba欢迎您’,0);
//解密:
echo encryptDecrypt(‘password’, ‘z0JAx4qMwcF+db5TNbp/xwdUM84snRsXvvpXuaCa4Bk=’,1);
2、PHP生成随机字符串
当我们需要生成一个随机名字,临时密码等字符串时可以用到下面的函数:

function generateRandomString($length = 10) {
$characters = ‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’;
r a n d o m S t r i n g = ′ ′ ; f o r ( randomString = &#x27;&#x27;; for ( randomString=;for(i = 0; $i < $length; $i++) {
$randomString .= c h a r a c t e r s [ r a n d ( 0 , s t r l e n ( characters[rand(0, strlen( characters[rand(0,strlen(characters) - 1)];
}
return $randomString;
}
使用方法如下

echo generateRandomString(20);
3、PHP获取文件扩展名(后缀)
以下函数可以快速获取文件的扩展名即后缀。

function getExtension($filename){
m y e x t = s u b s t r ( myext = substr( myext=substr(filename, strrpos( f i l e n a m e , ′ . ′ ) ) ; r e t u r n s t r r e p l a c e ( ′ . ′ , ′ ′ , filename, &#x27;.&#x27;)); return str_replace(&#x27;.&#x27;,&#x27;&#x27;, filename,.));returnstrreplace(.,,myext);
}
使用方法如下

f i l e n a m e = ′ 我 的 文 档 . d o c ′ ; e c h o g e t E x t e n s i o n ( filename = &#x27;我的文档.doc&#x27;; echo getExtension( filename=.doc;echogetExtension(filename);
4、PHP获取文件大小并格式化
以下使用的函数可以获取文件的大小,并且转换成便于阅读的KB,MB等格式。

function formatSize($size) {
s i z e s = a r r a y ( &quot; B y t e s &quot; , &quot; K B &quot; , &quot; M B &quot; , &quot; G B &quot; , &quot; T B &quot; , &quot; P B &quot; , &quot; E B &quot; , &quot; Z B &quot; , &quot; Y B &quot; ) ; i f ( sizes = array(&quot; Bytes&quot;, &quot; KB&quot;, &quot; MB&quot;, &quot; GB&quot;, &quot; TB&quot;, &quot; PB&quot;, &quot; EB&quot;, &quot; ZB&quot;, &quot; YB&quot;); if ( sizes=array("Bytes","KB","MB","GB","TB","PB","EB","ZB","YB");if(size == 0) {
return(‘n/a’);
} else {
return (round( s i z e / p o w ( 1024 , ( size/pow(1024, ( size/pow(1024,(i = floor(log($size, 1024)))), 2) . s i z e s [ sizes[ sizes[i]);
}
}
使用方法如下

t h e f i l e = f i l e s i z e ( ′ t e s t f i l e . m p 3 ′ ) ; e c h o f o r m a t S i z e ( thefile = filesize(&#x27;test_file.mp3&#x27;); echo formatSize( thefile=filesize(testfile.mp3);echoformatSize(thefile);
5、PHP替换标签字符
有时我们需要将字符串、模板标签替换成指定的内容,可以用到下面的函数:

function stringParser( s t r i n g , string, string,replacer){
r e s u l t = s t r r e p l a c e ( a r r a y k e y s ( result = str_replace(array_keys( result=strreplace(arraykeys(replacer), array_values( r e p l a c e r ) , replacer), replacer),string);
return $result;
}
使用方法如下

$string = ‘The {b}anchor text{/b} is the {b}actual word{/b} or words used {br}to describe the link {br}itself’;
$replace_array = array(’{b}’ => ‘’,’{/b}’ => ‘’,’{br}’ => ‘
’);

echo stringParser( s t r i n g , string, string,replace_array);
6、PHP列出目录下的文件名
如果你想列出目录下的所有文件,使用以下代码即可:

1function listDirFiles(KaTeX parse error: Expected '}', got 'EOF' at end of input: …rPath){ if(dir = opendir(KaTeX parse error: Expected '}', got 'EOF' at end of input: … while((file = readdir(KaTeX parse error: Expected '}', got 'EOF' at end of input: … if(!is_dir(DirPath.$file))
{
echo “filename: $file
”;
}
}
}
}
使用方法如下

listDirFiles(‘home/some_folder/’);
7、PHP获取当前页面URL
以下函数可以获取当前页面的URL,不管是http还是https。

11function curPageURL() {
p a g e U R L = ′ h t t p ′ ; i f ( ! e m p t y ( pageURL = &#x27;http&#x27;; if (!empty( pageURL=http;if(!empty(_SERVER[‘HTTPS’])) {$pageURL .= “s”;}
p a g e U R L . = &quot; : / / &quot; ; i f ( pageURL .= &quot;://&quot;; if ( pageURL.="://";if(_SERVER[“SERVER_PORT”] != “80”) {
$pageURL .= S E R V E R [ &quot; S E R V E R N A M E &quot; ] . &quot; : &quot; . _SERVER[&quot;SERVER_NAME&quot;].&quot;:&quot;. SERVER["SERVERNAME"].":"._SERVER[“SERVER_PORT”].$_SERVER[“REQUEST_URI”];
} else {
$pageURL .= S E R V E R [ &quot; S E R V E R N A M E &quot; ] . _SERVER[&quot;SERVER_NAME&quot;]. SERVER["SERVERNAME"]._SERVER[“REQUEST_URI”];
}
return $pageURL;
}
使用方法如下

echo curPageURL();
8、PHP强制下载文件
有时我们不想让浏览器直接打开文件,如PDF文件,而是要直接下载文件,那么以下函数可以强制下载文件,函数中使用了application/octet-stream头类型。

1function download(KaTeX parse error: Expected '}', got 'EOF' at end of input: … if ((isset(filename))&&(file_exists(KaTeX parse error: Expected '}', got 'EOF' at end of input: …th: ".filesize(filename));
header(‘Content-Type: application/octet-stream’);
header(‘Content-Disposition: attachment; filename="’ . f i l e n a m e . ′ &quot; ′ ) ; r e a d f i l e ( &quot; filename . &#x27;&quot;&#x27;); readfile(&quot; filename.");readfile("filename");
} else {
echo “Looks like file does not exist!”;
}
}
使用方法如下

download(’/down/test_45f73e852.zip’);
9、PHP截取字符串长度
我们经常会遇到需要截取字符串(含中文汉字)长度的情况,比如标题显示不能超过多少字符,超出的长度用…表示,以下函数可以满足你的需求。

111111111122222222223333/*
Utf-8、gb2312都支持的汉字截取函数
cut_str(字符串, 截取长度, 开始长度, 编码);
编码默认为 utf- 开始长度默认为 */
function cutStr($string, $sublen, $start = 0, KaTeX parse error: Expected '}', got 'EOF' at end of input: …TF-8'){ if(code == ‘UTF-8’){
KaTeX parse error: Expected 'EOF', got '\x' at position 9: pa = "/[\̲x̲01-\x7f]|[\xc2-…pa, $string, $t_string);

    if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen))."...";
    return join('', array_slice($t_string[0], $start, $sublen));
}else{
    $start = $start*2;
    $sublen = $sublen*2;
    $strlen = strlen($string);
    $tmpstr = '';

    for($i=0; $i<$strlen; $i++){
        if($i>=$start && $i<($start+$sublen)){
            if(ord(substr($string, $i, 1))>129){
                $tmpstr.= substr($string, $i, 2);
            }else{
                $tmpstr.= substr($string, $i, 1);
            }
        }
        if(ord(substr($string, $i, 1))>129) $i++;
    }
    if(strlen($tmpstr)<$strlen ) $tmpstr.= "...";
    return $tmpstr;
}

}
使用方法如下

s t r = &quot; j Q u e r y 插 件 实 现 的 加 载 图 片 和 页 面 效 果 &quot; ; e c h o c u t S t r ( str = &quot;jQuery插件实现的加载图片和页面效果&quot;; echo cutStr( str="jQuery";echocutStr(str,16);
10、PHP获取客户端真实IP
我们经常要用数据库记录用户的IP,以下代码可以获取客户端真实的IP:

11111111//获取用户真实IP
function getIp() {
if (getenv(“HTTP_CLIENT_IP”) && strcasecmp(getenv(“HTTP_CLIENT_IP”), “unknown”))
$ip = getenv(“HTTP_CLIENT_IP”);
else
if (getenv(“HTTP_X_FORWARDED_FOR”) && strcasecmp(getenv(“HTTP_X_FORWARDED_FOR”), “unknown”))
$ip = getenv(“HTTP_X_FORWARDED_FOR”);
else
if (getenv(“REMOTE_ADDR”) && strcasecmp(getenv(“REMOTE_ADDR”), “unknown”))
i p = g e t e n v ( &quot; R E M O T E A D D R &quot; ) ; e l s e i f ( i s s e t ( ip = getenv(&quot;REMOTE_ADDR&quot;); else if (isset ( ip=getenv("REMOTEADDR");elseif(isset(_SERVER[‘REMOTE_ADDR’]) && KaTeX parse error: Expected 'EOF', got '&' at position 24: …'REMOTE_ADDR'] &̲& strcasecmp(_SERVER[‘REMOTE_ADDR’], “unknown”))
$ip = $_SERVER[‘REMOTE_ADDR’];
else
i p = &quot; u n k n o w n &quot; ; r e t u r n ( ip = &quot;unknown&quot;; return ( ip="unknown";return(ip);
}
使用方法如下

echo getIp();
11、PHP防止SQL注入
我们在查询数据库时,出于安全考虑,需要过滤一些非法字符防止SQL恶意注入,请看一下函数:

function injCheck($sql_str) {
$check = preg_match(’/select|insert|update|delete|’|/*|*|../|./|union|into|load_file|outfile/’, s q l s t r ) ; i f ( sql_str); if ( sqlstr);if(check) {
echo ‘非法字符!!’;
exit;
} else {
return $sql_str;
}
}
使用方法如下

echo injCheck(‘1 or 1=1’);
12、PHP页面提示与跳转
我们在进行表单操作时,有时为了友好需要提示用户操作结果,并跳转到相关页面,请看以下函数:

11111111112222function message( m s g T i t l e , msgTitle, msgTitle,message,$jumpUrl){
$str = ‘’;
$str .= ‘’;
$str .= ‘’;
$str .= ‘’;
$str .= ‘页面提示’;
$str .= ‘’;
$str .= ‘’;
$str .= ‘’;
$str .= ‘

’;
s t r . = ′ &lt; h 3 &gt; ′ . str .= &#x27;&lt;h3&gt;&#x27;. str.=<h3>.msgTitle.’’;
$str .= ‘
’;
s t r . = ′ &lt; h 4 c l a s s = &quot; r e d &quot; &gt; ′ . str .= &#x27;&lt;h4 class=&quot;red&quot;&gt;&#x27;. str.=<h4class="red">.message.’’;
KaTeX parse error: Expected '}', got 'EOF' at end of input: …直接点击 <a href="{jumpUrl}">这里 跳转

’;
KaTeX parse error: Can't use function '\'' in math mode at position 46: …cation.replace(\̲'̲".jumpUrl."’)’,2000)";
$str .= ‘’;
$str .= ‘’;
$str .= ‘’;
$str .= ‘’;
echo $str;
}
使用方法如下

message(‘操作提示’,‘操作成功!’,‘http://www.helloweba.com/’);
13、PHP计算时长
我们在处理时间时,需要计算当前时间距离某个时间点的时长,如计算客户端运行时长,通常用hh:mm:ss表示。

1function changeTimeType(KaTeX parse error: Expected '}', got 'EOF' at end of input: …nds) { if (seconds > 3600) {
h o u r s = i n t v a l ( hours = intval( hours=intval(seconds / 3600);
$minutes = $seconds % 3600;
$time = $hours . “:” . gmstrftime(’%M:%S’, $minutes);
} else {
$time = gmstrftime(’%H:%M:%S’, $seconds);
}
return $time;
}
使用方法如下

s e c o n d s = 3712 ; e c h o c h a n g e T i m e T y p e ( seconds = 3712; echo changeTimeType( seconds=3712;echochangeTimeType(seconds);
14、PHP写日志
我们在测试代码的时候,需要了解代码执行情况,而这中执行时在后台运行的,前台无法知道是否运行正常,在这种情况下,我们一般用写日志的形式来调试代码。

function logResult($str=’’) {
f p = f o p e n ( &quot; l o g . t x t &quot; , &quot; a &quot; ) ; f l o c k ( fp = fopen(&quot;log.txt&quot;,&quot;a&quot;); flock( fp=fopen("log.txt","a");flock(fp, LOCK_EX) ;
fwrite( f p , &quot; 执 行 日 期 : &quot; . s t r f t i m e ( &quot; fp,&quot;执行日期:&quot;.strftime(&quot;%Y%m%d%H%M%S&quot;,time()).&quot;\n&quot;. fp,"".strftime("str."\n");
flock( f p , L O C K U N ) ; f c l o s e ( fp, LOCK_UN); fclose( fp,LOCKUN);fclose(fp);
}
函数logResult()记录执行时间,参数$str自定义,执行时会将运行日志写入到log.txt文件中,注意log.txt要有写权限。比如我们想知道支付接口返回的数据信息,可以这样调用:

logResult(‘获取数据reselt=xxx’);
15、PHP获取当前月份第一天和最后一天
我们在做统计查询时,经常要查询某个月的数据,就是从当月的第一天到最后一天,那么这个日期的获取整理成一个函数直接调用,请看:

function getthemonth($date){
f i r s t d a y = d a t e ( ′ Y − m − 0 1 ′ , s t r t o t i m e ( firstday = date(&#x27;Y-m-01&#x27;, strtotime( firstday=date(Ym01,strtotime(date));
l a s t d a y = d a t e ( ′ Y − m − d ′ , s t r t o t i m e ( &quot; lastday = date(&#x27;Y-m-d&#x27;, strtotime(&quot; lastday=date(Ymd,strtotime("firstday +1 month -1 day"));
return array( f i r s t d a y , firstday, firstday,lastday);
}
$today = date(“Y-m-d”);
d a y = g e t t h e m o n t h ( day=getthemonth( day=getthemonth(today);
echo "当月的第一天: ". d a y [ 0 ] . &quot; 当 月 的 最 后 一 天 : &quot; . day[0].&quot; 当月的最后一天: &quot;. day[0].":".day[1];
16、PHP检查是否宕机
有时候我们需要定期检查网站是否能正常访问,我们可以做个定时任务去执行访问网站上的固定页面,如果访问出错就有可能是宕机了,请看:

11111111function visit($url){
$agent = “Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)”;
c h = c u r l i n i t ( ) ; c u r l s e t o p t ( ch=curl_init(); curl_setopt ( ch=curlinit();curlsetopt(ch, CURLOPT_URL, u r l ) ; c u r l s e t o p t ( url ); curl_setopt( url);curlsetopt(ch, CURLOPT_USERAGENT, a g e n t ) ; c u r l s e t o p t ( agent); curl_setopt ( agent);curlsetopt(ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ( c h , C U R L O P T V E R B O S E , f a l s e ) ; c u r l s e t o p t ( ch,CURLOPT_VERBOSE,false); curl_setopt( ch,CURLOPTVERBOSE,false);curlsetopt(ch, CURLOPT_TIMEOUT, 5);
curl_setopt( c h , C U R L O P T S S L V E R I F Y P E E R , F A L S E ) ; c u r l s e t o p t ( ch,CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt( ch,CURLOPTSSLVERIFYPEER,FALSE);curlsetopt(ch,CURLOPT_SSLVERSION,3);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, FALSE);
p a g e = c u r l e x e c ( page=curl_exec( page=curlexec(ch); //echo curl_error($ch);
h t t p c o d e = c u r l g e t i n f o ( httpcode = curl_getinfo( httpcode=curlgetinfo(ch, CURLINFO_HTTP_CODE);
curl_close( c h ) ; i f ( ch); if( ch);if(httpcode>=200 && $httpcode<300) return true;
else return false;
}
使用方法如下

if (visit(“http://www.qq.com”))
echo “www.qq.com is OK”;
else
echo “Website DOWN”;
17、PHP搜索和高亮显示字符串中的关键字
当我们需要将搜索结果高亮显示的时候,可以使用以下函数:

function highlighter($text, $words) {
$split_words = explode(" " , w o r d s ) ; f o r e a c h ( words ); foreach( words);foreach(split_words as $word) {
$color = “#4285F4”;
t e x t = p r e g r e p l a c e ( &quot; / ( text = preg_replace(&quot;/( text=pregreplace("/(word)/i" , “<span style=“color:”.$color.”;">$1", $text );
}
return $text;
}
使用方法如下

$string = “基于Zepto的内容滑动插件:zepto.hwSlider.js”;
w o r d s = &quot; z e p t o &quot; ; e c h o h i g h l i g h t e r ( words = &quot;zepto&quot;; echo highlighter( words="zepto";echohighlighter(string ,$words);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值