设为首页 收藏本站
查看: 266|回复: 0

[经验分享] 十个超级有用的PHP代码片段

[复制链接]

尚未签到

发表于 2017-4-3 09:53:09 | 显示全部楼层 |阅读模式
  1. 发送短信
  调用 TextMagic API。



01// Include the TextMagic PHP lib
02require('textmagic-sms-api-php/TextMagicAPI.php');

03

04// Set the username and password information

05$username = 'myusername';

06$password = 'mypassword';

07

08// Create a new instance of TM

09$router = new TextMagicAPI(array(

10'username'=> $username,

11'password'=> $password

12));

13

14// Send a text message to '999-123-4567'

15$result = $router->send('Wake up!',array(9991234567), true);

16

17// result: Result is: Array ( [messages] => Array ( [19896128] => 9991234567 ) [sent_text] => Wake up! [parts_count] => 1 )



  2. 根据IP查找地址



01function detect_city($ip) {

02

03$default= 'UNKNOWN';

04

05if(!is_string($ip) ||strlen($ip) < 1 ||$ip == '127.0.0.1'|| $ip == 'localhost')

06$ip= '8.8.8.8';

07

08$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)';

09

10$url= 'http://ipinfodb.com/ip_locator.php?ip='. urlencode($ip);

11$ch= curl_init();

12

13$curl_opt= array(

14CURLOPT_FOLLOWLOCATION => 1,

15CURLOPT_HEADER => 0,

16CURLOPT_RETURNTRANSFER => 1,

17CURLOPT_USERAGENT =>$curlopt_useragent,

18CURLOPT_URL =>$url,

19CURLOPT_TIMEOUT => 1,

20CURLOPT_REFERER =>'http://' . $_SERVER['HTTP_HOST'],

21);

22

23curl_setopt_array($ch,$curl_opt);

24

25$content= curl_exec($ch);

26

27if(!is_null($curl_info)) {

28$curl_info= curl_getinfo($ch);

29}

30

31curl_close($ch);

32

33if( preg_match('{<li>City : ([^<]*)</li>}i',$content, $regs) ) {

34$city= $regs[1];

35}

36if( preg_match('{<li>State/Province : ([^<]*)</li>}i',$content, $regs) ) {

37$state= $regs[1];

38}

39

40if($city!=''&& $state!=''){

41$location= $city . ', ' . $state;

42return$location;

43}else{

44return$default;

45}

46

47}



  3. 显示网页的源代码



1<?php // display source code

2$lines = file('http://google.com/');

3foreach ($lines as$line_num => $line) {

4// loop thru each line and prepend line numbers

5echo"Line #<b>{$line_num}</b> : " . htmlspecialchars($line) ."<br>\n";

6}



  4. 检查服务器是否使用HTTPS



1if ($_SERVER['HTTPS'] !="on") {

2echo"This is not HTTPS";

3}else{

4echo"This is HTTPS";

5}



  5. 显示Faceboo丝数量



1function fb_fan_count($facebook_name){

2// Example: https://graph.facebook.com/digimantra

3$data= json_decode(file_get_contents("https://graph.facebook.com/".$facebook_name));

4echo$data->likes;

5}



  6. 检测图片的主要颜色



01$i = imagecreatefromjpeg("image.jpg");

02

03for ($x=0;$x<imagesx($i);$x++){

04for($y=0;$y<imagesy($i);$y++){

05$rgb= imagecolorat($i,$x,$y);

06$r= ($rgb >> 16) & 0xFF;

07$g= ($rgb >> & 0xFF;

08$b= $rgb & 0xFF;

09

10$rTotal+= $r;

11$gTotal+= $g;

12$bTotal+= $b;

13$total++;

14}

15}

16

17$rAverage = round($rTotal/$total);

18$gAverage = round($gTotal/$total);

19$bAverage = round($bTotal/$total);



  7. 获取内存使用信息



01echo "Initial: ".memory_get_usage()." bytes \n";

02/* prints

03Initial: 361400 bytes

04*/

05

06// let's use up some memory

07for ($i = 0; $i < 100000; $i++) {

08$array[]= md5($i);

09}

10

11// let's remove half of the array

12for ($i = 0; $i < 100000; $i++) {

13unset($array[$i]);

14}

15

16echo "Final: ".memory_get_usage()." bytes \n";

17/* prints

18Final: 885912 bytes

19*/

20

21echo "Peak: ".memory_get_peak_usage()." bytes \n";

22/* prints

23Peak: 13687072 bytes

24*/



  8. 使用 gzcompress() 压缩数据
01$string =

02"Lorem ipsum dolor sit amet, consectetur

03adipiscing elit. Nunc ut elit id mi ultricies

04adipiscing. Nulla facilisi. Praesent pulvinar,

05sapien vel feugiat vestibulum, nulla dui pretium orci,

06non ultricies elit lacus quis ante. Lorem ipsum dolor

07sit amet, consectetur adipiscing elit. Aliquam

08pretium ullamcorper urna quis iaculis. Etiam ac massa

09sed turpis tempor luctus. Curabitur sed nibh eu elit

10mollis congue. Praesent ipsum diam, consectetur vitae

11ornare a, aliquam a nunc. In id magna pellentesque

12tellus posuere adipiscing. Sed non mi metus, at lacinia

13augue. Sed magna nisi, ornare in mollis in, mollis

14sed nunc. Etiam at justo in leo congue mollis.

15Nullam in neque eget metus hendrerit scelerisque

16eu non enim. Ut malesuada lacus eu nulla bibendum

17id euismod urna sodales. ";

18

19$compressed = gzcompress($string);

20

21echo "Original size: ". strlen($string)."\n";

22/* prints

23Original size: 800

24*/

25

26echo "Compressed size: ". strlen($compressed)."\n";

27/* prints

28Compressed size: 418

29*/

30

31// getting it back

32$original = gzuncompress($compressed);



  9. 使用PHP做Whois检查



01function whois_query($domain) {

02

03// fix the domain name:

04$domain= strtolower(trim($domain));

05$domain= preg_replace('/^http:\/\//i','', $domain);

06$domain= preg_replace('/^www\./i','', $domain);

07$domain= explode('/',$domain);

08$domain= trim($domain[0]);

09

10// split the TLD from domain name

11$_domain= explode('.',$domain);

12$lst= count($_domain)-1;

13$ext= $_domain[$lst];

14

15// You find resources and lists

16// like these on wikipedia:

17//

18// http://de.wikipedia.org/wiki/Whois

19//

20$servers= array(

21"biz"=> "whois.neulevel.biz",

22"com"=> "whois.internic.net",

23"us"=> "whois.nic.us",

24"coop"=> "whois.nic.coop",

25"info"=> "whois.nic.info",

26"name"=> "whois.nic.name",

27"net"=> "whois.internic.net",

28"gov"=> "whois.nic.gov",

29"edu"=> "whois.internic.net",

30"mil"=> "rs.internic.net",

31"int"=> "whois.iana.org",

32"ac"=> "whois.nic.ac",

33"ae"=> "whois.uaenic.ae",

34"at"=> "whois.ripe.net",

35"au"=> "whois.aunic.net",

36"be"=> "whois.dns.be",

37"bg"=> "whois.ripe.net",

38"br"=> "whois.registro.br",

39"bz"=> "whois.belizenic.bz",

40"ca"=> "whois.cira.ca",

41"cc"=> "whois.nic.cc",

42"ch"=> "whois.nic.ch",

43"cl"=> "whois.nic.cl",

44"cn"=> "whois.cnnic.net.cn",

45"cz"=> "whois.nic.cz",

46"de"=> "whois.nic.de",

47"fr"=> "whois.nic.fr",

48"hu"=> "whois.nic.hu",

49"ie"=> "whois.domainregistry.ie",

50"il"=> "whois.isoc.org.il",

51"in"=> "whois.ncst.ernet.in",

52"ir"=> "whois.nic.ir",

53"mc"=> "whois.ripe.net",

54"to"=> "whois.tonic.to",

55"tv"=> "whois.tv",

56"ru"=> "whois.ripn.net",

57"org"=> "whois.pir.org",

58"aero"=> "whois.information.aero",

59"nl"=> "whois.domain-registry.nl"

60);

61

62if(!isset($servers[$ext])){

63die('Error: No matching nic server found!');

64}

65

66$nic_server= $servers[$ext];

67

68$output= '';

69

70// connect to whois server:

71if($conn = fsockopen ($nic_server, 43)) {

72fputs($conn,$domain."\r\n");

73while(!feof($conn)){

74$output.= fgets($conn,128);

75}

76fclose($conn);

77}

78else{ die('Error: Could not connect to '. $nic_server . '!'); }

79

80return$output;

81}



  10. 通过Email发送PHP错误



01<?php

02

03// Our custom error handler

04function nettuts_error_handler($number,$message, $file, $line,$vars){

05$email= "

06<p>An error ($number) occurred on line

07<strong>$line</strong>and in the <strong>file:$file.</strong>

08<p>$message </p>";

09

10$email.= "<pre>" . print_r($vars, 1) ."</pre>";

11

12$headers= 'Content-type: text/html; charset=iso-8859-1'. "\r\n";

13

14// Email the error to someone...

15error_log($email, 1,'you@youremail.com',$headers);

16

17// Make sure that you decide how to respond to errors (on the user's side)

18// Either echo an error message, or kill the entire project. Up to you...

19// The code below ensures that we only "die" if the error was more than

20// just a NOTICE.

21if( ($number !== E_NOTICE) && ($number < 2048) ) {

22die("There was an error. Please try again later.");

23}

24}

25

26// We should use our custom function to handle errors.

27set_error_handler('nettuts_error_handler');

28

29// Trigger an error... (var doesn't exist)

30echo $somevarthatdoesnotexist;



  原文地址:

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-359433-1-1.html 上篇帖子: 从一道php面试题说起 下篇帖子: 基于PHP的聊天室编程思想
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表