10个实用的PHP代码片段

释放双眼,带上耳机,听听看~!

作为一个正常的程序员,会好几种语言是十分正常的,相信大部分程序员也都会编写几句PHP程序;如果你是WEB程序员,那么PHP是必备的一门语言,即使你没用它开发过大型软件项目,也一定多少了解它的语法。

尽管PHP经常被人诟病,被人贬低,被人当玩笑开,事实证明,PHP是全世界网站开发中使用率最高的编程语言。

PHP最大的缺点是太简单,语法不严谨,框架体系很弱,但这也是它最大的优点,一个有点编程背景的普通人,只需要学习PHP半天时间,就可以上手开始开发web应用了。

网上有人总结几种编程语言的特点,我觉得也挺有道理的:

  • PHP就是: Quick and Dirty
  • Java就是: Beauty and Slowly
  • Ruby就是: Quick and Beauty
  • python就是: Quick and Simple

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

一、黑名单过滤


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
1function is_spam($text, $file, $split = ':', $regex = false){
2    $handle = fopen($file, 'rb');
3    $contents = fread($handle, filesize($file));
4    fclose($handle);
5    $lines = explode("n", $contents);
6    $arr = array();
7    foreach($lines as $line){
8        list($word, $count) = explode($split, $line);
9        if($regex)
10            $arr[$word] = $count;
11        else
12            $arr[preg_quote($word)] = $count;
13    }
14    preg_match_all("~".implode('|', array_keys($arr))."~", $text, $matches);
15    $temp = array();
16    foreach($matches[0] as $match){
17        if(!in_array($match, $temp)){
18            $temp[$match] = $temp[$match] + 1;
19            if($temp[$match] >= $arr[$word])
20                return true;
21        }
22    }
23    return false;
24}
25
26$file = 'spam.txt';
27$str = 'This string has cat, dog word';
28if(is_spam($str, $file))
29    echo 'this is spam';
30else
31    echo 'this is not spam';
32

输出:


1
2
3
4
5
1ab:3
2dog:3
3cat:2
4monkey:2
5

二、随机颜色生成器


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
1function randomColor() {
2    $str = '#';
3    for($i = 0 ; $i < 6 ; $i++) {
4        $randNum = rand(0 , 15);
5        switch ($randNum) {
6            case 10: $randNum = 'A'; break;
7            case 11: $randNum = 'B'; break;
8            case 12: $randNum = 'C'; break;
9            case 13: $randNum = 'D'; break;
10            case 14: $randNum = 'E'; break;
11            case 15: $randNum = 'F'; break;
12        }
13        $str .= $randNum;
14    }
15    return $str;
16}
17$color = randomColor();
18

三、从网络下载文件


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
1set_time_limit(0);
2// Supports all file types
3// URL Here:
4$url = 'http://somsite.com/some_video.flv';
5$pi = pathinfo($url);
6$ext = $pi['extension'];
7$name = $pi['filename'];
8
9// create a new cURL resource
10$ch = curl_init();
11
12// set URL and other appropriate options
13curl_setopt($ch, CURLOPT_URL, $url);
14curl_setopt($ch, CURLOPT_HEADER, false);
15curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
16curl_setopt($ch, CURLOPT_AUTOREFERER, true);
17curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
18curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
19
20// grab URL and pass it to the browser
21$opt = curl_exec($ch);
22
23// close cURL resource, and free up system resources
24curl_close($ch);
25
26$saveFile = $name.'.'.$ext;
27if(preg_match("/[^0-9a-z._-]/i", $saveFile))
28$saveFile = md5(microtime(true)).'.'.$ext;
29
30$handle = fopen($saveFile, 'wb');
31fwrite($handle, $opt);
32fclose($handle);
33

四、Alexa/Google Page Rank


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
1function page_rank($page, $type = 'alexa'){
2    switch($type){
3        case 'alexa':
4            $url = 'http://alexa.com/siteinfo/';
5            $handle = fopen($url.$page, 'r');
6            break;
7        case 'google':
8            $url = 'http://google.com/search?client=navclient-auto&ch=6-1484155081&features=Rank&q=info:';
9            $handle = fopen($url.'http://'.$page, 'r');
10            break;
11    }
12    $content = stream_get_contents($handle);
13    fclose($handle);
14    $content = preg_replace("~(n|t|ss+)~",'', $content);
15    switch($type){
16        case 'alexa':
17            if(preg_match('~<div class="data (down|up)"><img.+?>(.+?) </div>~im',$content,$matches)){
18                return $matches[2];
19            }else{
20            return FALSE;
21            }
22            break;
23        case 'google':
24            $rank = explode(':',$content);
25            if($rank[2] != '')
26                return $rank[2];
27            else
28                return FALSE;
29            break;
30        default:
31            return FALSE;
32            break;
33    }
34}
35// Alexa Page Rank:
36echo 'Alexa Rank: '.page_rank('techug.com');
37echo '
38';
39// Google Page Rank
40echo 'Google Rank: '.page_rank('techug.com', 'google');
41

五、强制下载文件


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
1$filename = $_GET['file']; //Get the fileid from the URL
2// Query the file ID
3$query = sprintf("SELECT * FROM tableName WHERE id = '%s'",mysql_real_escape_string($filename));
4$sql = mysql_query($query);
5if(mysql_num_rows($sql) > 0){
6    $row = mysql_fetch_array($sql);
7    // Set some headers
8    header("Pragma: public");
9    header("Expires: 0");
10    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
11    header("Content-Type: application/force-download");
12    header("Content-Type: application/octet-stream");
13    header("Content-Type: application/download");
14    header("Content-Disposition: attachment; filename=".basename($row['FileName']).";");
15    header("Content-Transfer-Encoding: binary");
16    header("Content-Length: ".filesize($row['FileName']));
17
18    @readfile($row['FileName']);
19    exit(0);
20}else{
21    header("Location: /");
22    exit;
23}
24

六、通过Email显示用户的Gravatar头像


1
2
3
1$gravatar_link = 'http://www.gravatar.com/avatar/' . md5($comment_author_email) . '?s=32';
2echo '<img src="' . $gravatar_link . '" />';
3

七、通过cURL获取RSS订阅数


1
2
3
4
5
6
7
8
1$ch = curl_init();
2curl_setopt($ch,CURLOPT_URL,'https://feedburner.google.com/api/awareness/1.0/GetFeedData?id=7qkrmib4r9rscbplq5qgadiiq4');
3curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
4curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,2);
5$content = curl_exec($ch);
6$subscribers = get_match('/circulation="(.*)"/isU',$content);
7curl_close($ch);
8

八、时间差异计算函数


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
1function ago($time)
2{
3    $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
4    $lengths = array("60","60","24","7","4.35","12","10");
5    $now = time();
6    $difference = $now - $time;
7    $tense = "ago";
8    for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
9        $difference /= $lengths[$j];
10    }
11    $difference = round($difference);
12    if($difference != 1) {
13        $periods[$j].= "s";
14    }
15    return "$difference $periods[$j] 'ago' ";
16}
17

九、裁剪图片


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
1$filename= "test.jpg";
2list($w, $h, $type, $attr) = getimagesize($filename);
3$src_im = imagecreatefromjpeg($filename);
4
5$src_x = '0'; // begin x
6$src_y = '0'; // begin y
7$src_w = '100'; // width
8$src_h = '100'; // height
9$dst_x = '0'; // destination x
10$dst_y = '0'; // destination y
11
12$dst_im = imagecreatetruecolor($src_w, $src_h);
13$white = imagecolorallocate($dst_im, 255, 255, 255);
14imagefill($dst_im, 0, 0, $white);
15
16imagecopy($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h);
17
18header("Content-type: image/png");
19imagepng($dst_im);
20imagedestroy($dst_im);
21

十、检查网站是否宕机


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
1function Visit($url){
2    $agent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";$ch=curl_init();
3    curl_setopt ($ch, CURLOPT_URL,$url );
4    curl_setopt($ch, CURLOPT_USERAGENT, $agent);
5    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
6    curl_setopt ($ch,CURLOPT_VERBOSE,false);
7    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
8    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, FALSE);
9    curl_setopt($ch,CURLOPT_SSLVERSION,3);
10    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, FALSE);
11    $page=curl_exec($ch);
12    //echo curl_error($ch);
13    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
14    curl_close($ch);
15    if($httpcode>=200 && $httpcode<300) return true;
16    else return false;
17}
18if (Visit("http://www.google.com"))
19    echo "Website OK"."n";
20else
21    echo "Website DOWN";
22

给TA打赏
共{{data.count}}人
人已打赏
安全技术

c++ vector

2022-1-11 12:36:11

安全漏洞

Chrome更新项目发布 修复Gears高危漏洞

2008-12-3 11:12:22

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索