10个超级有用、必须收藏的PHP代码样例

来源:http://www.sh-fengwen.com 作者:家常菜谱 人气:185 发布时间:2019-09-06
摘要:作为一个正常的程序员,会好几种语言是十分正常的,相信大部分程序员也都会编写几句PHP程序,如果是WEB程序员,PHP一定是必备的,即使你没用开发过大型软件项目,也一定多少了解

作为一个正常的程序员,会好几种语言是十分正常的,相信大部分程序员也都会编写几句PHP程序,如果是WEB程序员,PHP一定是必备的,即使你没用开发过大型软件项目,也一定多少了解它的语法。在PHP的流行普及中,网上总结出了很多实用的PHP代码片段,这些代码片段在当你遇到类似的问题时,粘贴过去就可以使用,非常的高效,非常的省时省力。将这些程序员前辈总结出的优秀代码放到自己的知识库中,是一个善于学习的程序员的好习惯。

      在PHP的流行普及中,网上总结出了很多实用的PHP代码片段,这些代码片段在当你遇到类似的问题时,粘贴过去就可以使用,非常的高效,非常的省时省力。将这些程序员前辈总结出的优秀代码放到自己的知识库中,是一个善于学习的程序员的好习惯。虽然很多内容还不是太理解,不过先收集整理出来。

图片 110个超级有用、必须收藏的PHP代码样例

一、黑名单过滤

function is_spam($text, $file, $split = ':', $regex = false){ 
    $handle = fopen($file, 'rb'); 
    $contents = fread($handle, filesize($file)); 
    fclose($handle); 
    $lines = explode("n", $contents); 
    $arr = array(); 
    foreach($lines as $line){ 
        list($word, $count) = explode($split, $line); 
        if($regex) 
            $arr[$word] = $count; 
        else 
            $arr[preg_quote($word)] = $count; 
    } 
    preg_match_all("~".implode('|', array_keys($arr))."~", $text, $matches); 
    $temp = array(); 
    foreach($matches[0] as $match){ 
        if(!in_array($match, $temp)){ 
            $temp[$match] = $temp[$match] + 1; 
            if($temp[$match] >= $arr[$word]) 
                return true; 
        } 
    } 
    return false; 
} 

$file = 'spam.txt'; 
$str = 'This string has cat, dog word'; 
if(is_spam($str, $file)) 
    echo 'this is spam'; 
else 
    echo 'this is not spam';

ab:3
dog:3
cat:2
monkey:2

PHP代码样例

二、随机颜色生成器

function randomColor() { 
    $str = '#'; 
    for($i = 0 ; $i < 6 ; $i++) { 
        $randNum = rand(0 , 15); 
        switch ($randNum) { 
            case 10: $randNum = 'A'; break; 
            case 11: $randNum = 'B'; break; 
            case 12: $randNum = 'C'; break; 
            case 13: $randNum = 'D'; break; 
            case 14: $randNum = 'E'; break; 
            case 15: $randNum = 'F'; break; 
        } 
        $str .= $randNum; 
    } 
    return $str; 
} 
$color = randomColor();
<?php/** * 时间:2015-8-6 * 作者:River * 超级有用、必须收藏的PHP代码样例 */class Helper { /** * 友好显示var_dump */ static public function dump($var, $echo = true, $label = null, $strict = true) { $label = ( $label === null ) ? '' : rtrim . ' '; if  { if (ini_get('html_errors')) { $output = print_r($var, true); $output = "<pre>" . $label . htmlspecialchars($output, ENT_QUOTES) . "</pre>"; } else { $output = $label . print_r($var, true); } } else { ob_start(); var_dump; $output = ob_get_clean(); if (!extension_loaded) { $output = preg_replace("/]=>n/m", "] => ", $output); $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>'; } } if  { echo $output; return null; } else return $output; } /** * 获取客户端IP地址 */ static public function getClientIP() { static $ip = NULL; if ($ip !== NULL) return $ip; if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); $pos = array_search('unknown', $arr); if (false !== $pos) unset($arr[$pos]); $ip = trim; } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (isset($_SERVER['REMOTE_ADDR'])) { $ip = $_SERVER['REMOTE_ADDR']; } // IP地址合法验证 $ip = ( false !== ip2long ? $ip : '0.0.0.0'; return $ip; } /** * 循环创建目录 */ static public function mkdir($dir, $mode = 0777) { if (is_dir || @mkdir($dir, $mode)) return true; if (!mk_dir(dirname, $mode)) return false; return @mkdir($dir, $mode); } /** * 格式化单位 */ static public function byteFormat($size, $dec = 2) { $a = array("B", "KB", "MB", "GB", "TB", "PB"); $pos = 0; while ($size >= 1024) { $size /= 1024; $pos++; } return round($size, $dec) . " " . $a[$pos]; } /** * 下拉框,单选按钮 自动选择 * * @param $string 输入字符 * @param $param 条件 * @param $type 类型 * selected checked * @return string */ static public function selected($string, $param = 1, $type = 'select') { if (is_array { $true = in_array($string, $param); } elseif ($string == $param) { $true = true; } if  $return = $type == 'select' ? 'selected="selected"' : 'checked="checked"'; echo $return; } /** * 获得来源类型 post get * * @return unknown */ static public function method() { return strtoupper(isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET' ); } /** * 提示信息 */ static public function message($action = 'success', $content = '', $redirect = 'javascript:history.back;', $timeout = 4) { switch  { case 'success': $titler = '操作完成'; $class = 'message_success'; $images = 'message_success.png'; break; case 'error': $titler = '操作未完成'; $class = 'message_error'; $images = 'message_error.png'; break; case 'errorBack': $titler = '操作未完成'; $class = 'message_error'; $images = 'message_error.png'; break; case 'redirect': header("Location:$redirect"); break; case 'script': if (empty($redirect)) { exit('<script language="javascript">alert("' . $content . '");window.history.back</script>'); } else { exit('<script language="javascript">alert("' . $content . '");window.location=" ' . $redirect . ' "</script>'); } break; } // 信息头部 $header = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title>操作提示</title><style type="text/css">body{font:12px/1.7 "5b8b4f53",Tahoma;}html,body,div,p,a,h3{margin:0;padding:0;}.tips_wrap{ background:#F7FBFE;border:1px solid #DEEDF6;width:780px;padding:50px;margin:50px auto 0;}.tips_inner{zoom:1;}.tips_inner:after{visibility:hidden;display:block;font-size:0;content:" ";clear:both;height:0;}.tips_inner .tips_img{width:80px;float:left;}.tips_info{float:left;line-height:35px;width:650px}.tips_info h3{font-weight:bold;color:#1A90C1;font-size:16px;}.tips_info p{font-size:14px;color:#999;}.tips_info p.message_error{font-weight:bold;color:#F00;font-size:16px; line-height:22px}.tips_info p.message_success{font-weight:bold;color:#1a90c1;font-size:16px; line-height:22px}.tips_info p.return{font-size:12px}.tips_info .time{color:#f00; font-size:14px; font-weight:bold}.tips_info p a{color:#1A90C1;text-decoration:none;}</style></head><body>'; // 信息底部 $footer = '</body></html>'; $body = '<script type="text/javascript"> function delayURL { var delay = document.getElementById.innerHTML; //alert; if(delay > 0){ delay--; document.getElementById.innerHTML = delay; } else { window.location.href = url; } setTimeout("delayURL('" + url + "')", 1000); } </script><div > <div > <div > <img src="' . Yii::app()->baseUrl . '/static/images/' . $images . '"/> </div> <div > <p >' . $content . '</p> <p >系统自动跳转在 ' . $timeout . '  秒后,如果不想等待,<a href="' . $redirect . '">点击这里跳转</a></p> </div> </div></div><script type="text/javascript"> delayURL("' . $redirect . '"); </script>'; exit($header . $body . $footer); } /** * 查询字符生成 */ static public function buildCondition(array $getArray, array $keys = array { if ($getArray) { foreach ($getArray as $key => $value) { if (in_array($key, $keys) && $value) { $arr[$key] = CHtml::encode(strip_tags; } } return $arr; } } /** * base64_encode */ static function b64encode { $data = base64_encode; $data = str_replace(array('+', '/', '='), array('-', '_', ''), $data); return $data; } /** * base64_decode */ static function b64decode { $data = str_replace(array, array, $string); $mod4 = strlen % 4; if  { $data .= substr('====', $mod4); } return base64_decode; } /** * 验证邮箱 */ public static function email { if (empty return true; $chars = "/^([a-z0-9+_]|\-|\.)+@(([a-z0-9_]|\-)+\.)+[a-z]{2,6}$/i"; if (strpos($str, '@') !== false && strpos($str, '.') !== false) { if (preg_match($chars, $str)) { return true; } else { return false; } } else { return false; } } /** * 验证手机号码 */ public static function mobile { if (empty { return true; } return preg_match('#^13[d]{9}$|14^[0-9]d{8}|^15[0-9]d{8}$|^18[0-9]d{8}$#', $str); } /** * 验证固定电话 */ public static function tel { if (empty { return true; } return preg_match('/^(()|?((0d{2,3})|0d{2,3}-)?[1-9]d{6,7}(-d{1,4})?$/', trim; } /** * 验证qq号码 */ public static function qq { if (empty { return true; } return preg_match('/^[1-9]d{4,12}$/', trim; } /** * 验证邮政编码 */ public static function zipCode { if (empty { return true; } return preg_match('/^[1-9]d{5}$/', trim; } /** * 验证ip */ public static function ip { if (empty return true; if (!preg_match('#^d{1,3}.d{1,3}.d{1,3}.d{1,3}$#', $str)) { return false; } $ip_array = explode('.', $str); //真实的ip地址每个数字不能大于255 return ( $ip_array[0] <= 255 && $ip_array[1] <= 255 && $ip_array[2] <= 255 && $ip_array[3] <= 255 ) ? true : false; } /** * 验证身份证 */ public static function idCard { $str = trim; if (empty return true; if (preg_match("/^([0-9]{15}|[0-9]{17}[0-9a-z])$/i", $str)) return true; else return false; } /** * 验证网址 */ public static function url { if (empty return true; return preg_match('#(http|https|ftp|ftps)://+[w-]+(/[w-./?%&=]*)?#i', $str) ? true : false; } /** * 根据ip获取地理位置 * @param $ip * return :ip,beginip,endip,country,area */ public static function getlocation { $ip = new XIp(); $ipArr = $ip->getlocation; return $ipArr; } /** * 中文转换为拼音 */ public static function pinyin { $ip = new XPinyin(); return $ip->output; } /** * 拆分sql * * @param $sql */ public static function splitsql { $sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "ENGINE=\1 DEFAULT CHARSET=" . Yii::app()->db->charset, $sql); $sql = str_replace("r", "n", $sql); $ret = array(); $num = 0; $queriesarray = explode(";n", trim; unset; foreach ($queriesarray as $query) { $ret[$num] = ''; $queries = explode("n", trim; $queries = array_filter; foreach ($queries as $query) { $str1 = substr($query, 0, 1); if ($str1 != '#' && $str1 != '-') $ret[$num] .= $query; } $num++; } return ; } /** * 字符截取 * * @param $string * @param $length * @param $dot */ public static function cutstr($string, $length, $dot = '...', $charset = 'utf-8') { if (strlen <= $length) return $string; $pre = chr; $end = chr; $string = str_replace(array('&', '"', '<', '>'), array($pre . '&' . $end, $pre . '"' . $end, $pre . '<' . $end, $pre . '>' . $end), $string); $strcut = ''; if (strtolower == 'utf-8') { $n = $tn = $noc = 0; while ($n < strlen { $t = ord($string[$n]); if ($t == 9 || $t == 10 || ( 32 <= $t && $t <= 126 )) { $tn = 1; $n++; $noc++; } elseif (194 <= $t && $t <= 223) { $tn = 2; $n += 2; $noc += 2; } elseif (224 <= $t && $t <= 239) { $tn = 3; $n += 3; $noc += 2; } elseif (240 <= $t && $t <= 247) { $tn = 4; $n += 4; $noc += 2; } elseif (248 <= $t && $t <= 251) { $tn = 5; $n += 5; $noc += 2; } elseif ($t == 252 || $t == 253) { $tn = 6; $n += 6; $noc += 2; } else { $n++; } if ($noc >= $length) { break; } } if ($noc > $length) { $n -= $tn; } $strcut = substr($string, 0, $n); } else { for ($i = 0; $i < $length; $i++) { $strcut .= ord($string[$i]) > 127 ? $string[$i] . $string[++$i] : $string[$i]; } } $strcut = str_replace(array($pre . '&' . $end, $pre . '"' . $end, $pre . '<' . $end, $pre . '>' . $end), array('&', '"', '<', '>'), $strcut); $pos = strrpos($strcut, chr; if ($pos !== false) { $strcut = substr($strcut, 0, $pos); } return $strcut . $dot; } /** * 描述格式化 * @param $subject */ public static function clearCutstr($subject, $length = 0, $dot = '...', $charset = 'utf-8') { if  { return XUtils::cutstr(strip_tags(str_replace(array, '', $subject)), $length, $dot, $charset); } else { return strip_tags(str_replace(array, '', $subject)); } } /** * 检测是否为英文或英文数字的组合 * * @return unknown */ public static function isEnglist { if (!eregi("^[A-Z0-9]{1,26}$", $param)) { return false; } else { return true; } } /** * 将自动判断网址是否加http:// * * @param $http * @return string */ public static function convertHttp { if ($url == 'http://' || $url == '') return ''; if (substr($url, 0, 7) != 'http://' && substr($url, 0, 8) != 'https://') $str = 'http://' . $url; else $str = $url; return $str; } /* 标题样式格式化 */ public static function titleStyle { $text = ''; if ($style['bold'] == 'Y') { $text .='font-weight:bold;'; $serialize['bold'] = 'Y'; } if ($style['underline'] == 'Y') { $text .='text-decoration:underline;'; $serialize['underline'] = 'Y'; } if (!empty($style['color'])) { $text .='color:#' . $style['color'] . ';'; $serialize['color'] = $style['color']; } return array('text' => $text, 'serialize' => empty($serialize) ? '' : serialize($serialize)); } // 自动转换字符集 支持数组转换 static public function autoCharset($string, $from = 'gbk', $to = 'utf-8') { $from = strtoupper == 'UTF8' ? 'utf-8' : $from; $to = strtoupper == 'UTF8' ? 'utf-8' : $to; if (strtoupper === strtoupper || empty || (is_scalar && !is_string) { //如果编码相同或者非字符串标量则不转换 return $string; } if (is_string { if (function_exists('mb_convert_encoding')) { return mb_convert_encoding($string, $to, $from); } elseif (function_exists { return iconv($from, $to, $string); } else { return $string; } } elseif (is_array { foreach ($string as $key => $val) { $_key = self::autoCharset($key, $from, $to); $string[$_key] = self::autoCharset($val, $from, $to); if ($key != $_key) unset($string[$key]); } return $string; } else { return $string; } } /* 标题样式恢复 */ public static function titleStyleRestore($serialize, $scope = 'bold') { $unserialize = unserialize($serialize); if ($unserialize['bold'] == 'Y' && $scope == 'bold') return 'Y'; if ($unserialize['underline'] == 'Y' && $scope == 'underline') return 'Y'; if ($unserialize['color'] && $scope == 'color') return $unserialize['color']; } /** * 列出文件夹列表 * * @param $dirname * @return unknown */ public static function getDir { $files = array(); if (is_dir) { $fileHander = opendir; while (( $file = readdir($fileHander) ) !== false) { $filepath = $dirname . '/' . $file; if (strcmp($file, '.') == 0 || strcmp($file, '..') == 0 || is_file($filepath)) { continue; } $files[] = self::autoCharset($file, 'GBK', 'UTF8'); } closedir($fileHander); } else { $files = false; } return $files; } /** * 列出文件列表 * * @param $dirname * @return unknown */ public static function getFile { $files = array(); if (is_dir) { $fileHander = opendir; while (( $file = readdir($fileHander) ) !== false) { $filepath = $dirname . '/' . $file; if (strcmp($file, '.') == 0 || strcmp($file, '..') == 0 || is_dir($filepath)) { continue; } $files[] = self::autoCharset($file, 'GBK', 'UTF8'); ; } closedir($fileHander); } else { $files = false; } return $files; } /** * [格式化图片列表数据] * * @return [type] [description] */ public static function imageListSerialize { foreach  $data['file'] as $key => $row) { if  { $var[$key]['fileId'] = $data['fileId'][$key]; $var[$key]['file'] = $row; } } return array('data' => $var, 'dataSerialize' => empty ? '' : serialize; } /** * 反引用一个引用字符串 * @param $string * @return string */ static function stripslashes { if (is_array { foreach ($string as $key => $val) { $string[$key] = self::stripslashes; } } else { $string = stripslashes; } return $string; } /** * 引用字符串 * @param $string * @param $force * @return string */ static function addslashes($string, $force = 1) { if (is_array { foreach ($string as $key => $val) { $string[$key] = self::addslashes($val, $force); } } else { $string = addslashes; } return $string; } /** * 格式化内容 */ static function formatHtml($content, $options = '') { $purifier = new CHtmlPurifier(); if ($options != false) $purifier->options = $options; return $purifier->purify; }}?>

三、从网络下载文件

set_time_limit(0); 
// Supports all file types 
// URL Here: 
$url = 'http://somsite.com/some_video.flv'; 
$pi = pathinfo($url); 
$ext = $pi['extension']; 
$name = $pi['filename']; 

// create a new cURL resource 
$ch = curl_init(); 

// set URL and other appropriate options 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_HEADER, false); 
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); 
curl_setopt($ch, CURLOPT_AUTOREFERER, true); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 

// grab URL and pass it to the browser 
$opt = curl_exec($ch); 

// close cURL resource, and free up system resources 
curl_close($ch); 

$saveFile = $name.'.'.$ext; 
if(preg_match("/[^0-9a-z._-]/i", $saveFile)) 
    $saveFile = md5(microtime(true)).'.'.$ext; 

$handle = fopen($saveFile, 'wb'); 
fwrite($handle, $opt); 
fclose($handle);

原文:

四、Alexa/Google Page Rank

function page_rank($page, $type = 'alexa'){ 
    switch($type){ 
        case 'alexa': 
            $url = 'http://alexa.com/siteinfo/'; 
            $handle = fopen($url.$page, 'r'); 
        break; 
        case 'google': 
            $url = 'http://google.com/search?client=navclient-auto&ch=6-1484155081&features=Rank&q=info:'; 
            $handle = fopen($url.'http://'.$page, 'r'); 
        break; 
    } 
    $content = stream_get_contents($handle); 
    fclose($handle); 
    $content = preg_replace("~(n|t|ss+)~",'', $content); 
    switch($type){ 
        case 'alexa': 
            if(preg_match('~<div class="data (down|up)"><img.+?>(.+?) </div>~im',$content,$matches)){ 
                return $matches[2]; 
            }else{ 
                return FALSE; 
            } 
        break; 
        case 'google': 
            $rank = explode(':',$content); 
            if($rank[2] != '') 
                return $rank[2]; 
            else 
                return FALSE; 
        break; 
        default: 
            return FALSE; 
        break; 
    } 
} 
// Alexa Page Rank: 
echo 'Alexa Rank: '.page_rank('techug.com'); 
echo '
'; 
// Google Page Rank 
echo 'Google Rank: '.page_rank('techug.com', 'google');

五、强制下载文件

$filename = $_GET['file']; //Get the fileid from the URL 
// Query the file ID 
$query = sprintf("SELECT * FROM tableName WHERE id = '%s'",mysql_real_escape_string($filename)); 
$sql = mysql_query($query); 
if(mysql_num_rows($sql) > 0){ 
    $row = mysql_fetch_array($sql); 
    // Set some headers 
    header("Pragma: public"); 
    header("Expires: 0"); 
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
    header("Content-Type: application/force-download"); 
    header("Content-Type: application/octet-stream"); 
    header("Content-Type: application/download"); 
    header("Content-Disposition: attachment; filename=".basename($row['FileName']).";"); 
    header("Content-Transfer-Encoding: binary"); 
    header("Content-Length: ".filesize($row['FileName'])); 

    @readfile($row['FileName']); 
    exit(0); 
}else{ 
    header("Location: /"); 
    exit; 
}

本文由美高梅游戏平台网站发布于家常菜谱,转载请注明出处:10个超级有用、必须收藏的PHP代码样例

关键词:

上一篇:没有了

下一篇:没有了

最火资讯