php开发中实用的PHP代码片段

原创
2016-06-08 17:22:25 689浏览

下面我们一起来看我整理了在php开发中一些常用的php函数整理,希望这些函数代码地各位同学同样有帮助哦。

1.关键词高亮

代码如下 复制代码

function highlight($sString, $aWords) {
if (!is_array ($aWords) || empty ($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';
} www,111cn.net
if ($strength >= 8 ) {
$vowels .= '@#$%';
}

$password = '';
$alt = time() % 2;
for ($i = 0; $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) {
/* remove comments */
$buffer = preg_replace('!/*[^*]**+([^/][^*]**+)*/!', '', $buffer);
/* remove tabs, spaces, newlines, etc. */
$buffer = str_replace(array("rn", "r", "n", "t", ' ', ' ', ' '), '', $buffer);
return $buffer;
}

/* your css files */
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

return $year_diff;
}

7.计算执行时间

代码如下 复制代码

//Create a variable for start time
$time_start = microtime(true);

// Place your PHP/HTML/JavaScript/CSS/Etc. Here

//Create a variable for end time
$time_end = microtime(true);
//Subtract the two times to get seconds
$time = $time_end - $time_start;

echo 'Script took '.$time.' seconds to execute';8.PHP的维护模式
function maintenance($mode = FALSE){
if($mode){ www.111cn.net

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;
}
}
}


9.阻止CSS样式被缓存

代码如下 复制代码

function make_ranked($rank) {
$last = substr( $rank, -1 );
$seclast = substr( $rank, -2, -1 );
if( $last > 3 || $last == 0 ) $ext = 'th';
else if( $last == 3 ) $ext = 'rd';
else if( $last == 2 ) $ext = 'nd';
else $ext = 'st';

if( $last == 1 && $seclast == 1) $ext = 'th';
if( $last == 2 && $seclast == 1) $ext = 'th';
if( $last == 3 && $seclast == 1) $ext = 'th';

return $rank.$ext;
}

通过IP判断来源


这是一个非常实用的代码片段,可以帮助你通过IP来判断访客来源。下面的方法通过接收一个参数,然后返回IP所在地点。如果没有找到,则返回UNKNOWN。

代码如下 复制代码
function detect_city($ip) {

$default = 'UNKNOWN';

if (!is_string($ip) || strlen($ip) $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 for ($y=0;$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来获取错误信息。下面的代码可以帮助你实现。

    代码如下 复制代码

    // Our custom error handler
    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";

    // Email the error to someone...
    error_log($email, 1, 'you@youremail.com', $headers);

    // Make sure that you decide how to respond to errors (on the user's side)
    // Either echo an error message, or kill the entire project. Up to you...
    // The code below ensures that we only "die" if the error was more than
    // just a NOTICE.
    if ( ($number !== E_NOTICE) && ($number die("There was an error. Please try again later.");
    }
    }

    // We should use our custom function to handle errors.
    set_error_handler('nettuts_error_handler');

    // Trigger an error... (var doesn't exist)
    echo $somevarthatdoesnotexist;
    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。