php开发中实用的PHP代码片段
1.关键词高亮,代码如下:
- function highlight($sString, $aWords) {
- if (!is_array ($aWords) || emptyempty ($aWords) || !is_string ($sString)) {
- return false;
- }
-
- $sWords = implode ('|', $aWords);
- return preg_replace ('@b('.$sWords.')b@si', '$1', $sString);
- }
2.获取你的Feedburner的用户,代码如下:
- function get_average_readers($feed_id,$interval = 7){
- $today = date('Y-m-d', strtotime("now"));
- $ago = date('Y-m-d', strtotime("-".$interval." days"));
- $feed_url="https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=".$feed_id."&dates=".$ago.",".$today;
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_URL, $feed_url);
- $data = curl_exec($ch);
- curl_close($ch);
- $xml = new SimpleXMLElement($data);
- $fb = $xml->feed->entry['circulation'];
-
- $nb = 0;
- foreach($xml->feed->children() as $circ){
- $nb += $circ['circulation'];
- }
-
- return round($nb/$interval);
- }
3.自动生成密码,代码如下:
- function generatePassword($length=9, $strength=0) {
- $vowels = 'aeuy';
- $consonants = 'bdghjmnpqrstvz';
- if ($strength >= 1) {
- $consonants .= 'BDGHJLMNPQRSTVWXZ';
- }
- if ($strength >= 2) {
- $vowels .= "AEUY";
- }
- if ($strength >= 4) {
- $consonants .= '23456789';
- }
- if ($strength >= 8 ) {
- $vowels .= '@#$%';
- }
-
- $password = '';
- $alt = time() % 2;
- for ($i = 0; $i < $length; $i++) {
- if ($alt == 1) {
- $password .= $consonants[(rand() % strlen($consonants))];
- $alt = 0;
- } else {
- $password .= $vowels[(rand() % strlen($vowels))];
- $alt = 1;
- }
- }
- return $password;
- }
4.压缩多个CSS文件,代码如下:
- header('Content-type: text/css');
- ob_start("compress");
- function compress($buffer) {
-
- $buffer = preg_replace('!/*[^*]**+([^/][^*]**+)*/!', '', $buffer);
-
- $buffer = str_replace(array("rn", "r", "n", "t", ' ', ' ', ' '), '', $buffer);
- return $buffer;
- }
-
-
- include('master.css');
- include('typography.css');
- include('grid.css');
- include('print.css');
- include('handheld.css');
-
- ob_end_flush();
5.获取短网址,代码如下:
- function getTinyUrl($url) {
- return file_get_contents("http://tinyurl.com/api-create.php?url=".$url);
- }
6.根据生日计算年龄,代码如下:
- function age($date){
- $year_diff = '';
- $time = strtotime($date);
- if(FALSE === $time){
- return '';
- }
-
- $date = date('Y-m-d', $time);
- list($year,$month,$day) = explode("-",$date);
- $year_diff = date("Y") – $year;
- $month_diff = date("m") – $month;
- $day_diff = date("d") – $day;
- if ($day_diff < 0 || $month_diff < 0) $year_diff–;
-
- return $year_diff;
- }
7.计算执行时间,代码如下:
-
- $time_start = microtime(true);
-
-
-
-
- $time_end = microtime(true);
-
- $time = $time_end - $time_start;
-
- echo 'Script took '.$time.' seconds to execute';8.PHP的维护模式
- function maintenance($mode = FALSE){
- if($mode){
-
- if(basename($_SERVER['SCRIPT_FILENAME']) != 'maintenance.php'){
- header("Location: http://example.com/maintenance.php");
- exit;
- }
- }else{
- if(basename($_SERVER['SCRIPT_FILENAME']) == 'maintenance.php'){
- header("Location: http://example.com/");
- exit;
- }
- }
- }
通过IP判断来源,这是一个非常实用的代码片段,可以帮助你通过IP来判断访客来源,下面的方法通过接收一个参数,然后返回IP所在地点,如果没有找到,则返回UNKNOWN,代码如下:
- function detect_city($ip) {
-
- $default = 'UNKNOWN';
-
- if (!is_string($ip) || strlen($ip) < 1 || $ip == '127.0.0.1' || $ip == 'localhost')
- $ip = '8.8.8.8';
-
- $curlopt_useragent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)';
-
- $url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip);
- $ch = curl_init();
-
- $curl_opt = array(
- CURLOPT_FOLLOWLOCATION => 1,
- CURLOPT_HEADER => 0,
- CURLOPT_RETURNTRANSFER => 1,
- CURLOPT_USERAGENT => $curlopt_useragent,
- CURLOPT_URL => $url,
- CURLOPT_TIMEOUT => 1,
- CURLOPT_REFERER => 'http://' . $_SERVER['HTTP_HOST'],
- );
-
- curl_setopt_array($ch, $curl_opt);
-
- $content = curl_exec($ch);
-
- if (!is_null($curl_info)) {
- $curl_info = curl_getinfo($ch);
- }
-
- curl_close($ch);
-
- if ( preg_match('{
- City : ([^<]*)
- }i', $content, $regs) ) {
- $city = $regs[1];
- }
- if ( preg_match('{
- State/Province : ([^<]*)
- }i', $content, $regs) ) {
- $state = $regs[1];
- }
-
- if( $city!='' && $state!='' ){
- $location = $city . ', ' . $state;
- return $location;
- }else{
- return $default;
- }
-
- }
判断一张图片的主色调,下面这个代码非常实用,能帮助你判断一张图片中的主色调,你可以分析任何图片,代码如下:
- $i = imagecreatefromjpeg("image.jpg");
-
- for ($x=0;$x$i);$x++) {
- for ($y=0;$y$i);$y++) {
- $rgb = imagecolorat($i,$x,$y);
- $r = ($rgb >> 16) & 0xFF;
- $g = ($rgb >> & 0xFF;
- $b = $rgb & 0xFF;
-
- $rTotal += $r;
- $gTotal += $g;
- $bTotal += $b;
- $total++;
- }
- }
-
- $rAverage = round($rTotal/$total);
- $gAverage = round($gTotal/$total);
- $bAverage = round($bTotal/$total);
不显示PHP错误而发送电子邮件取代之,如果你不想在页面中显示PHP错误,也可以通过email来获取错误信息,下面的代码可以帮助你实现.
-
- function nettuts_error_handler($number, $message, $file, $line, $vars){
- $email = "
-
An error ($number) occurred on line
- $line and in the file: $file.
-
$message
";
-
- $email .= "
" . print_r($vars, 1) . "
";
-
- $headers = 'Content-type: text/html; charset=iso-8859-1' . "rn";
-
-
- error_log($email, 1, 'you@youremail.com', $headers);
-
-
-
-
-
- if ( ($number !== E_NOTICE) && ($number < 2048) ) {
- die("There was an error. Please try again later.");
- }
- }
-
-
- set_error_handler('nettuts_error_handler');
-
-
- echo $somevarthatdoesnotexist;
|