当前位置:Gxlcms > PHP教程 > 46个非常有用的PHP代码片段(二)

46个非常有用的PHP代码片段(二)

时间:2021-07-01 10:21:17 帮助过:3人阅读

16. 解压文件[代码]php代码:

  1. function unzip($location,$newLocation)
  2. {
  3. if(exec("unzip $location",$arr)){
  4. mkdir($newLocation);
  5. for($i = 1;$i< count($arr);$i++){
  6. $file = trim(preg_replace("~inflating: ~","",$arr[$i]));
  7. copy($location.'/'.$file,$newLocation.'/'.$file);
  8. unlink($location.'/'.$file);
  9. }
  10. return TRUE;
  11. }else{
  12. return FALSE;
  13. }
  14. }

语法:

<?php

unzip('test.zip','unziped/test'); //File would be unzipped in unziped/test folder

?>

17. 缩放图片

[代码]php代码:

  1. function resize_image($filename, $tmpname, $xmax, $ymax)
  2. {
  3. $ext = explode(".", $filename);
  4. $ext = $ext[count($ext)-1];
  5. if($ext == "jpg" || $ext == "jpeg")
  6. $im = imagecreatefromjpeg($tmpname);
  7. elseif($ext == "png")
  8. $im = imagecreatefrompng($tmpname);
  9. elseif($ext == "gif")
  10. $im = imagecreatefromgif($tmpname);
  11. $x = imagesx($im);
  12. $y = imagesy($im);
  13. if($x <= $xmax && $y <= $ymax)
  14. return $im;
  15. if($x >= $y) {
  16. $newx = $xmax;
  17. $newy = $newx * $y / $x;
  18. }
  19. else {
  20. $newy = $ymax;
  21. $newx = $x / $y * $newy;
  22. }
  23. $im2 = imagecreatetruecolor($newx, $newy);
  24. imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);
  25. return $im2;
  26. }

18. 使用 mail() 发送邮件

之前我们提供了如何使用 Mandrill 发送邮件的 PHP 代码片段,但是如果你不想使用第三方服务,那么可以使用下面的 PHP 代码片段。

[代码]php代码:

  1. function send_mail($to,$subject,$body)
  2. {
  3. $headers = "From: KOONK\r\n";
  4. $headers .= "Reply-To: blog@koonk.com\r\n";
  5. $headers .= "Return-Path: blog@koonk.com\r\n";
  6. $headers .= "X-Mailer: PHP5\n";
  7. $headers .= 'MIME-Version: 1.0' . "\n";
  8. $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
  9. mail($to,$subject,$body,$headers);
  10. }

语法:

<?php

$to = "admin@koonk.com";

$subject = "This is a test mail";

$body = "Hello World!";

send_mail($to,$subject,$body);

?>

19. 把秒转换成天数,小时数和分钟

[代码]php代码:

  1. function secsToStr($secs) {
  2. if($secs>=86400){$days=floor($secs/86400);$secs=$secs%86400;$r=$days.' day';if($days<>1){$r.='s';}if($secs>0){$r.=', ';}}
  3. if($secs>=3600){$hours=floor($secs/3600);$secs=$secs%3600;$r.=$hours.' hour';if($hours<>1){$r.='s';}if($secs>0){$r.=', ';}}
  4. if($secs>=60){$minutes=floor($secs/60);$secs=$secs%60;$r.=$minutes.' minute';if($minutes<>1){$r.='s';}if($secs>0){$r.=', ';}}
  5. $r.=$secs.' second';if($secs<>1){$r.='s';}
  6. return $r;
  7. }

语法:

<?php

$seconds = "56789";

$output = secsToStr($seconds);

echo $output;

?>

20. 数据库连接

  1. <?php
  2. $DBNAME = 'koonk';
  3. $HOST = 'localhost';
  4. $DBUSER = 'root';
  5. $DBPASS = 'koonk';
  6. $CONNECT = mysql_connect($HOST,$DBUSER,$DBPASS);
  7. if(!$CONNECT)
  8. {
  9. echo 'MySQL Error: '.mysql_error();
  10. }
  11. $SELECT = mysql_select_db($DBNAME);
  12. if(!$SELECT)
  13. {
  14. echo 'MySQL Error: '.mysql_error();
  15. }
  16. ?>

21. 目录清单

使用下面的 PHP 代码片段可以在一个目录中列出所有文件和文件夹

[代码]php代码:

  1. function list_files($dir)
  2. {
  3. if(is_dir($dir))
  4. {
  5. if($handle = opendir($dir))
  6. {
  7. while(($file = readdir($handle)) !== false)
  8. {
  9. if($file != "." && $file != ".." && $file != "Thumbs.db"/*pesky windows, images..*/)
  10. {
  11. echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a><br>'."\n";
  12. }
  13. }
  14. closedir($handle);
  15. }
  16. }
  17. }

语法:

<?php

list_files("images/"); //This will list all files of images folder

?>

22. 检测用户语言

使用下面的 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. }

23. 查看 CSV 文件

[代码]php代码:

  1. function readCSV($csvFile){
  2. $file_handle = fopen($csvFile, 'r');
  3. while (!feof($file_handle) ) {
  4. $line_of_text[] = fgetcsv($file_handle, 1024);
  5. }
  6. fclose($file_handle);
  7. return $line_of_text;
  8. }

语法:

<?php

$csvFile = "test.csv";

$csv = readCSV($csvFile);

$a = csv[0][0]; // This will get value of Column 1 & Row 1

?>

24. 从 PHP 数据创建 CSV 文件

[代码]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

$data[0] = "apple";

$data[1] = "oranges";

generateCsv($data, $delimiter = ',', $enclosure = '"');

?>

25. 解析 XML 数据

[代码]php代码:

  1. $xml_string="<!--?xml version='1.0'?-->
  2. <moleculedb>
  3. <molecule name="Benzine">
  4. <symbol>ben</symbol>
  5. <code>A</code>
  6. </molecule>
  7. <molecule name="Water">
  8. <symbol>h2o</symbol>
  9. <code>K</code>
  10. </molecule>
  11. </moleculedb>";
  12. //load the xml string using <a href="http://www.php-z.com/" target="_blank" class="relatedlink">Simple</a>xml function
  13. $xml = simplexml_load_string($xml_string);
  14. //loop through the each node of molecule
  15. foreach ($xml->molecule as $record)
  16. {
  17. //attribute are accessted by
  18. echo $record['name'], ' ';
  19. //node are accessted by -> operator
  20. echo $record->symbol, ' ';
  21. echo $record->code, '<br>';
  22. }

26. 解析 JSON 数据

[代码]php代码:

  1. $json_string='{"id":1,"name":"rolf","country":"russia","office":["google","oracle"]} ';
  2. $obj=json_decode($json_string);
  3. //print the parsed data
  4. echo $obj->name; //displays rolf
  5. echo $obj->office[0]; //displays google

27. 获取当前页面 URL

这个 PHP 片段可以帮助你让用户登录后直接跳转到之前浏览的页面

[代码]php代码:

  1. function current_url()
  2. {
  3. $url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
  4. $validURL = str_replace("&", "&", $url);
  5. return validURL;
  6. }

语法:

<?php

echo "Currently you are on: ".current_url();

?>

28. 从任意的 Twitter 账号获取最新的 Tweet

[代码]php代码:

  1. function my_twitter($username)
  2. {
  3. $no_of_tweets = 1;
  4. $feed = "http://search.twitter.com/search.atom?q=from:" . $username . "&rpp=" . $no_of_tweets;
  5. $xml = simplexml_load_file($feed);
  6. foreach($xml->children() as $child) {
  7. foreach ($child as $value) {
  8. if($value->getName() == "link") $link = $value['href'];
  9. if($value->getName() == "content") {
  10. $content = $value . "";
  11. echo '<p class="twit">'.$content.' <a class="twt" href="'.$link.'" title=""> </a></p>';
  12. }
  13. }
  14. }
  15. }

语法:

<?php

$handle = "koonktech";

my_twitter($handle);

?>

29. 转发数量

使用这个 PHP 片段可以检测你的页面 URL 有多少转发数量

[代码]php代码:

  1. function tweetCount($url) {
  2. $content = file_get_contents("http://api.tweetmeme.com/url_info?url=".$url);
  3. $element = new SimpleXmlElement($content);
  4. $retweets = $element->story->url_count;
  5. if($retweets){
  6. return $retweets;
  7. } else {
  8. return 0;
  9. }
  10. }

语法:

<?php

$url = "http://blog.koonk.com";

$count = tweetCount($url);

return $count;

?>

30. 计算两个日期的差

[代码]php代码:

  1. <!--?php
  2. $date1 = date( 'Y-m-d' );
  3. $date2 = "2015-12-04";
  4. $diff = abs(strtotime($date2) - strtotime($date1));
  5. $years = floor($diff / (365*60*60*24));
  6. $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
  7. $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
  8. printf("%d years, %d months, %d days\n", $years, $months, $days);
  9. -------------------------------------------------------- OR
  10. $date1 = new DateTime("2007-03-24");
  11. $date2 = new DateTime("2009-06-26");
  12. $interval = $date1--->diff($date2);
  13. echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";
  14. // shows the total amount of days (not divided into years, months and days like above)
  15. echo "difference " . $interval->days . " days ";
  16. -------------------------------------------------------- OR
  17. /**
  18. * Calculate differences between two dates with precise semantics. <a href="http://www.php-z.com/" target="_blank" class="relatedlink">Base</a>d on PHPs DateTime::diff()
  19. * implementation by Derick Rethans. Ported to PHP by Emil H, 2011-05-02. No rights reserved.
  20. *
  21. * See here for original code:
  22. * http://svn.php.com/viewvc/php/php-src/trunk/ext/date/lib/tm2unixtime.c?revision=302890&view=markup
  23. * http://svn.php.com/viewvc/php/php-src/trunk/ext/date/lib/interval.c?revision=298973&view=markup
  24. */
  25. function _date_range_limit($start, $end, $adj, $a, $b, $result)
  26. {
  27. if ($result[$a] < $start) {
  28. $result[$b] -= intval(($start - $result[$a] - 1) / $adj) + 1;
  29. $result[$a] += $adj * intval(($start - $result[$a] - 1) / $adj + 1);
  30. }
  31. if ($result[$a] >= $end) {
  32. $result[$b] += intval($result[$a] / $adj);
  33. $result[$a] -= $adj * intval($result[$a] / $adj);
  34. }
  35. return $result;
  36. }
  37. function _date_range_limit_days($base, $result)
  38. {
  39. $days_in_month_leap = array(31, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
  40. $days_in_month = array(31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
  41. _date_range_limit(1, 13, 12, "m", "y", &$base);
  42. $year = $base["y"];
  43. $month = $base["m"];
  44. if (!$result["invert"]) {
  45. while ($result["d"] < 0) {
  46. $month--;
  47. if ($month < 1) {
  48. $month += 12;
  49. $year--;
  50. }
  51. $leapyear = $year % 400 == 0 || ($year % 100 != 0 && $year % 4 == 0);
  52. $days = $leapyear ? $days_in_month_leap[$month] : $days_in_month[$month];
  53. $result["d"] += $days;
  54. $result["m"]--;
  55. }
  56. } else {
  57. while ($result["d"] < 0) {
  58. $leapyear = $year % 400 == 0 || ($year % 100 != 0 && $year % 4 == 0);
  59. $days = $leapyear ? $days_in_month_leap[$month] : $days_in_month[$month];
  60. $result["d"] += $days;
  61. $result["m"]--;
  62. $month++;
  63. if ($month > 12) {
  64. $month -= 12;
  65. $year++;
  66. }
  67. }
  68. }
  69. return $result;
  70. }
  71. function _date_normalize($base, $result)
  72. {
  73. $result = _date_range_limit(0, 60, 60, "s", "i", $result);
  74. $result = _date_range_limit(0, 60, 60, "i", "h", $result);
  75. $result = _date_range_limit(0, 24, 24, "h", "d", $result);
  76. $result = _date_range_limit(0, 12, 12, "m", "y", $result);
  77. $result = _date_range_limit_days(&$base, &$result);
  78. $result = _date_range_limit(0, 12, 12, "m", "y", $result);
  79. return $result;
  80. }
  81. /**
  82. * Accepts two unix timestamps.
  83. */
  84. function _date_diff($one, $two)
  85. {
  86. $invert = false;
  87. if ($one > $two) {
  88. list($one, $two) = array($two, $one);
  89. $invert = true;
  90. }
  91. $key = array("y", "m", "d", "h", "i", "s");
  92. $a = array_combine($key, array_map("intval", explode(" ", date("Y m d H i s", $one))));
  93. $b = array_combine($key, array_map("intval", explode(" ", date("Y m d H i s", $two))));
  94. $result = array();
  95. $result["y"] = $b["y"] - $a["y"];
  96. $result["m"] = $b["m"] - $a["m"];
  97. $result["d"] = $b["d"] - $a["d"];
  98. $result["h"] = $b["h"] - $a["h"];
  99. $result["i"] = $b["i"] - $a["i"];
  100. $result["s"] = $b["s"] - $a["s"];
  101. $result["invert"] = $invert ? 1 : 0;
  102. $result["days"] = intval(abs(($one - $two)/86400));
  103. if ($invert) {
  104. _date_normalize(&$a, &$result);
  105. } else {
  106. _date_normalize(&$b, &$result);
  107. }
  108. return $result;
  109. }
  110. $date = "2014-12-04 19:37:22";
  111. echo '<pre>';
  112. print_r( _date_diff( strtotime($date), time() ) );
  113. echo '</pre>';
  114. ?>

以上就是46 个非常有用的 PHP 代码片段(二)的内容,更多相关内容请关注PHP中文网(www.gxlcms.com)!

人气教程排行