欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

九个超实用的PHP代码片段

程序员文章站 2024-02-08 09:36:28
...

每位程序员和开发者都喜欢讨论他们最爱的代码片段,尤其是当PHP开发者花费数个小时为网页编码或创建应用时,他们更知道这些代码的重要性。为了节约编码时间,笔者收集了一些较为实用的代码片段,帮助开发者提高工作效率。点击查看PHP代码片段(一) 1)Whois

每位程序员和开发者都喜欢讨论他们最爱的代码片段,尤其是当PHP开发者花费数个小时为网页编码或创建应用时,他们更知道这些代码的重要性。为了节约编码时间,笔者收集了一些较为实用的代码片段,帮助开发者提高工作效率。>>> 点击查看PHP代码片段(一)

九个超实用的PHP代码片段

1) Whois query using PHP ——利用PHP获取Whois请求

利用这段代码,在特定的域名里可获得whois信息。把域名名称作为参数,并显示所有域名的相关信息。

[js] view plaincopy九个超实用的PHP代码片段九个超实用的PHP代码片段

  1. function whois_query($domain) {
  2. // fix the domain name:
  3. $domain = strtolower(trim($domain));
  4. $domain = preg_replace('/^http:\/\//i', '', $domain);
  5. $domain = preg_replace('/^www\./i', '', $domain);
  6. $domain = explode('/', $domain);
  7. $domain = trim($domain[0]);
  8. // split the TLD from domain name
  9. $_domain = explode('.', $domain);
  10. $lst = count($_domain)-1;
  11. $ext = $_domain[$lst];
  12. // You find resources and lists
  13. // like these on wikipedia:
  14. //
  15. // http://de.wikipedia.org/wiki/Whois
  16. //
  17. $servers = array(
  18. "biz" => "whois.neulevel.biz",
  19. "com" => "whois.internic.net",
  20. "us" => "whois.nic.us",
  21. "coop" => "whois.nic.coop",
  22. "info" => "whois.nic.info",
  23. "name" => "whois.nic.name",
  24. "net" => "whois.internic.net",
  25. "gov" => "whois.nic.gov",
  26. "edu" => "whois.internic.net",
  27. "mil" => "rs.internic.net",
  28. "int" => "whois.iana.org",
  29. "ac" => "whois.nic.ac",
  30. "ae" => "whois.uaenic.ae",
  31. "at" => "whois.ripe.net",
  32. "au" => "whois.aunic.net",
  33. "be" => "whois.dns.be",
  34. "bg" => "whois.ripe.net",
  35. "br" => "whois.registro.br",
  36. "bz" => "whois.belizenic.bz",
  37. "ca" => "whois.cira.ca",
  38. "cc" => "whois.nic.cc",
  39. "ch" => "whois.nic.ch",
  40. "cl" => "whois.nic.cl",
  41. "cn" => "whois.cnnic.net.cn",
  42. "cz" => "whois.nic.cz",
  43. "de" => "whois.nic.de",
  44. "fr" => "whois.nic.fr",
  45. "hu" => "whois.nic.hu",
  46. "ie" => "whois.domainregistry.ie",
  47. "il" => "whois.isoc.org.il",
  48. "in" => "whois.ncst.ernet.in",
  49. "ir" => "whois.nic.ir",
  50. "mc" => "whois.ripe.net",
  51. "to" => "whois.tonic.to",
  52. "tv" => "whois.tv",
  53. "ru" => "whois.ripn.net",
  54. "org" => "whois.pir.org",
  55. "aero" => "whois.information.aero",
  56. "nl" => "whois.domain-registry.nl"
  57. );
  58. if (!isset($servers[$ext])){
  59. die('Error: No matching nic server found!');
  60. }
  61. $nic_server = $servers[$ext];
  62. $output = '';
  63. // connect to whois server:
  64. if ($conn = fsockopen ($nic_server, 43)) {
  65. fputs($conn, $domain."\r\n");
  66. while(!feof($conn)) {
  67. $output .= fgets($conn,128);
  68. }
  69. fclose($conn);
  70. }
  71. else { die('Error: Could not connect to ' . $nic_server . '!'); }
  72. return $output;
  73. }

2) Text messaging with PHP using the TextMagic API ——使用TextMagic API 获取PHP Test信息

TextMagic引入强大的核心API,可轻松将SMS发送到手机。该API是需要付费。

[js] view plaincopy九个超实用的PHP代码片段九个超实用的PHP代码片段

  1. the TextMagic PHP lib
  2. require('textmagic-sms-api-php/TextMagicAPI.php');
  3. // Set the username and password information
  4. $username = 'myusername';
  5. $password = 'mypassword';
  6. // Create a new instance of TM
  7. $router = new TextMagicAPI(array(
  8. 'username' => $username,
  9. 'password' => $password
  10. ));
  11. // Send a text message to '999-123-4567'
  12. $result = $router->send('Wake up!', array(9991234567), true);
  13. // result: Result is: Array ( [messages] => Array ( [19896128] => 9991234567 ) [sent_text] => Wake up! [parts_count] => 1 )

3) Get info about your memory usage——获取内存使用率

这段代码帮助你获取内存使用率。

[js] view plaincopy九个超实用的PHP代码片段九个超实用的PHP代码片段

  1. echo "Initial: ".memory_get_usage()." bytes \n";
  2. /* prints
  3. Initial: 361400 bytes
  4. */
  5. // let's use up some memory
  6. for ($i = 0; $i
  7. $array []= md5($i);
  8. }
  9. // let's remove half of the array
  10. for ($i = 0; $i
  11. unset($array[$i]);
  12. }
  13. echo "Final: ".memory_get_usage()." bytes \n";
  14. /* prints
  15. Final: 885912 bytes
  16. */
  17. echo "Peak: ".memory_get_peak_usage()." bytes \n";
  18. /* prints
  19. Peak: 13687072 bytes
  20. */

4) Display source code of any webpage——查看任意网页源代码

如果你想查看网页源代码,那么只需更改第二行的URL,源代码就会在网页上显示出。

[js] view plaincopy九个超实用的PHP代码片段九个超实用的PHP代码片段

  1. // display source code $lines = file('http://google.com/'); foreach ($lines as $line_num => $line) {
  2. // loop thru each line and prepend line numbers
  3. echo "Line #{$line_num} : " . htmlspecialchars($line) . "
  4. \n";
  5. }

5) Create data uri’s——创建数据uri

通过使用此代码,你可以创建数据Uri,这对在HTML/CSS中嵌入图片非常有用,可帮助节省HTTP请求。

[js] view plaincopy九个超实用的PHP代码片段九个超实用的PHP代码片段

  1. function data_uri($file, $mime) {
  2. $contents=file_get_contents($file);
  3. $base64=base64_encode($contents);
  4. echo "data:$mime;base64,$base64";
  5. }

6) Detect location by IP——通过IP检索出地理位置

这段代码帮助你查找特定的IP,只需在功能参数上输入IP,就可检测出位置。

[js] view plaincopy九个超实用的PHP代码片段九个超实用的PHP代码片段

  1. function detect_city($ip) {
  2. $default = 'UNKNOWN';
  3. if (!is_string($ip) || strlen($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,
  4. CURLOPT_HEADER => 0,
  5. CURLOPT_RETURNTRANSFER => 1,
  6. CURLOPT_USERAGENT => $curlopt_useragent,
  7. CURLOPT_URL => $url,
  8. CURLOPT_TIMEOUT => 1,
  9. CURLOPT_REFERER => 'http://' . $_SERVER['HTTP_HOST'],
  10. );
  11. curl_setopt_array($ch, $curl_opt);
  12. $content = curl_exec($ch);
  13. if (!is_null($curl_info)) {
  14. $curl_info = curl_getinfo($ch);
  15. }
  16. curl_close($ch);
  17. if ( preg_match('{
  18. City : ([^
  19. }i’, $content, $regs) ) { $city = $regs[1]; } if ( preg_match(‘{
  20. State/Province : ([^
  21. }i’, $content, $regs) ) { $state = $regs[1]; } if( $city!=” && $state!=” ){ $location = $city . ‘, ‘ . $state; return $location; }else{ return $default; } }

7) Detect browser language——查看浏览器语言

检测浏览器使用的代码脚本语言。

[js] view plaincopy九个超实用的PHP代码片段九个超实用的PHP代码片段

  1. function get_client_language($availableLanguages, $default='en'){
  2. if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
  3. $langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
  4. foreach ($langs as $value){
  5. $choice=substr($value,0,2);
  6. if(in_array($choice, $availableLanguages)){
  7. return $choice;
  8. }
  9. }
  10. }
  11. return $default;
  12. }

8) Check if server is HTTPS——检测服务器是否是HTTPS

[js] view plaincopy九个超实用的PHP代码片段九个超实用的PHP代码片段

  1. if ($_SERVER['HTTPS'] != "on") {
  2. echo "This is not HTTPS";
  3. }else{
  4. echo "This is HTTPS";
  5. }

9) Generate CSV file from a PHP array——在PHP数组中生成.csv 文件

[js] view plaincopy九个超实用的PHP代码片段九个超实用的PHP代码片段

  1. function generateCsv($data, $delimiter = ',', $enclosure = '"') {
  2. $handle = fopen('php://temp', 'r+');
  3. foreach ($data as $line) {
  4. fputcsv($handle, $line, $delimiter, $enclosure);
  5. }
  6. rewind($handle);
  7. while (!feof($handle)) {
  8. $contents .= fread($handle, 8192);
  9. }
  10. fclose($handle);
  11. return $contents;
  12. }
九个超实用的PHP代码片段